// Check-in flow + Queue screen

function CheckinScreen({ dark, go }) {
  const t = useT(dark);
  const [step, setStep] = React.useState(0);
  const ex = LUMEN_DATA.upcoming[0];

  // Steps: 0 = arrivals confirm, 1 = docs, 2 = QR scan, 3 = success
  const next = () => setStep(s => Math.min(s + 1, 3));

  const StepDot = ({ i }) => (
    <div style={{
      width: i === step ? 22 : 6, height: 6, borderRadius: 99,
      background: i <= step ? t.accent : t.borderStrong,
      transition: 'all 0.25s',
    }} />
  );

  return (
    <Screen dark={dark} pad={false}>
      <div style={{ padding: '62px 20px 0', display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
        <BackButton dark={dark} onClick={() => step > 0 ? setStep(s => s - 1) : go('home')} />
        <div style={{ flex: 1, display: 'flex', gap: 6, justifyContent: 'center' }}>
          {[0,1,2,3].map(i => <StepDot key={i} i={i} />)}
        </div>
        <div style={{ width: 38 }} />
      </div>

      <div style={{ padding: '0 20px' }}>
        {step === 0 && <CheckinArrival dark={dark} ex={ex} onNext={next} />}
        {step === 1 && <CheckinDocs dark={dark} onNext={next} />}
        {step === 2 && <CheckinQR dark={dark} onNext={next} />}
        {step === 3 && <CheckinSuccess dark={dark} onQueue={() => go('queue')} />}
      </div>
    </Screen>
  );
}

function CheckinArrival({ dark, ex, onNext }) {
  const t = useT(dark);
  const [inside, setInside] = React.useState(false);
  React.useEffect(() => {
    const tm = setTimeout(() => setInside(true), 1200);
    return () => clearTimeout(tm);
  }, []);
  return (
    <div>
      <div style={{ fontSize: 11, color: t.accent, letterSpacing: 1.4, textTransform: 'uppercase', fontWeight: 700, marginBottom: 8 }}>Etapa 1 de 3</div>
      <h1 style={{ margin: 0, fontFamily: LUMEN_FONTS.serif, fontSize: 34, color: t.text, letterSpacing: -0.4, lineHeight: 1.05 }}>
        Confirme sua<br/>chegada
      </h1>
      <div style={{ fontSize: 15, color: t.textMuted, marginTop: 10, lineHeight: 1.5 }}>
        Detectamos que você está próximo da unidade. Seu check-in libera a recepção.
      </div>

      <Card dark={dark} padding={0} style={{ marginTop: 24, overflow: 'hidden' }}>
        {/* Mock map */}
        <div style={{
          height: 180, background: `
            repeating-linear-gradient(45deg, ${t.surfaceSunken}, ${t.surfaceSunken} 10px, ${t.surfaceAlt} 10px, ${t.surfaceAlt} 20px)
          `, position: 'relative',
        }}>
          {/* Route hint */}
          <svg width="100%" height="100%" style={{ position: 'absolute', inset: 0 }}>
            <path d="M 20 150 Q 100 80, 180 100 T 340 60" stroke={t.accent} strokeWidth="2.5" fill="none" strokeDasharray="4 6" opacity="0.5" />
          </svg>
          {/* You */}
          <div style={{ position: 'absolute', left: 20, top: 140, display: 'flex', alignItems: 'center', gap: 4 }}>
            <div style={{ width: 14, height: 14, borderRadius: 99, background: t.info, border: '2.5px solid white', boxShadow: `0 0 0 2px ${t.info}40` }} />
            <span style={{ fontSize: 11, color: t.text, fontWeight: 600, background: t.surface, padding: '2px 6px', borderRadius: 6 }}>você</span>
          </div>
          {/* Unit */}
          <div style={{ position: 'absolute', right: 28, top: 48, display: 'flex', alignItems: 'center', gap: 4 }}>
            <div style={{ width: 24, height: 24, borderRadius: 99, background: t.accent, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="building" size={14} color="#FFF4E6" />
            </div>
          </div>
        </div>
        <div style={{ padding: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <div style={{ width: 8, height: 8, borderRadius: 99, background: inside ? t.sage : t.warning, animation: 'pulse 1.8s infinite' }} />
            <span style={{ fontSize: 13, fontWeight: 600, color: inside ? t.sage : t.warning }}>
              {inside ? 'Você está na unidade' : 'Verificando localização…'}
            </span>
          </div>
          <div style={{ fontSize: 15, fontWeight: 500, color: t.text }}>{ex.unit}</div>
          <div style={{ fontSize: 13, color: t.textMuted, marginTop: 2 }}>{ex.address}</div>
        </div>
      </Card>

      <div style={{ marginTop: 16, display: 'flex', gap: 10, padding: 14, borderRadius: 16, background: t.accentBg }}>
        <Icon name="clock" size={18} color={t.accent} />
        <div style={{ flex: 1, fontSize: 13, color: dark ? t.text : '#3A2760', lineHeight: 1.4 }}>
          Seu exame é às <strong>{ex.time}</strong>. Chegada sugerida: <strong>{ex.checkinOpensAt}</strong>.
        </div>
      </div>

      <div style={{ marginTop: 28 }}>
        <Button dark={dark} full size="lg" variant="primary" onClick={onNext} disabled={!inside}>
          {inside ? 'Estou aqui, continuar' : 'Aguardando localização…'}
        </Button>
      </div>
    </div>
  );
}

function CheckinDocs({ dark, onNext }) {
  const t = useT(dark);
  const [done, setDone] = React.useState({ cpf: true, convenio: false, prep: false });
  const ready = Object.values(done).every(Boolean);

  const items = [
    { key: 'cpf', label: 'Documento com foto', detail: 'RG · válido', verified: true },
    { key: 'convenio', label: 'Carteirinha do convênio', detail: 'Bradesco Saúde Top', verified: done.convenio },
    { key: 'prep', label: 'Jejum confirmado', detail: 'Últimos 4 horas sem alimentos', verified: done.prep },
  ];
  return (
    <div>
      <div style={{ fontSize: 11, color: t.accent, letterSpacing: 1.4, textTransform: 'uppercase', fontWeight: 700, marginBottom: 8 }}>Etapa 2 de 3</div>
      <h1 style={{ margin: 0, fontFamily: LUMEN_FONTS.serif, fontSize: 34, color: t.text, letterSpacing: -0.4, lineHeight: 1.05 }}>
        Vamos conferir<br/>alguns detalhes
      </h1>
      <div style={{ fontSize: 15, color: t.textMuted, marginTop: 10, lineHeight: 1.5 }}>
        Confirme cada item para agilizar a recepção.
      </div>

      <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map(it => (
          <Card key={it.key} dark={dark} padding={16} onClick={() => setDone(d => ({ ...d, [it.key]: true }))}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              <div style={{
                width: 40, height: 40, borderRadius: 12,
                background: it.verified ? t.sageBg : t.surfaceSunken,
                color: it.verified ? t.sage : t.textMuted,
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                transition: 'all 0.2s',
              }}>
                <Icon name={it.verified ? 'check' : 'doc'} size={20} strokeWidth={it.verified ? 2.5 : 1.7} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15, fontWeight: 500, color: t.text }}>{it.label}</div>
                <div style={{ fontSize: 12.5, color: t.textMuted, marginTop: 1 }}>
                  {it.verified ? it.detail : 'Toque para confirmar'}
                </div>
              </div>
              {it.verified && (
                <span style={{ fontSize: 11, color: t.sage, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>Ok</span>
              )}
            </div>
          </Card>
        ))}
      </div>

      <div style={{ marginTop: 28 }}>
        <Button dark={dark} full size="lg" variant="primary" onClick={onNext} disabled={!ready}>
          Continuar
        </Button>
      </div>
    </div>
  );
}

function CheckinQR({ dark, onNext }) {
  const t = useT(dark);
  React.useEffect(() => {
    const tm = setTimeout(onNext, 2600);
    return () => clearTimeout(tm);
  }, []);
  return (
    <div>
      <div style={{ fontSize: 11, color: t.accent, letterSpacing: 1.4, textTransform: 'uppercase', fontWeight: 700, marginBottom: 8 }}>Etapa 3 de 3</div>
      <h1 style={{ margin: 0, fontFamily: LUMEN_FONTS.serif, fontSize: 34, color: t.text, letterSpacing: -0.4, lineHeight: 1.05 }}>
        Seu código<br/>de chegada
      </h1>
      <div style={{ fontSize: 15, color: t.textMuted, marginTop: 10, lineHeight: 1.5 }}>
        Apresente na recepção ou use os totens.
      </div>

      <div style={{
        marginTop: 28, background: t.surface, borderRadius: 28, padding: 28,
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        border: `1px solid ${t.border}`,
      }}>
        <QRMock t={t} />
        <div style={{ fontSize: 11, color: t.textMuted, letterSpacing: 1.2, textTransform: 'uppercase', fontWeight: 600, marginTop: 18 }}>Senha</div>
        <div style={{ fontFamily: LUMEN_FONTS.serif, fontSize: 44, color: t.text, letterSpacing: 1, marginTop: 4 }}>B-042</div>
        <div style={{ fontSize: 13, color: t.textMuted, marginTop: 4 }}>Helena M. · Ressonância · 09:40</div>
      </div>

      <div style={{
        marginTop: 16, display: 'flex', alignItems: 'center', gap: 10,
        padding: 14, borderRadius: 16, background: t.sageBg,
      }}>
        <div style={{ width: 10, height: 10, borderRadius: 99, background: t.sage, animation: 'pulse 1.4s infinite' }} />
        <div style={{ flex: 1, fontSize: 13, color: dark ? t.text : '#3D2D5A' }}>
          Aguardando confirmação da recepção…
        </div>
      </div>
    </div>
  );
}

function QRMock({ t }) {
  // Deterministic pattern
  const cells = 21;
  const pattern = [];
  for (let y = 0; y < cells; y++) {
    for (let x = 0; x < cells; x++) {
      // finders
      if ((x < 7 && y < 7) || (x >= cells-7 && y < 7) || (x < 7 && y >= cells-7)) {
        const inFinder = (p, q) => (p === 0 || p === 6 || q === 0 || q === 6) || (p >= 2 && p <= 4 && q >= 2 && q <= 4);
        let lx = x < 7 ? x : x - (cells - 7);
        let ly = y < 7 ? y : y - (cells - 7);
        if (inFinder(lx, ly)) pattern.push([x, y]);
        continue;
      }
      if ((x * 31 + y * 17 + x*y) % 3 === 0) pattern.push([x, y]);
    }
  }
  const size = 180, cs = size / cells;
  return (
    <div style={{ width: size, height: size, background: '#fff', padding: 0, borderRadius: 12 }}>
      <svg width={size} height={size}>
        {pattern.map(([x, y], i) => (
          <rect key={i} x={x * cs} y={y * cs} width={cs} height={cs} fill="#1F1B16" />
        ))}
      </svg>
    </div>
  );
}

function CheckinSuccess({ dark, onQueue }) {
  const t = useT(dark);
  return (
    <div style={{ textAlign: 'center', paddingTop: 10 }}>
      <div style={{
        width: 86, height: 86, borderRadius: 99, margin: '0 auto',
        background: t.sageBg, color: t.sage,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        animation: 'scaleIn 0.4s ease-out',
      }}>
        <Icon name="check" size={44} strokeWidth={2.2} />
      </div>
      <h1 style={{ margin: '22px 0 0', fontFamily: LUMEN_FONTS.serif, fontSize: 38, color: t.text, letterSpacing: -0.5, lineHeight: 1.05 }}>
        Check-in feito.
      </h1>
      <div style={{ fontSize: 16, color: t.textMuted, marginTop: 10, lineHeight: 1.5, padding: '0 10px' }}>
        Agora é só esperar ser chamada. Você pode acompanhar sua posição na fila.
      </div>

      <Card dark={dark} padding={18} style={{ marginTop: 28, textAlign: 'left' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: 11, color: t.textMuted, letterSpacing: 1, textTransform: 'uppercase', fontWeight: 600 }}>Sua senha</div>
            <div style={{ fontFamily: LUMEN_FONTS.serif, fontSize: 32, color: t.text, marginTop: 2 }}>B-042</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 11, color: t.textMuted, letterSpacing: 1, textTransform: 'uppercase', fontWeight: 600 }}>Posição</div>
            <div style={{ fontFamily: LUMEN_FONTS.serif, fontSize: 32, color: t.accent, marginTop: 2 }}>2º</div>
          </div>
        </div>
      </Card>

      <div style={{ marginTop: 22 }}>
        <Button dark={dark} full size="lg" variant="primary" onClick={onQueue} icon="clock">
          Acompanhar fila
        </Button>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
function QueueScreen({ dark, go }) {
  const t = useT(dark);
  const q = LUMEN_DATA.queue;
  const [secs, setSecs] = React.useState(8 * 60);
  React.useEffect(() => {
    const id = setInterval(() => setSecs(s => Math.max(0, s - 1)), 1000);
    return () => clearInterval(id);
  }, []);
  const mm = String(Math.floor(secs/60)).padStart(2,'0');
  const ss = String(secs%60).padStart(2,'0');

  return (
    <Screen dark={dark} pad={false}>
      <div style={{ padding: '62px 20px 0', display: 'flex', justifyContent: 'space-between', marginBottom: 24 }}>
        <BackButton dark={dark} onClick={() => go('home')} />
        <div style={{ fontSize: 13, color: t.textMuted, alignSelf: 'center', fontWeight: 500 }}>Atualiza ao vivo</div>
        <div style={{ width: 38 }} />
      </div>

      <div style={{ padding: '0 20px' }}>
        {/* Hero counter */}
        <Card dark={dark} tone="dark" padding={28} style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 11, color: 'rgba(236,232,245,0.5)', letterSpacing: 1.4, textTransform: 'uppercase', fontWeight: 700 }}>
            Sua posição na fila
          </div>
          <div style={{
            fontFamily: LUMEN_FONTS.serif, fontSize: 120, color: t.queueText,
            lineHeight: 1, letterSpacing: -4, marginTop: 8,
          }}>
            {q.position}<span style={{ color: t.accent, fontSize: 60 }}>º</span>
          </div>
          <div style={{ fontSize: 14, color: 'rgba(236,232,245,0.65)', marginTop: 4 }}>
            {q.ahead} pessoa na sua frente
          </div>

          <div style={{
            marginTop: 22, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            padding: '10px 16px', borderRadius: 99, background: 'rgba(236,232,245,0.08)',
            display: 'inline-flex',
          }}>
            <Icon name="clock" size={16} color={t.accent} />
            <span style={{ color: t.queueText, fontSize: 14, fontWeight: 500 }}>
              Estimativa <strong style={{ fontFamily: LUMEN_FONTS.serif, fontSize: 18, marginLeft: 4 }}>{mm}:{ss}</strong>
            </span>
          </div>
        </Card>

        {/* Ticket info */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14 }}>
          <Card dark={dark} padding={14}>
            <div style={{ fontSize: 11, color: t.textMuted, letterSpacing: 1, textTransform: 'uppercase', fontWeight: 600 }}>Senha</div>
            <div style={{ fontFamily: LUMEN_FONTS.serif, fontSize: 28, color: t.text, marginTop: 2 }}>B-042</div>
          </Card>
          <Card dark={dark} padding={14}>
            <div style={{ fontSize: 11, color: t.textMuted, letterSpacing: 1, textTransform: 'uppercase', fontWeight: 600 }}>Sala provável</div>
            <div style={{ fontFamily: LUMEN_FONTS.serif, fontSize: 20, color: t.text, marginTop: 4, letterSpacing: -0.2 }}>Sala 3 · RM</div>
          </Card>
        </div>

        {/* Live board */}
        <div style={{ fontSize: 11, color: t.textMuted, textTransform: 'uppercase', letterSpacing: 1.2, fontWeight: 600, padding: '22px 4px 10px' }}>
          Chamadas recentes
        </div>
        <Card dark={dark} padding={0}>
          {q.calling.map((c, i) => (
            <div key={i} style={{
              padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12,
              borderBottom: i < q.calling.length - 1 ? `1px solid ${t.border}` : 'none',
            }}>
              <div style={{
                width: 8, height: 8, borderRadius: 99,
                background: c.status === 'calling' ? t.accent : c.status === 'in-progress' ? t.warning : t.textSubtle,
                animation: c.status === 'calling' ? 'pulse 1.2s infinite' : 'none',
              }} />
              <div style={{ fontFamily: LUMEN_FONTS.serif, fontSize: 18, color: t.text, letterSpacing: -0.2, minWidth: 70 }}>{c.ticket}</div>
              <div style={{ flex: 1, fontSize: 13, color: t.textMuted }}>{c.room}</div>
              <div style={{ fontSize: 11, color: c.status === 'calling' ? t.accent : t.textSubtle, textTransform: 'uppercase', letterSpacing: 0.8, fontWeight: 700 }}>
                {c.status === 'calling' ? 'Chamando' : c.status === 'in-progress' ? 'Em sala' : 'Concluído'}
              </div>
            </div>
          ))}
        </Card>

        <div style={{
          marginTop: 18, padding: 14, borderRadius: 16, background: t.accentBg,
          display: 'flex', gap: 10, alignItems: 'start',
        }}>
          <Icon name="info" size={18} color={t.accent} />
          <div style={{ flex: 1, fontSize: 13, color: dark ? t.text : '#3A2760', lineHeight: 1.4 }}>
            Vamos te avisar por notificação quando faltarem 2 minutos para sua chamada.
          </div>
        </div>
        <div style={{ height: 20 }} />
      </div>
    </Screen>
  );
}

window.CheckinScreen = CheckinScreen;
window.QueueScreen = QueueScreen;
