// EN House web — physical-card activation: scan QR → magic link → in

// ───────────────────────── Scan the card ─────────────────────────
function ScanCard({ D, onBack, onFound }) {
  const [found, setFound] = React.useState(false);
  const doneRef = React.useRef(false);

  const detect = React.useCallback(() => {
    if (doneRef.current) return;
    doneRef.current = true;
    setFound(true);
    setTimeout(() => onFound(), 1050);
  }, [onFound]);

  // auto-detect after a beat (prototype: no real camera)
  React.useEffect(() => {
    const t = setTimeout(detect, 2800);
    return () => clearTimeout(t);
  }, [detect]);

  return (
    <>
      <AuthBar onBack={onBack} right={<span className="cap">Cartão físico</span>} />
      <Centered max={440}>
        <div className="fade" style={{ textAlign: "center" }}>
          <Eyebrow accent style={{ marginBottom: 14 }}>O teu cartão chegou</Eyebrow>
          <h1 className="h1">Aponta ao código.</h1>
          <p className="body" style={{ margin: "12px auto 30px", maxWidth: 340 }}>
            Vira o cartão que recebeste por correio e enquadra o código no verso. A casa faz o resto.
          </p>

          <div className={"scan-view" + (found ? " found" : "")} onClick={detect} role="button"
            aria-label="Área de leitura do código" style={{ cursor: found ? "default" : "pointer" }}>
            <div className="scan-card">
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "#E9D4A8" }}>
                  <Brush size={14} color="#E9D4A8" />
                  <span style={{ fontWeight: 900, fontSize: 8.5, letterSpacing: ".2em", color: "#F4E8D2" }}>EN&nbsp;HOUSE</span>
                </span>
                <span style={{ fontSize: 8, letterSpacing: ".18em", color: "rgba(244,232,210,.55)", fontWeight: 700 }}>Nº 047</span>
              </div>
              <div style={{ background: "#140c08", borderRadius: 7, padding: 9 }}><FauxQR size={140} /></div>
            </div>
            <div className="recticle"><i className="tl" /><i className="tr" /><i className="bl" /><i className="br" /></div>
            {!found && <div className="scan-line" />}
          </div>

          <div style={{ marginTop: 26, display: "flex", alignItems: "center", justifyContent: "center", gap: 10, minHeight: 24 }}>
            {found
              ? <><Icon name="check" size={18} style={{ color: "var(--accent)" }} /><span className="cap" style={{ color: "var(--accent)", letterSpacing: ".14em" }}>Código lido</span></>
              : <><Spinner /><span className="cap" style={{ letterSpacing: ".14em" }}>À procura do código…</span></>}
          </div>

          <p style={{ marginTop: 24, display: "flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
            <Icon name="lock" size={13} style={{ color: "var(--ink-3)" }} />
            <span className="cap">Cada cartão lê uma só vez. O código não sai do teu telemóvel.</span>
          </p>
        </div>
      </Centered>
    </>
  );
}

// ───────────────────────── Magic link from the card ─────────────────────────
function CardLink({ D, onEnter, onBack }) {
  const m = D.member;
  const [opening, setOpening] = React.useState(false);
  const token = "047-" + Math.random().toString(16).slice(2, 8);
  const open = () => { setOpening(true); setTimeout(onEnter, 950); };

  return (
    <>
      <AuthBar onBack={onBack} />
      <Centered max={460}>
        <div className="fade" style={{ textAlign: "center", paddingTop: 8 }}>
          <div style={{ width: 72, height: 72, borderRadius: 999, margin: "0 auto 24px",
            background: "color-mix(in srgb, var(--accent) 12%, transparent)", border: "1px solid var(--line-2)",
            display: "flex", alignItems: "center", justifyContent: "center", color: "var(--accent)" }}>
            <Icon name="check" size={32} stroke={2} />
          </div>
          <Eyebrow accent>Cartão reconhecido</Eyebrow>
          <h1 className="h1" style={{ margin: "14px 0 0" }}>Bem-vindo de volta, {m.name.split(" ")[0]}.</h1>

          <div style={{ margin: "30px 0 0", padding: "22px 24px", textAlign: "left", background: "var(--bg-2)",
            borderRadius: 8, border: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 16 }}>
            <div style={{ width: 46, height: 46, borderRadius: 8, background: "linear-gradient(160deg,#211712,#16100c)",
              display: "flex", alignItems: "center", justifyContent: "center", color: "#E9D4A8", flexShrink: 0 }}>
              <Icon name="card" size={22} />
            </div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 800, fontSize: 16 }}>{m.name}</div>
              <div className="cap" style={{ marginTop: 3, letterSpacing: ".14em" }}>{m.no} · Membro fundador · {m.seat}</div>
            </div>
          </div>

          <div style={{ margin: "16px 0 0", padding: "14px 16px", display: "flex", alignItems: "center", gap: 12,
            background: "color-mix(in srgb, var(--accent) 6%, transparent)", border: "1px dashed var(--line-2)", borderRadius: 8 }}>
            <Icon name="key" size={16} style={{ color: "var(--accent)", flexShrink: 0 }} />
            <div style={{ textAlign: "left", minWidth: 0 }}>
              <div className="cap" style={{ letterSpacing: ".1em" }}>Link de acesso único</div>
              <div style={{ fontFamily: "monospace", fontSize: 12.5, color: "var(--ink)", marginTop: 2,
                overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>enhouse.pt/c/{token}</div>
            </div>
          </div>

          <p className="small" style={{ margin: "16px auto 0", maxWidth: 360 }}>
            Gerámos este link a partir do teu cartão. Vale uma vez, só neste dispositivo — depois disto, entras com um toque.
          </p>

          <div style={{ marginTop: 28 }}>
            <Button variant="primary" block disabled={opening} onClick={open} icon={opening ? null : "arrowR"}>
              {opening ? <Spinner /> : null}{opening ? "A abrir a casa…" : "Entrar na EN House"}
            </Button>
          </div>
        </div>
      </Centered>
    </>
  );
}

Object.assign(window, { ScanCard, CardLink });
