/* global React, Icon, TotemLogo, NumericKeypad, DniDisplay, ActionCard,
   AppointmentCard, LabOrderCard, Tag, StepHeader, Modal, tt, totemDateLocale, totemMarket, totemFormatMoney, totemProfile, jsQR */

function isPharmacy() {
  return typeof totemProfile !== 'undefined' && totemProfile === 'pharmacy';
}
function isLab() {
  return typeof totemProfile !== 'undefined' && totemProfile === 'lab';
}
function isHospital() {
  return typeof totemProfile !== 'undefined' && totemProfile === 'hospital';
}
function isDental() {
  return typeof totemProfile !== 'undefined' && totemProfile === 'dental';
}
function vert(phKey, labKey, clinicKey, hospKey, odKey, vars) {
  var v = vars;
  var hosp = clinicKey;
  var od = clinicKey;
  if (typeof hospKey === 'string') hosp = hospKey;
  else if (hospKey) v = hospKey;
  if (typeof odKey === 'string') od = odKey;
  else if (odKey) v = odKey;
  if (isPharmacy()) return tt(phKey, v);
  if (isLab()) return tt(labKey, v);
  if (isHospital()) return tt(hosp, v);
  if (isDental()) return tt(od, v);
  return tt(clinicKey, v);
}
const { useState: uS, useEffect: uE, useRef: uR, useMemo: uM } = React;

// =================== IDLE / WELCOME ===================
function ScreenIdle({ org, theme, onStart }) {
  const [time, setTime] = uS(new Date());
  uE(() => {
    const t = setInterval(() => setTime(new Date()), 1000 * 30);
    return () => clearInterval(t);
  }, []);
  const dl = (typeof totemDateLocale !== 'undefined' ? totemDateLocale : 'es-AR');
  const dayName = time.toLocaleDateString(dl, { weekday: 'long' });
  const monthDay = time.toLocaleDateString(dl, { day: 'numeric', month: 'long' });
  const hh = time.toLocaleTimeString(dl, { hour: '2-digit', minute: '2-digit' });

  return (
    <div className="idle fade-in" onClick={onStart}>
      <div className="idle-bg-glow" />
      <div className="idle-content">
        <div className="idle-eyebrow">
          <span className="idle-dot" /> {tt('idle.service')}
        </div>
        <h1 className="idle-title">{tt('idle.welcome')}<br /><span className="idle-org">{org.name}</span></h1>
        <div className="idle-sub">{vert('ph.idle.sub', 'labp.idle.sub', 'idle.sub', 'hosp.idle.sub', 'od.idle.sub')}</div>

        <div className="idle-tap">
          <div className="idle-tap-hand">
            <Icon name="spark" size={32} />
          </div>
          <div className="idle-tap-text">{tt('idle.tap')}</div>
        </div>

        <div className="idle-clock">
          <div className="idle-time">{hh}</div>
          <div className="idle-date">{dayName}, {monthDay}</div>
        </div>
        <div style={{ marginTop: 28, fontSize: 13, color: '#5A6275', maxWidth: 420 }}>
          {tt('idle.privacy')}{' '}
          <a
            href={tt('consent.link')}
            target="_blank"
            rel="noopener"
            style={{ color: '#5DD3FF' }}
            onClick={(e) => e.stopPropagation()}
          >
            {tt('idle.privacy.link')}
          </a>
        </div>
      </div>

      <style>{`
        .idle {
          flex: 1; min-height: 0;
          position: relative;
          display: grid; place-items: center;
          cursor: pointer;
          overflow: hidden;
          padding: 48px;
        }
        .idle-bg-glow {
          position: absolute; inset: -10%;
          background:
            radial-gradient(600px 600px at 30% 30%, rgba(30,144,255,0.18), transparent 60%),
            radial-gradient(500px 500px at 75% 75%, rgba(93,211,255,0.10), transparent 60%);
          animation: drift 20s ease-in-out infinite alternate;
        }
        @keyframes drift {
          0% { transform: translate(0,0); }
          100% { transform: translate(-20px, 20px); }
        }
        .idle-content {
          position: relative; z-index: 2;
          display: flex; flex-direction: column; align-items: center;
          text-align: center;
        }
        .idle-eyebrow {
          display: inline-flex; align-items: center; gap: 8px;
          padding: 8px 16px;
          background: rgba(76,175,80,0.10);
          border: 1px solid rgba(76,175,80,0.3);
          color: #7DDB85;
          border-radius: 999px;
          font-size: 13px;
          font-weight: 600;
          letter-spacing: 0.08em;
          text-transform: uppercase;
          margin-bottom: 32px;
        }
        .idle-dot {
          width: 8px; height: 8px; border-radius: 50%; background: #4CAF50;
          box-shadow: 0 0 12px #4CAF50;
        }
        .idle-title {
          font-size: 86px;
          font-weight: 800;
          letter-spacing: -0.03em;
          line-height: 0.95;
          margin: 0;
          color: white;
        }
        .idle-org {
          background: linear-gradient(135deg, #5DD3FF 0%, #1E90FF 100%);
          -webkit-background-clip: text;
          background-clip: text;
          color: transparent;
        }
        .idle-sub {
          margin-top: 18px;
          font-size: 22px;
          color: #8A93A6;
          letter-spacing: 0.02em;
        }
        .idle-tap {
          margin-top: 56px;
          display: flex; align-items: center; gap: 16px;
          padding: 14px 26px 14px 14px;
          background: rgba(30,144,255,0.10);
          border: 1px solid rgba(30,144,255,0.4);
          border-radius: 999px;
          animation: float 2.4s ease-in-out infinite;
        }
        @keyframes float {
          0%,100% { transform: translateY(0); }
          50% { transform: translateY(-6px); }
        }
        .idle-tap-hand {
          width: 56px; height: 56px;
          border-radius: 50%;
          background: linear-gradient(135deg, #5DD3FF, #1E90FF);
          color: white;
          display: grid; place-items: center;
          box-shadow: 0 6px 24px rgba(30,144,255,0.5);
        }
        .idle-tap-text {
          font-size: 22px;
          font-weight: 600;
          color: white;
          letter-spacing: 0.01em;
        }
        .idle-clock {
          margin-top: 56px;
          text-align: center;
        }
        .idle-time {
          font-size: 56px;
          font-weight: 300;
          font-variant-numeric: tabular-nums;
          letter-spacing: -0.02em;
          color: white;
        }
        .idle-date {
          font-size: 18px;
          color: #5A6275;
          margin-top: 4px;
          text-transform: capitalize;
        }
      `}</style>
    </div>);

}

// =================== ACTION PICKER ===================
function ScreenActionPicker({ onPick, onBack }) {
  return (
    <div className="screen scale-in">
      <div className="screen-inner">
        <StepHeader step={1} total={5} label={vert('ph.pick.step', 'labp.pick.step', 'pick.step', 'hosp.pick.step', 'od.pick.step')} onCancel={onBack} />
        <h2 className="h-title" style={{ marginTop: 8, marginBottom: 8 }}>{vert('ph.pick.title', 'labp.pick.title', 'pick.title', 'hosp.pick.title', 'od.pick.title')}</h2>
        <p className="h-body" style={{ marginBottom: 36, color: '#8A93A6' }}>{vert('ph.pick.sub', 'labp.pick.sub', 'pick.sub', 'hosp.pick.sub', 'od.pick.sub')}</p>

        <div className="actions-grid">
          {isDental() ? <>
            <ActionCard
              icon="calendar-check"
              title={tt('od.pick.appt.title')}
              subtitle={tt('od.pick.appt.sub')}
              accent="linear-gradient(135deg,#1E90FF,#0066CC)"
              onClick={() => onPick("odappt")} />
            <ActionCard
              icon="alert"
              title={tt('od.pick.urgent.title')}
              subtitle={tt('od.pick.urgent.sub')}
              badge={tt('od.pick.urgent.badge')}
              accent="linear-gradient(135deg,#FF6B6B,#C0392B)"
              onClick={() => onPick("odurgent")} />
            <ActionCard
              icon="spark"
              title={tt('od.pick.hygiene.title')}
              subtitle={tt('od.pick.hygiene.sub')}
              accent="linear-gradient(135deg,#5DD3FF,#3094B4)"
              onClick={() => onPick("odhygiene")} />
          </> : isHospital() ? <>
            <ActionCard
              icon="alert"
              title={tt('hosp.pick.er.title')}
              subtitle={tt('hosp.pick.er.sub')}
              badge={tt('hosp.pick.er.badge')}
              accent="linear-gradient(135deg,#FF6B6B,#C0392B)"
              onClick={() => onPick("er")} />
            <ActionCard
              icon="calendar-check"
              title={tt('hosp.pick.admit.title')}
              subtitle={tt('hosp.pick.admit.sub')}
              accent="linear-gradient(135deg,#1E90FF,#0066CC)"
              onClick={() => onPick("admit")} />
            <ActionCard
              icon="user"
              title={tt('hosp.pick.visit.title')}
              subtitle={tt('hosp.pick.visit.sub')}
              accent="linear-gradient(135deg,#5DD3FF,#3094B4)"
              onClick={() => onPick("visit")} />
          </> : isLab() ? <>
            <ActionCard
              icon="flask"
              title={tt('labp.pick.draw.title')}
              subtitle={tt('labp.pick.draw.sub')}
              badge={tt('labp.pick.draw.badge')}
              accent="linear-gradient(135deg,#1E90FF,#0066CC)"
              onClick={() => onPick("draw")} />
            <ActionCard
              icon="document"
              title={tt('labp.pick.results.title')}
              subtitle={tt('labp.pick.results.sub')}
              accent="linear-gradient(135deg,#5DD3FF,#3094B4)"
              onClick={() => onPick("results")} />
            <ActionCard
              icon="check-circle"
              title={tt('labp.pick.dropoff.title')}
              subtitle={tt('labp.pick.dropoff.sub')}
              accent="linear-gradient(135deg,#FF9248,#FF6B35)"
              onClick={() => onPick("dropoff")} />
          </> : isPharmacy() ? <>
            <ActionCard
              icon="document"
              title={tt('ph.pick.rx.title')}
              subtitle={tt('ph.pick.rx.sub')}
              accent="linear-gradient(135deg,#1E90FF,#0066CC)"
              onClick={() => onPick("rx")} />
            <ActionCard
              icon="check-circle"
              title={tt('ph.pick.pickup.title')}
              subtitle={tt('ph.pick.pickup.sub')}
              accent="linear-gradient(135deg,#5DD3FF,#3094B4)"
              onClick={() => onPick("pickup")} />
            <ActionCard
              icon="spark"
              title={tt('ph.pick.counter.title')}
              subtitle={tt('ph.pick.counter.sub')}
              badge={tt('ph.pick.counter.badge')}
              accent="linear-gradient(135deg,#FF9248,#FF6B35)"
              onClick={() => onPick("counter")} />
          </> : <>
            <ActionCard
              icon="calendar-check"
              title={tt('pick.appt.title')}
              subtitle={tt('pick.appt.sub')}
              accent="linear-gradient(135deg,#1E90FF,#0066CC)"
              onClick={() => onPick("appointment")} />
            <ActionCard
              icon="alert"
              title={tt('pick.walkin.title')}
              subtitle={tt('pick.walkin.sub')}
              badge={tt('pick.walkin.badge')}
              accent="linear-gradient(135deg,#FF9248,#FF6B35)"
              onClick={() => onPick("walkin")} />
            <ActionCard
              icon="flask"
              title={tt('pick.labs.title')}
              subtitle={tt('pick.labs.sub')}
              accent="linear-gradient(135deg,#5DD3FF,#3094B4)"
              onClick={() => onPick("labs")} />
          </>}
        </div>
      </div>

      <style>{`
        .screen { flex:1; min-height:0; display: flex; justify-content: center; padding: 28px 56px 24px; overflow: hidden; }
        .screen-inner { width: 100%; max-width: 1100px; margin: 0 auto; display: flex; flex-direction: column; min-height: 0; }
        .actions-grid { display: flex; flex-direction: column; gap: 16px; }
      `}</style>
    </div>);

}


// =================== DOC validation (DNI / CPF) ===================
function isValidCpf(raw) {
  const cpf = String(raw || '').replace(/\D/g, '');
  if (cpf.length !== 11 || /^(\d)\1{10}$/.test(cpf)) return false;
  const dig = (nums, weights) => {
    const sum = nums.reduce((acc, n, i) => acc + n * weights[i], 0);
    const r = sum % 11;
    return r < 2 ? 0 : 11 - r;
  };
  const nums = cpf.split('').map(Number);
  const d1 = dig(nums.slice(0, 9), [10,9,8,7,6,5,4,3,2]);
  const d2 = dig(nums.slice(0, 9).concat(d1), [11,10,9,8,7,6,5,4,3,2]);
  return nums[9] === d1 && nums[10] === d2;
}

function isDocValid(doc) {
  const d = String(doc || '').replace(/\D/g, '');
  const isBr = (typeof totemMarket !== 'undefined' && totemMarket.code === 'BR');
  if (isBr) {
    // CPF completo válido, o códigos cortos de demo (mock)
    if (d.length === 11) return isValidCpf(d);
    return d.length >= 7 && d.length <= 10;
  }
  return d.length >= 7 && d.length <= 10;
}

function docMaxLen() {
  return (typeof totemMarket !== 'undefined' && totemMarket.code === 'BR') ? 11 : 10;
}

// =================== DNI ENTRY ===================
function ScreenDni({ flow, onSubmit, onBack, onCancel, onScanQr }) {
  const [dni, setDni] = uS("");
  const [err, setErr] = uS(false);
  const maxLen = docMaxLen();

  const flowLabel = {
    appointment: tt('flow.appointment'),
    walkin: tt('flow.walkin'),
    labs: tt('flow.labs'),
    rx: tt('ph.flow.rx'),
    pickup: tt('ph.flow.pickup'),
    counter: tt('ph.flow.counter'),
    draw: tt('labp.flow.draw'),
    results: tt('labp.flow.results'),
    dropoff: tt('labp.flow.dropoff'),
    er: tt('hosp.flow.er'),
    admit: tt('hosp.flow.admit'),
    visit: tt('hosp.flow.visit'),
    odappt: tt('od.flow.appt'),
    odurgent: tt('od.flow.urgent'),
    odhygiene: tt('od.flow.hygiene')
  }[flow];

  const press = (n) => {setErr(false);setDni((d) => d.length < maxLen ? d + n : d);};
  const back = () => {setErr(false);setDni((d) => d.slice(0, -1));};
  const clear = () => {setErr(false);setDni("");};

  const valid = isDocValid(dni);
  const [checking, setChecking] = uS(false);
  const submit = async () => {
    if (!valid) { setErr(true); return; }
    const isBr = (typeof totemMarket !== 'undefined' && totemMarket.code === 'BR');
    const digits = String(dni).replace(/\D/g, '');
    // CPF completo: validar también en API (fail-open si backend no tiene el endpoint aún)
    if (isBr && digits.length === 11) {
      setChecking(true);
      try {
        const apiBase = (typeof totemMarket !== 'undefined' && totemMarket.apiBase) || 'https://api.medicalcaresaas.online/v1';
        const res = await fetch(apiBase + '/auth/totem/validate-document', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ document: digits, country: 'BR' }),
        });
        if (res.ok) {
          const data = await res.json();
          if (data && data.valid === false) {
            setErr(true);
            setChecking(false);
            return;
          }
        }
      } catch (_) {
        // fail-open: local CPF check already passed
      }
      setChecking(false);
    }
    onSubmit(dni);
  };

  return (
    <div className="screen scale-in">
      <div className="screen-inner-wide">
        <StepHeader step={2} total={5} label={`${flowLabel} · ${tt('dni.step')}`} onBack={onBack} onCancel={onCancel} />

        <div className="dni-grid">
          <div className="dni-left">
            <h2 className="h-title">{tt('dni.title')}<br />{tt('doc')}</h2>
            <p className="h-body" style={{ marginTop: 14, marginBottom: 28 }}>{tt('dni.hint')}</p>

            <DniDisplay value={dni} error={err} max={maxLen} />

            <div className="dni-helper">
              {err && <span className="dni-err"><Icon name="x-circle" size={16} /> {tt('dni.invalid')}</span>}
              {!err && dni.length > 0 && <span className="dni-ok"><Icon name="check-circle" size={16} /> {dni.length} {tt('dni.digits')}</span>}
              {!err && dni.length === 0 && <span className="dni-hint">{tt('dni.placeholder')}</span>}
            </div>

            <div className="dni-actions">
              <button className="btn btn-primary btn-block btn-xl" disabled={!valid || checking} onClick={submit}>
                {tt('dni.continue')} <Icon name="arrow-right" size={26} />
              </button>
              {onScanQr && (
                <button className="btn btn-ghost btn-block" style={{ marginTop: 12 }} onClick={onScanQr}>
                  <Icon name="qr" size={20} /> {tt('dni.scanQr')}
                </button>
              )}
            </div>
          </div>

          <div className="dni-right">
            <NumericKeypad onPress={press} onBackspace={back} onClear={clear} />
          </div>
        </div>
      </div>

      <style>{`
        .screen-inner-wide { width: 100%; max-width: 1080px; margin: 0 auto; display:flex; flex-direction:column; padding: 0 24px; }
        .dni-grid {
          display: grid;
          grid-template-columns: minmax(0, 480px) auto;
          gap: 56px;
          align-items: center;
          margin-top: 8px;
          justify-content: center;
        }
        .dni-left { min-width: 0; }
        .dni-helper { margin-top: 14px; min-height: 24px; font-size: 14px; }
        .dni-err { color: var(--t-error); display: inline-flex; align-items:center; gap: 6px; }
        .dni-ok  { color: var(--t-success); display: inline-flex; align-items:center; gap: 6px; }
        .dni-hint { color: #5A6275; }
        .dni-actions { margin-top: 24px; max-width: 460px; }
      `}</style>
    </div>);

}

// =================== QR SCAN (check-in por Health Passport) ===================
function ScreenQrScan({ onScan, onBack, onCancel, onFallbackDni }) {
  const videoRef = uR(null);
  const canvasRef = uR(null);
  const streamRef = uR(null);
  const rafRef = uR(null);
  const scannedRef = uR(false); // evita disparar onScan más de una vez por el mismo frame loop
  const [status, setStatus] = uS('requesting'); // requesting | scanning | denied

  uE(() => {
    let cancelled = false;
    function tick() {
      if (cancelled || scannedRef.current) return;
      const video = videoRef.current;
      const canvas = canvasRef.current;
      if (video && canvas && video.readyState === video.HAVE_ENOUGH_DATA && typeof jsQR === 'function') {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        const code = jsQR(imageData.data, imageData.width, imageData.height);
        if (code && code.data) {
          scannedRef.current = true;
          onScan(code.data);
          return;
        }
      }
      rafRef.current = requestAnimationFrame(tick);
    }
    async function start() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: 'environment' },
          audio: false,
        });
        if (cancelled) { stream.getTracks().forEach((tr) => tr.stop()); return; }
        streamRef.current = stream;
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
          await videoRef.current.play();
        }
        setStatus('scanning');
        tick();
      } catch (e) {
        if (!cancelled) setStatus('denied');
      }
    }
    start();
    return () => {
      cancelled = true;
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
      if (streamRef.current) streamRef.current.getTracks().forEach((tr) => tr.stop());
    };
  }, []);

  return (
    <div className="screen scale-in">
      <div className="screen-inner">
        <StepHeader step={2} total={5} label={tt('qr.title')} onBack={onBack} onCancel={onCancel} />
        <div className="qr-card">
          <h2 className="h-title">{tt('qr.title')}</h2>
          <p className="h-body" style={{ marginTop: 10, marginBottom: 22 }}>{tt('qr.hint')}</p>

          <div className="qr-frame">
            <video ref={videoRef} playsInline muted className="qr-video" />
            <canvas ref={canvasRef} style={{ display: 'none' }} />
            {status !== 'scanning' && (
              <div className="qr-overlay">
                {status === 'requesting' && <span>{tt('qr.requesting')}</span>}
                {status === 'denied' && <span className="dni-err">{tt('qr.denied')}</span>}
              </div>
            )}
          </div>

          <button className="btn btn-ghost btn-block" style={{ marginTop: 20, maxWidth: 460 }} onClick={onFallbackDni}>
            {tt('qr.useDni')}
          </button>
        </div>
      </div>

      <style>{`
        .qr-card { max-width: 520px; margin: 0 auto; text-align: center; }
        .qr-frame {
          position: relative; width: 100%; aspect-ratio: 1 / 1; max-width: 420px; margin: 0 auto;
          border-radius: 24px; overflow: hidden; background: #0A0E1A; border: 2px solid var(--t-border-strong);
        }
        .qr-video { width: 100%; height: 100%; object-fit: cover; }
        .qr-overlay {
          position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
          text-align: center; padding: 24px; background: rgba(10,14,26,0.85); color: #C7CDDB; font-size: 15px;
        }
      `}</style>
    </div>);
}

// =================== NOT FOUND ===================
function ScreenNotFound({ dni, onRetry, onCancel }) {
  return (
    <div className="screen scale-in">
      <div className="screen-inner">
        <div className="nf-card">
          <div className="nf-icon"><Icon name="x-circle" size={56} stroke={1.5} /></div>
          <h2 className="h-title">{tt('notfound.title')}</h2>
          <p className="h-body" style={{ marginTop: 12 }}>
            {tt('notfound.body', { doc: dni }).split(dni)[0]}
            <strong style={{ color: 'white' }}>{dni}</strong>
            {tt('notfound.body', { doc: dni }).split(dni)[1] || ''}
          </p>
          <div className="nf-info">
            <Icon name="info" size={18} />
            <span>{tt('notfound.info')}</span>
          </div>
          <div className="nf-actions">
            <button className="btn btn-secondary" onClick={onRetry}>
              <Icon name="arrow-left" size={20} /> {tt('notfound.retry')}
            </button>
            <button className="btn btn-primary" onClick={onCancel}>{tt('notfound.home')}</button>
          </div>
        </div>
      </div>
      <style>{`
        .nf-card {
          max-width: 720px; margin: 60px auto 0;
          text-align: center;
          background: rgba(255,107,107,0.04);
          border: 1px solid rgba(255,107,107,0.2);
          border-radius: 28px;
          padding: 56px 48px;
        }
        .nf-icon {
          width: 110px; height: 110px;
          margin: 0 auto 24px;
          display: grid; place-items: center;
          border-radius: 50%;
          background: rgba(255,107,107,0.08);
          color: var(--t-error);
        }
        .nf-info {
          margin: 24px auto 0;
          padding: 14px 18px;
          background: rgba(255,255,255,0.04);
          border: 1px solid rgba(255,255,255,0.08);
          border-radius: 14px;
          display: inline-flex; align-items: center; gap: 10px;
          color: #C7CCD9;
          font-size: 15px;
          text-align: left;
          max-width: 540px;
        }
        .nf-info svg { color: #FFD479; flex: 0 0 auto; }
        .nf-actions { margin-top: 36px; display: flex; gap: 16px; justify-content: center; }
      `}</style>
    </div>);

}

// =================== CONFIRM IDENTITY ===================
function ScreenConfirm({ patient, onYes, onNo, onCancel }) {
  return (
    <div className="screen scale-in">
      <div className="screen-inner">
        <StepHeader step={3} total={5} label={tt('confirm.step')} onBack={onNo} onCancel={onCancel} />
        <div className="confirm-card">
          <div className="confirm-eyebrow">
            <Icon name="user" size={16} /> {tt('confirm.eyebrow')}
          </div>
          <h2 className="confirm-name">{tt('confirm.ask')}</h2>
          <h1 className="confirm-fullname">{patient.firstName}<br />{patient.lastName}?</h1>

          <div className="confirm-meta">
            <div className="confirm-meta-item">
              <span className="h-label">{tt('doc')}</span>
              <span className="confirm-meta-value">{patient.documentNumber}</span>
            </div>
            {patient.coverage &&
            <div className="confirm-meta-item">
                <span className="h-label">{tt('confirm.coverage')}</span>
                <span className="confirm-meta-value">{patient.coverage.provider}</span>
              </div>
            }
          </div>

          <div className="confirm-actions">
            <button className="btn btn-secondary" style={{ flex: 1, height: 72, fontSize: 18 }} onClick={onNo}>
              <Icon name="x" size={20} /> {tt('confirm.no')}
            </button>
            <button className="btn btn-primary" style={{ flex: 1.4, height: 72, fontSize: 20 }} onClick={onYes}>
              <Icon name="check" size={22} stroke={3} /> {tt('confirm.yes')}
            </button>
          </div>
        </div>
      </div>

      <style>{`
        .confirm-card {
          max-width: 860px; margin: 0 auto;
          text-align: center;
          background: linear-gradient(180deg, rgba(30,144,255,0.06), rgba(255,255,255,0.02));
          border: 1px solid rgba(30,144,255,0.25);
          border-radius: 24px;
          padding: 22px 36px 28px;
        }
        .confirm-eyebrow {
          display: inline-flex; align-items: center; gap: 8px;
          padding: 5px 12px;
          background: rgba(30,144,255,0.12);
          border: 1px solid rgba(30,144,255,0.3);
          border-radius: 999px;
          color: #BFE0FF;
          font-size: 11px;
          font-weight: 600;
          letter-spacing: 0.1em;
          text-transform: uppercase;
          margin-bottom: 14px;
        }
        .confirm-name { font-size: 22px; color: #C7CCD9; margin: 0; font-weight: 400; letter-spacing: -0.005em; }
        .confirm-fullname {
          font-size: 44px;
          font-weight: 700;
          letter-spacing: -0.025em;
          line-height: 1.05;
          margin: 8px 0 18px;
          color: white;
        }
        .confirm-meta {
          display: flex;
          justify-content: center;
          gap: 56px;
          padding: 12px 24px;
          background: rgba(255,255,255,0.03);
          border: 1px solid rgba(255,255,255,0.08);
          border-radius: 14px;
          margin-bottom: 22px;
        }
        .confirm-meta-item { text-align: left; }
        .confirm-meta-value {
          display: block;
          font-size: 18px; font-weight: 600;
          font-variant-numeric: tabular-nums;
          margin-top: 2px;
          letter-spacing: 0.02em;
        }
        .confirm-actions { display: flex; gap: 12px; }
      `}</style>
    </div>);

}

// =================== APPOINTMENTS LIST ===================
function ScreenAppointments({ patient, appointments, onSelect, onBack, onCancel }) {
  const [selected, setSelected] = uS(appointments[0]?.id || null);
  const onContinue = () => {
    const a = appointments.find((x) => x.id === selected);
    if (a) onSelect(a);
  };
  return (
    <div className="screen scale-in" style={{ fontWeight: "400", lineHeight: "0.4" }}>
      <div className="screen-inner">
        <StepHeader step={4} total={5} label={tt('appts.step')} onBack={onBack} onCancel={onCancel} />
        <div className="appt-head">
          <div>
            <h2 className="h-title" style={{ margin: 0 }}>{tt('appts.hello', { name: patient.firstName })}</h2>
            <p className="h-body" style={{ marginTop: 8 }}>
              {appointments.length === 1 ?
              tt('appts.one') :
              tt('appts.many', { n: appointments.length })}
            </p>
          </div>
          <Tag color="blue">{tt('appts.today')} · {new Date().toLocaleDateString(typeof totemDateLocale !== 'undefined' ? totemDateLocale : 'es-AR', { day: 'numeric', month: 'short' })}</Tag>
        </div>

        <div className="appt-list" style={{ gap: "12px" }}>
          {appointments.map((a) =>
          <AppointmentCard key={a.id} appt={a}
          selected={selected === a.id}
          onClick={() => setSelected(a.id)} />
          )}
        </div>

        <div className="appt-foot" style={{ textAlign: "center", borderStyle: "none", padding: "23px 0px 0px", margin: "0px 0px 0px 115px" }}>
          <button className="btn btn-primary btn-xl" disabled={!selected} onClick={onContinue} style={{ backgroundPosition: "center center", alignItems: "center", textAlign: "center", backgroundSize: "contain" }}>
            {tt('appts.continue')} <Icon name="arrow-right" size={26} />
          </button>
        </div>
      </div>
      <style>{`
        .appt-head { display: flex; align-items: flex-start; justify-content: space-between; margin-bottom: 24px; }
        .appt-list { display: flex; flex-direction: column; gap: 14px; max-height: 320px; overflow-y: auto; padding-right: 4px; }
        .appt-foot { margin-top: auto; padding-top: 24px; }
        .appt-list::-webkit-scrollbar { width: 6px; }
        .appt-list::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 3px; }
      `}</style>
    </div>);

}

// =================== VISIT REASON (walk-in) ===================
function ScreenVisitReason({ reasons, onSelect, onBack, onCancel }) {
  const [picked, setPicked] = uS(null);
  return (
    <div className="screen scale-in">
      <div className="screen-inner" style={{ maxWidth: 820 }}>
        <StepHeader step={3} total={5} label={vert('ph.reason.step', 'labp.reason.step', 'reason.step', 'hosp.reason.step', 'od.reason.step')} onBack={onBack} onCancel={onCancel} />
        <h2 className="h-section" style={{ marginTop: 0, marginBottom: 4, textAlign: 'center' }}>{vert('ph.reason.title', 'labp.reason.title', 'reason.title', 'hosp.reason.title', 'od.reason.title')}</h2>
        <p className="h-body" style={{ marginTop: 6, marginBottom: 18, fontSize: 17, textAlign: 'center' }}>{vert('ph.reason.sub', 'labp.reason.sub', 'reason.sub', 'hosp.reason.sub', 'od.reason.sub')}</p>

        <div className="reason-grid">
          {reasons.map((r) =>
          <button key={r.id}
          className={"reason-card " + (picked === r.id ? "reason-selected" : "")}
          onClick={() => setPicked(r.id)}>
              <div className="reason-icon"><Icon name={r.icon} size={26} /></div>
              <div className="reason-label">{r.label}</div>
              {picked === r.id && <div className="reason-check"><Icon name="check" size={14} stroke={3} /></div>}
            </button>
          )}
        </div>

        <div style={{ marginTop: 18 }}>
          <button className="btn btn-primary btn-block" style={{ height: 64, fontSize: 20 }} disabled={!picked}
          onClick={() => onSelect(reasons.find((r) => r.id === picked))}>
            {tt('dni.continue')} <Icon name="arrow-right" size={22} />
          </button>
        </div>
      </div>
      <style>{`
        .reason-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; }
        .reason-card {
          appearance: none; font-family: inherit;
          display: flex; align-items: center; gap: 14px;
          padding: 16px 18px;
          background: rgba(255,255,255,0.04);
          border: 1.5px solid rgba(255,255,255,0.10);
          border-radius: 16px;
          color: white;
          font-size: 18px; font-weight: 600;
          cursor: pointer;
          text-align: left;
          position: relative;
          transition: all 0.18s;
        }
        .reason-card:hover { background: rgba(255,255,255,0.07); border-color: rgba(255,255,255,0.2); }
        .reason-selected {
          background: rgba(30,144,255,0.10) !important;
          border-color: var(--t-primary) !important;
          box-shadow: 0 0 0 3px rgba(30,144,255,0.15);
        }
        .reason-icon {
          width: 46px; height: 46px;
          border-radius: 12px;
          background: rgba(30,144,255,0.12);
          color: #5DD3FF;
          display: grid; place-items: center;
          flex: 0 0 auto;
        }
        .reason-selected .reason-icon { background: rgba(30,144,255,0.2); color: white; }
        .reason-check {
          position: absolute; top: 10px; right: 10px;
          width: 22px; height: 22px;
          background: var(--t-primary);
          color: white;
          border-radius: 50%;
          display: grid; place-items: center;
          box-shadow: 0 4px 10px rgba(30,144,255,0.5);
        }
      `}</style>
    </div>);

}

// =================== COVERAGE ===================
function ScreenCoverage({ providers, onSubmit, onBack, onCancel }) {
  const [hasCoverage, setHasCoverage] = uS(null);
  const [providerId, setProviderId] = uS(null);
  const [showModal, setShowModal] = uS(false);

  const selectedProvider = providers.find((p) => p.id === providerId);
  const ready = hasCoverage === false || hasCoverage === true && providerId;

  const onContinue = () => {
    if (hasCoverage === false) {
      onSubmit({ type: "particular", provider: tt('coverage.particular') });
    } else if (selectedProvider) {
      onSubmit({ type: "covered", provider: selectedProvider.name });
    }
  };

  return (
    <div className="screen scale-in">
      <div className="screen-inner">
        <StepHeader step={4} total={5} label={vert('ph.coverage.step', 'labp.coverage.step', 'coverage.step', 'hosp.coverage.step', 'od.coverage.step')} onBack={onBack} onCancel={onCancel} />
        <h2 className="h-title">{vert('ph.coverage.title', 'labp.coverage.title', 'coverage.title', 'hosp.coverage.title', 'od.coverage.title')}</h2>
        <p className="h-body" style={{ marginTop: 12, marginBottom: 32 }}>{vert('ph.coverage.sub', 'labp.coverage.sub', 'coverage.sub', 'hosp.coverage.sub', 'od.coverage.sub')}</p>

        <div className="cov-radio">
          <button
            className={"cov-card " + (hasCoverage === true ? "cov-selected" : "")}
            onClick={() => {setHasCoverage(true);if (!providerId) setShowModal(true);}}>
            <div className="cov-icon" style={{ background: 'rgba(76,175,80,0.12)', color: '#7DDB85' }}>
              <Icon name="shield" size={32} />
            </div>
            <div className="cov-text">
              <div className="cov-title">{vert('ph.coverage.yes', 'labp.coverage.yes', 'coverage.yes', 'hosp.coverage.yes', 'od.coverage.yes')}</div>
              <div className="cov-sub">{selectedProvider ? selectedProvider.name : vert('ph.coverage.yes.sub', 'labp.coverage.yes.sub', 'coverage.yes.sub', 'hosp.coverage.yes.sub', 'od.coverage.yes.sub')}</div>
            </div>
            {hasCoverage === true && selectedProvider &&
            <button className="btn btn-ghost" onClick={(e) => {e.stopPropagation();setShowModal(true);}}>{tt('coverage.change')}</button>
            }
          </button>

          <button
            className={"cov-card " + (hasCoverage === false ? "cov-selected" : "")}
            onClick={() => {setHasCoverage(false);setProviderId(null);}}>
            <div className="cov-icon" style={{ background: 'rgba(255,181,71,0.12)', color: '#FFD479' }}>
              <Icon name="shield-off" size={32} />
            </div>
            <div className="cov-text">
              <div className="cov-title">{vert('ph.coverage.no', 'labp.coverage.no', 'coverage.no', 'hosp.coverage.no', 'od.coverage.no')}</div>
              <div className="cov-sub">{vert('ph.coverage.no.sub', 'labp.coverage.no.sub', 'coverage.no.sub', 'hosp.coverage.no.sub', 'od.coverage.no.sub')}</div>
            </div>
          </button>
        </div>

        <div style={{ marginTop: 32 }}>
          <button className="btn btn-primary btn-xl btn-block" disabled={!ready} onClick={onContinue}>
            {tt('dni.continue')} <Icon name="arrow-right" size={26} />
          </button>
        </div>
      </div>

      <Modal open={showModal} onClose={() => setShowModal(false)} title={vert('ph.coverage.modal', 'labp.coverage.modal', 'coverage.modal', 'hosp.coverage.modal', 'od.coverage.modal')}>
        <div className="prov-list">
          {providers.filter((p) => p.id !== "particular").map((p) =>
          <button key={p.id}
          className={"prov-row " + (providerId === p.id ? "prov-selected" : "")}
          onClick={() => {setProviderId(p.id);setShowModal(false);}}>
              <div className="prov-logo">{p.name.charAt(0)}</div>
              <div className="prov-name">{p.name}</div>
              {providerId === p.id && <Icon name="check" size={20} stroke={3} />}
            </button>
          )}
        </div>
        <style>{`
          .prov-list { display: flex; flex-direction: column; gap: 8px; max-height: 380px; overflow-y: auto; }
          .prov-row {
            appearance: none; font-family: inherit;
            display: flex; align-items: center; gap: 16px;
            padding: 14px 18px;
            background: rgba(255,255,255,0.03);
            border: 1px solid rgba(255,255,255,0.08);
            border-radius: 12px;
            color: white;
            cursor: pointer;
            text-align: left;
            transition: all 0.15s;
          }
          .prov-row:hover { background: rgba(255,255,255,0.07); border-color: rgba(255,255,255,0.18); }
          .prov-selected {
            background: rgba(30,144,255,0.12) !important;
            border-color: var(--t-primary) !important;
            color: white;
          }
          .prov-logo {
            width: 40px; height: 40px; border-radius: 10px;
            background: linear-gradient(135deg, #5DD3FF, #1E90FF);
            display: grid; place-items: center;
            font-weight: 700;
            font-size: 18px;
          }
          .prov-name { flex: 1; font-size: 18px; font-weight: 500; }
        `}</style>
      </Modal>

      <style>{`
        .cov-radio { display: flex; flex-direction: column; gap: 12px; }
        .cov-card {
          appearance: none; font-family: inherit;
          width: 100%; text-align: left;
          display: flex; align-items: center; gap: 20px;
          padding: 24px;
          background: rgba(255,255,255,0.04);
          border: 1.5px solid rgba(255,255,255,0.10);
          border-radius: 18px;
          color: white;
          cursor: pointer;
          transition: all 0.18s;
        }
        .cov-card:hover { background: rgba(255,255,255,0.07); border-color: rgba(255,255,255,0.2); }
        .cov-selected { border-color: var(--t-primary) !important; background: rgba(30,144,255,0.08) !important; box-shadow: 0 0 0 3px rgba(30,144,255,0.15); }
        .cov-icon {
          width: 64px; height: 64px;
          border-radius: 16px;
          display: grid; place-items: center;
          flex: 0 0 auto;
        }
        .cov-text { flex: 1; }
        .cov-title { font-size: 22px; font-weight: 600; }
        .cov-sub { font-size: 15px; color: #8A93A6; margin-top: 4px; }
      `}</style>
    </div>);

}

// =================== LAB ORDERS ===================
function ScreenLabOrders({ patient, orders, onConfirm, onBack, onCancel }) {
  const [selected, setSelected] = uS(orders.map((o) => o.id));

  const toggle = (id) => setSelected((s) => s.includes(id) ? s.filter((x) => x !== id) : [...s, id]);
  const ready = selected.length > 0;

  const submit = () => {
    onConfirm(orders.filter((o) => selected.includes(o.id)));
  };

  return (
    <div className="screen scale-in">
      <div className="screen-inner">
        <StepHeader step={4} total={5} label={isPharmacy() ? tt('ph.pickup.step') : tt('labs.step')} onBack={onBack} onCancel={onCancel} />
        <div className="appt-head">
          <div>
            <h2 className="h-title" style={{ margin: 0 }}>{tt('labs.hello', { name: patient.firstName })}</h2>
            <p className="h-body" style={{ marginTop: 8 }}>
              {isPharmacy() ? tt('ph.pickup.count', { n: orders.length }) : tt('labs.count', { n: orders.length })}
            </p>
          </div>
          <Tag color="green">{isPharmacy() ? tt('ph.pickup.ready') : tt('labs.ready')}</Tag>
        </div>

        <div className="lab-list">
          {orders.map((o) =>
          <LabOrderCard key={o.id} order={o}
          selected={selected.includes(o.id)}
          onToggle={() => toggle(o.id)} />
          )}
        </div>

        <div style={{ marginTop: 'auto', paddingTop: 24 }}>
          <button className="btn btn-primary btn-xl btn-block" disabled={!ready} onClick={submit}>
            {tt(isPharmacy() ? 'ph.pickup.confirm' : 'labs.confirm', { n: selected.length, unit: selected.length === 1 ? tt(isPharmacy() ? 'ph.pickup.unit.one' : 'labs.unit.one') : tt(isPharmacy() ? 'ph.pickup.unit.many' : 'labs.unit.many') })} <Icon name="arrow-right" size={26} />
          </button>
        </div>
      </div>
      <style>{`
        .lab-list { display: flex; flex-direction: column; gap: 12px; max-height: 340px; overflow-y: auto; }
      `}</style>
    </div>);

}

// =================== SUMMARY ===================
function ScreenSummary({ flow, patient, appointment, reason, coverage, labs, onConfirm, onBack, onCancel }) {
  return (
    <div className="screen scale-in">
      <div className="screen-inner">
        <StepHeader step={5} total={5} label={tt('summary.step')} onBack={onBack} onCancel={onCancel} />
        <h2 className="h-section" style={{ marginTop: 0, marginBottom: 4 }}>{tt('summary.title')}</h2>
        <p className="h-body" style={{ marginTop: 6, marginBottom: 16, fontSize: 18 }}>{tt('summary.sub')}</p>

        <div className="summary-card">
          <div className="summary-row">
            <span className="h-label">{tt('summary.patient')}</span>
            <span className="summary-val">{patient.firstName} {patient.lastName}</span>
          </div>
          <div className="summary-row">
            <span className="h-label">{tt('doc')}</span>
            <span className="summary-val">{patient.documentNumber}</span>
          </div>
          {flow === "appointment" && appointment &&
          <>
              <div className="summary-row">
                <span className="h-label">{tt('summary.appt')}</span>
                <span className="summary-val">{appointment.time}{tt('time.hours') ? ' ' + tt('time.hours') : ''} · {appointment.doctorName}</span>
              </div>
              <div className="summary-row">
                <span className="h-label">{tt('summary.specialty')}</span>
                <span className="summary-val">{appointment.specialty} · {appointment.room}</span>
              </div>
              {patient.coverage &&
            <div className="summary-row">
                  <span className="h-label">{tt('summary.coverage')}</span>
                  <span className="summary-val">{patient.coverage.provider}</span>
                </div>
            }
              {appointment.copay > 0 &&
            <div className="summary-row summary-highlight">
                  <span className="h-label">{tt('summary.copay')}</span>
                  <span className="summary-val">{(typeof totemFormatMoney === 'function' ? totemFormatMoney(appointment.copay) : '$ ' + appointment.copay.toLocaleString(typeof totemDateLocale !== 'undefined' ? totemDateLocale : 'es-AR'))}</span>
                </div>
            }
            </>
          }
          {(flow === "walkin" || flow === "rx" || flow === "draw" || flow === "er" || flow === "odurgent" || flow === "odhygiene") &&
          <>
              <div className="summary-row">
                <span className="h-label">{tt('summary.reason')}</span>
                <span className="summary-val">{reason?.label}</span>
              </div>
              <div className="summary-row">
                <span className="h-label">{tt('summary.coverage')}</span>
                <span className="summary-val">{coverage?.provider}</span>
              </div>
              <div className="summary-row">
                <span className="h-label">{tt('summary.careType')}</span>
                <span className="summary-val">{flow === "rx" ? tt('ph.flow.rx') : flow === "draw" ? tt('labp.flow.draw') : flow === "er" ? tt('hosp.flow.er') : flow === "odurgent" ? tt('od.flow.urgent') : flow === "odhygiene" ? tt('od.flow.hygiene') : tt('summary.careValue')}</span>
              </div>
            </>
          }
          {(flow === "counter" || flow === "dropoff" || flow === "visit" || flow === "admit" || flow === "odappt") &&
          <>
              <div className="summary-row">
                <span className="h-label">{tt('summary.careType')}</span>
                <span className="summary-val">{flow === "dropoff" ? tt('labp.flow.dropoff') : flow === "visit" ? tt('hosp.flow.visit') : flow === "admit" ? tt('hosp.flow.admit') : flow === "odappt" ? tt('od.flow.appt') : tt('ph.summary.care')}</span>
              </div>
              {(flow === "admit" || flow === "odappt") && coverage &&
              <div className="summary-row">
                <span className="h-label">{tt('summary.coverage')}</span>
                <span className="summary-val">{coverage?.provider}</span>
              </div>}
            </>
          }
          {(flow === "labs" || flow === "pickup" || flow === "results") &&
          <>
              <div className="summary-row" style={{ alignItems: 'flex-start' }}>
                <span className="h-label">{tt('summary.labs')}</span>
                <div className="summary-val" style={{ textAlign: 'right' }}>
                  {labs?.map((l) => <div key={l.id} style={{ marginBottom: 4 }}>{l.studyType}</div>)}
                </div>
              </div>
            </>
          }
        </div>

        <div className="summary-actions">
          <button className="btn btn-secondary" style={{ flex: 1 }} onClick={onBack}>
            <Icon name="arrow-left" size={18} /> {tt('summary.edit')}
          </button>
          <button className="btn btn-primary btn-xl" style={{ flex: 2 }} onClick={onConfirm}>
            <Icon name="check" size={26} stroke={3} /> {tt('summary.confirm')}
          </button>
        </div>
      </div>
      <style>{`
        .summary-card {
          background: rgba(255,255,255,0.03);
          border: 1px solid rgba(255,255,255,0.10);
          border-radius: 18px;
          padding: 4px 24px;
          margin-bottom: 16px;
        }
        .summary-row {
          display: flex; justify-content: space-between; align-items: center;
          padding: 12px 0;
          border-bottom: 1px solid rgba(255,255,255,0.06);
          gap: 24px;
        }
        .summary-row:last-child { border-bottom: 0; }
        .summary-val {
          font-size: 18px; font-weight: 600;
          letter-spacing: -0.005em;
          text-align: right;
        }
        .summary-highlight {
          background: rgba(30,144,255,0.06);
          margin: 0 -24px;
          padding-left: 24px; padding-right: 24px;
        }
        .summary-highlight .summary-val { color: #5DD3FF; font-size: 22px; }
        .summary-actions { display: flex; gap: 14px; }
      `}</style>
    </div>);

}

// =================== TICKET (success + countdown) ===================
function ScreenTicket({ flow, patient, appointment, reason, coverage, labs, ticketNumber, queuePosition, eta, org, onPrint, onReset }) {
  const [count, setCount] = uS(15);
  uE(() => {
    if (count <= 0) {onReset();return;}
    const t = setTimeout(() => setCount((c) => c - 1), 1000);
    return () => clearTimeout(t);
  }, [count]);

  const isAppt = flow === "appointment";
  const isWalkin = flow === "walkin" || flow === "rx" || flow === "counter" || flow === "draw" || flow === "dropoff" || flow === "er" || flow === "admit" || flow === "visit" || flow === "odappt" || flow === "odurgent" || flow === "odhygiene";
  const isLabs = flow === "labs";
  const isPickup = flow === "pickup" || flow === "results";

  return (
    <div className="screen scale-in">
      <div className="screen-inner-wide">
        <div className="ticket-grid">
          <div className="ticket-success">
            <div className="success-glow" />
            <div className="success-ring">
              <div className="success-ring-inner">
                <Icon name="check" size={64} stroke={4} />
              </div>
            </div>
            <h2 className="h-title" style={{ marginTop: 28 }}>
              {isLabs ? tt('ticket.labs.title') : flow === "pickup" ? tt('ph.pick.pickup.title') : flow === "results" ? tt('labp.pick.results.title') : tt('ticket.ok.title')}
            </h2>
            <p className="h-body" style={{ marginTop: 12 }}>
              {isLabs ?
              tt('ticket.labs.body') :
              flow === "pickup" ?
              tt('ph.ticket.footer.pickup') :
              flow === "results" ?
              tt('ticket.labs.body') :
              <>{tt('ticket.ok.body')}<br />{tt('ticket.eta', { eta })}</>
              }
            </p>

            {!isLabs &&
            <div className="success-stats">
                <div className="success-stat">
                  <span className="h-label">{tt('ticket.yourNumber')}</span>
                  <span className="success-stat-val">{ticketNumber}</span>
                </div>
                <div className="success-stat">
                  <span className="h-label">{tt('ticket.queue')}</span>
                  <span className="success-stat-val">#{queuePosition}</span>
                </div>
              </div>
            }

            <div className="ticket-actions">
              <button className="btn btn-secondary" onClick={onPrint}>
                <Icon name="printer" size={20} /> {tt('ticket.reprint')}
              </button>
              <button className="btn btn-primary" onClick={onReset}>
                {tt('ticket.finish', { n: count })}
              </button>
            </div>
          </div>

          <div className="ticket-preview-wrap">
            <div className="ticket-preview-label">
              <Icon name="printer" size={14} /> {tt('ticket.printed')}
            </div>
            <div className="ticket-preview">
              <TicketContent
                org={org}
                flow={flow}
                patient={patient}
                appointment={appointment}
                reason={reason}
                coverage={coverage}
                labs={labs}
                ticketNumber={ticketNumber}
                queuePosition={queuePosition} />
              
            </div>
          </div>
        </div>
      </div>

      <style>{`
        .ticket-grid {
          display: grid;
          grid-template-columns: 1.4fr auto;
          gap: 56px;
          align-items: center;
          padding: 16px 0;
        }
        .ticket-success { position: relative; padding: 24px 8px; }
        .success-glow {
          position: absolute;
          left: -40px; top: -40px;
          width: 280px; height: 280px;
          background: radial-gradient(circle, rgba(76,175,80,0.22), transparent 70%);
          pointer-events: none;
          animation: pulseGlow 2.4s ease-in-out infinite;
        }
        @keyframes pulseGlow {
          0%,100% { opacity: 0.6; transform: scale(1); }
          50%     { opacity: 1; transform: scale(1.05); }
        }
        .success-ring {
          position: relative;
          width: 120px; height: 120px;
          border-radius: 50%;
          background: rgba(76,175,80,0.10);
          display: grid; place-items: center;
          animation: scaleIn 0.5s cubic-bezier(0.2,0.9,0.3,1) both;
        }
        .success-ring-inner {
          width: 96px; height: 96px;
          border-radius: 50%;
          background: linear-gradient(135deg, #4CAF50, #2E7D32);
          color: white;
          display: grid; place-items: center;
          box-shadow: 0 12px 32px rgba(76,175,80,0.5);
        }
        .success-stats {
          display: flex; gap: 20px;
          margin-top: 28px;
        }
        .success-stat {
          flex: 1;
          padding: 18px 22px;
          background: rgba(255,255,255,0.04);
          border: 1px solid rgba(255,255,255,0.10);
          border-radius: 16px;
        }
        .success-stat-val {
          display: block;
          font-size: 44px; font-weight: 700;
          font-variant-numeric: tabular-nums;
          letter-spacing: -0.02em;
          color: #5DD3FF;
          margin-top: 4px;
          line-height: 1;
        }
        .ticket-actions { margin-top: 32px; display: flex; gap: 12px; }

        .ticket-preview-wrap {
          display: flex; flex-direction: column; align-items: center; gap: 10px;
        }
        .ticket-preview-label {
          display: inline-flex; align-items: center; gap: 6px;
          font-size: 12px; letter-spacing: 0.12em; text-transform: uppercase;
          color: #5A6275;
          font-weight: 600;
        }
        .ticket-preview {
          background: white;
          color: #111;
          width: 320px;
          padding: 24px 22px;
          font-family: ui-monospace, 'SF Mono', Menlo, monospace;
          font-size: 12px;
          line-height: 1.5;
          box-shadow:
            0 30px 60px -20px rgba(0,0,0,0.6),
            0 0 0 1px rgba(255,255,255,0.06);
          border-radius: 4px;
          position: relative;
        }
        .ticket-preview::before, .ticket-preview::after {
          content: ''; position: absolute; left: 0; right: 0;
          height: 16px;
          background-image:
            radial-gradient(circle at 8px 8px, transparent 6px, white 6px),
            radial-gradient(circle at 8px 8px, transparent 6px, white 6px);
          background-size: 16px 16px;
        }
        .ticket-preview::before { top: -16px; transform: rotate(180deg); }
        .ticket-preview::after { bottom: -16px; }
      `}</style>
    </div>);

}

// =================== TICKET CONTENT (shared by preview + print) ===================
function TicketContent({ org, flow, patient, appointment, reason, coverage, labs, ticketNumber, queuePosition }) {
  const date = new Date();
  const dl = (typeof totemDateLocale !== 'undefined' ? totemDateLocale : 'es-AR');
  const dStr = date.toLocaleDateString(dl, { day: '2-digit', month: '2-digit', year: 'numeric' });
  const tStr = date.toLocaleTimeString(dl, { hour: '2-digit', minute: '2-digit' });

  const isAppt = flow === "appointment";
  const isWalkin = flow === "walkin";
  const isRx = flow === "rx";
  const isCounter = flow === "counter";
  const isLabs = flow === "labs";
  const isPickup = flow === "pickup";

  return (
    <div className="t-print-content">
      <div className="t-center t-bold t-lg">{org.name}</div>
      <div className="t-divider t-divider-dashed" />
      <div className="t-center t-bold" style={{ fontSize: 14, letterSpacing: '0.1em' }}>
        {isAppt && tt('ticket.type.appt')}
        {isWalkin && tt('ticket.type.walkin')}
        {isLabs && tt('ticket.type.labs')}
        {isRx && tt('ph.ticket.type.rx')}
        {isPickup && tt('ph.ticket.type.pickup')}
        {isCounter && tt('ph.ticket.type.counter')}
        {flow === "draw" && tt('labp.ticket.type.draw')}
        {flow === "results" && tt('labp.ticket.type.results')}
        {flow === "dropoff" && tt('labp.ticket.type.dropoff')}
        {flow === "er" && tt('hosp.ticket.type.er')}
        {flow === "admit" && tt('hosp.ticket.type.admit')}
        {flow === "visit" && tt('hosp.ticket.type.visit')}
        {flow === "odappt" && tt('od.ticket.type.appt')}
        {flow === "odurgent" && tt('od.ticket.type.urgent')}
        {flow === "odhygiene" && tt('od.ticket.type.hygiene')}
      </div>
      <div className="t-divider t-divider-dashed" />

      {!(isLabs) &&
      <div className="t-center" style={{ margin: '12px 0 8px' }}>
          <div className="t-muted t-tiny">{tt('ticket.yourNum')}</div>
          <div className="t-ticketnum">{ticketNumber}</div>
          <div className="t-muted t-tiny">{tt('ticket.queuePos', { n: queuePosition })}</div>
        </div>
      }

      <div className="t-divider" />
      <div className="t-row"><span>{tt('summary.patient')}</span><span className="t-bold">{patient.firstName} {patient.lastName}</span></div>
      <div className="t-row"><span>{tt('doc')}</span><span>{patient.documentNumber}</span></div>
      <div className="t-row"><span>{tt('ticket.date')}</span><span>{dStr}</span></div>
      <div className="t-row"><span>{tt('ticket.checkin')}</span><span>{tStr}</span></div>

      {isAppt && appointment && <>
        <div className="t-divider" />
        <div className="t-row"><span>{tt('ticket.apptTime')}</span><span className="t-bold">{appointment.time}{tt('time.hours') ? ' ' + tt('time.hours') : ''}</span></div>
        <div className="t-row"><span>{tt('ticket.doctor')}</span><span>{appointment.doctorName}</span></div>
        <div className="t-row"><span>{tt('ticket.specialty')}</span><span>{appointment.specialty}</span></div>
        <div className="t-row"><span>{tt('ticket.room')}</span><span className="t-bold">{appointment.room}</span></div>
        {patient.coverage && <div className="t-row"><span>{tt('summary.coverage')}</span><span>{patient.coverage.provider}</span></div>}
        {appointment.copay > 0 && <div className="t-row"><span>{tt('ticket.copay')}</span><span className="t-bold">{typeof totemFormatMoney === 'function' ? totemFormatMoney(appointment.copay) : '$ ' + appointment.copay.toLocaleString(dl)}</span></div>}
      </>}

      {(isWalkin || isRx || flow === "draw" || flow === "er" || flow === "odurgent" || flow === "odhygiene") && <>
        <div className="t-divider" />
        <div className="t-row"><span>{tt('ticket.reason')}</span><span className="t-bold">{reason?.label}</span></div>
        <div className="t-row"><span>{tt('summary.coverage')}</span><span>{coverage?.provider}</span></div>
        <div className="t-row"><span>{tt('ticket.care')}</span><span>{isRx ? tt('ph.flow.rx') : flow === "draw" ? tt('labp.flow.draw') : flow === "er" ? tt('hosp.flow.er') : flow === "odurgent" ? tt('od.flow.urgent') : flow === "odhygiene" ? tt('od.flow.hygiene') : tt('ticket.careVal')}</span></div>
      </>}

      {(isCounter || flow === "dropoff" || flow === "visit" || flow === "admit" || flow === "odappt") && <>
        <div className="t-divider" />
        <div className="t-row"><span>{tt('ticket.care')}</span><span className="t-bold">{flow === "dropoff" ? tt('labp.flow.dropoff') : flow === "visit" ? tt('hosp.flow.visit') : flow === "admit" ? tt('hosp.flow.admit') : flow === "odappt" ? tt('od.flow.appt') : tt('ph.summary.care')}</span></div>
        {(flow === "admit" || flow === "odappt") && coverage && <div className="t-row"><span>{tt('summary.coverage')}</span><span>{coverage?.provider}</span></div>}
      </>}

      {(isLabs || isPickup || flow === "results") && labs && <>
        <div className="t-divider" />
        <div className="t-muted" style={{ margin: '4px 0' }}>{isPickup ? tt('ph.ticket.studies') : tt('ticket.studies')}</div>
        {labs.map((l) =>
        <div key={l.id} style={{ margin: '4px 0' }}>
            <div className="t-bold" style={{ fontSize: 11 }}>· {l.studyType}</div>
            <div className="t-muted t-tiny" style={{ paddingLeft: 8 }}>{tt('lab.requested')} {l.requestedBy} · {l.date}</div>
          </div>
        )}
      </>}

      <div className="t-divider t-divider-dashed" />
      <div className="t-center t-tiny t-muted">
        {flow === "pickup" ? tt('ph.ticket.footer.pickup') : flow === "draw" ? tt('labp.ticket.footer.draw') : flow === "er" ? tt('hosp.ticket.footer.er') : flow === "odurgent" ? tt('od.ticket.footer.urgent') : (isLabs || flow === "results") ? tt('ticket.footer.labs') : tt('ticket.footer.wait')}
      </div>
      <div className="t-center t-tiny t-muted" style={{ marginTop: 6 }}>www.medicalcaresaas.com</div>

      <style>{`
        .t-print-content { color: #111; }
        .t-center { text-align: center; }
        .t-bold { font-weight: 700; }
        .t-muted { color: #555; }
        .t-tiny { font-size: 10px; }
        .t-lg { font-size: 14px; }
        .t-divider { border-top: 1px solid #ccc; margin: 10px 0; }
        .t-divider-dashed { border-top: 1px dashed #888; }
        .t-row { display: flex; justify-content: space-between; gap: 8px; padding: 2px 0; }
        .t-row span:first-child { color: #555; }
        .t-ticketnum {
          font-size: 48px;
          font-weight: 800;
          letter-spacing: 0.04em;
          line-height: 1.1;
          margin: 4px 0;
        }
      `}</style>
    </div>);

}

Object.assign(window, {
  ScreenIdle, ScreenActionPicker, ScreenDni, ScreenNotFound,
  ScreenConfirm, ScreenAppointments, ScreenVisitReason, ScreenCoverage,
  ScreenLabOrders, ScreenSummary, ScreenTicket, TicketContent
});