/* flow_approvals.jsx — Face ID approvals exploration (proposed, Nov 16 2026).
   Phones approve with a key the Yoshi app keeps in the phone's secure chip,
   unlocked by Face ID. Web keeps passkeys. Enabled with `?approvals=faceid`;
   without it the existing passkey Security step is unchanged.

   Screens:
   - FaceIdSecurity   onboarding Security step on the phone (replaces passkey creation)
   - NewPhoneSetup       "Link this iPhone": sign-in on an iPhone with no key
   - Another device's request (link a computer or a new iPhone, approve a web transfer) is a
     standard Needs You Brief in the app: the Camera scans the code and opens app/index.html?brief=…
   All interactions are simulated; nothing creates a credential or calls Yoshi. */

// One approvals choice per tab: ?approvals=faceid|faceid-phone|passkeys sets it, Tweaks › Approvals changes it.
const FACE_ID_APPROVALS = (() => {
  let mode = new URLSearchParams(location.search).get("approvals");
  try { if (mode) sessionStorage.setItem("lucid-approvals", mode); mode = mode || sessionStorage.getItem("lucid-approvals"); } catch {}
  return mode === "faceid" || mode === "faceid-phone";
})();
const setApprovalsMode = (mode) => { const url = new URL(location.href); url.searchParams.set("approvals", mode); location.replace(url.href); };
// The core web and mobile apps: next door when every prototype is served from one root, else their hosted sites.
const prototypeUrl = (app, path) => {
  const root = location.pathname.match(/^(.*)\/(?:web|mobile)-onboarding\//);
  return root ? `${root[1]}/${app}/${path}` : `https://${app}-prototype.yoshi.ai/${path}`;
};

/* Face ID glyph: four corner brackets, eyes, nose and smile. */
const FaceIdGlyph = ({ size = 22, color = "currentColor", stroke = 1.6 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={stroke} strokeLinecap="round" aria-hidden="true">
    <path d="M3 8V5.5A2.5 2.5 0 0 1 5.5 3H8" /><path d="M16 3h2.5A2.5 2.5 0 0 1 21 5.5V8" />
    <path d="M21 16v2.5a2.5 2.5 0 0 1-2.5 2.5H16" /><path d="M8 21H5.5A2.5 2.5 0 0 1 3 18.5V16" />
    <path d="M8.5 9v1.5" /><path d="M15.5 9v1.5" /><path d="M12 9v4h-1" /><path d="M9 16c1.6 1.3 4.4 1.3 6 0" />
  </svg>
);

const ComputerGlyph = ({ size = 20, color = "currentColor" }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" aria-hidden="true">
    <rect x="3.5" y="4.5" width="17" height="11.5" rx="1.5" /><path d="M2 19.5h20" />
  </svg>
);

const PhoneGlyph = ({ size = 20, color = "currentColor", stroke = 1.6 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={stroke} strokeLinecap="round" aria-hidden="true">
    <rect x="6.5" y="2.5" width="11" height="19" rx="2.5" /><path d="M10.5 18.5h3" />
  </svg>
);

const PersonGlyph = ({ size = 20, color = "currentColor" }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" aria-hidden="true">
    <circle cx="12" cy="8.5" r="3.5" /><path d="M5 20c0-4.5 3-6 7-6s7 1.5 7 6" />
  </svg>
);

const CheckGlyph = ({ size = 16, color = "currentColor" }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M5 12.5l4.5 4.5L19 7" />
  </svg>
);

/* Required switch row for enabling Face ID; same Lucid tile and switch art as Security. */
const FaceIdTile = ({ state, onTurnOn }) => {
  const working = state === "working";
  const done = state === "done";
  return <button className="press ld-funding-tile ld-security-tile" type="button" role="switch" aria-checked={done}
    aria-label={done ? "Face ID on" : "Enable Face ID · Required"}
    disabled={working || done} onClick={onTurnOn}>
    <span className="ld-funding-icon" style={{ color: "var(--ink-2)" }}><FaceIdGlyph /></span>
    <span className="ld-funding-copy"><strong>{working ? "Waiting for Face ID…" : done ? "Face ID on" : "Enable Face ID"}</strong>{!done && <small>Required</small>}</span>
    <SecuritySwitchArt on={done} />
  </button>;
};

const useFaceIdTile = () => {
  const [state, setState] = useState("idle");
  useEffect(() => {
    if (state !== "working") return;
    const t = setTimeout(() => setState("done"), 1300);
    return () => clearTimeout(t);
  }, [state]);
  return [state, () => setState("working")];
};

const ApprovalNote = ({ children, icon = "shield" }) => (
  <div style={{ marginTop: 16, display: "flex", alignItems: "flex-start", gap: 9, fontFamily: "var(--f-display)", fontSize: 11, lineHeight: 1.5, color: "var(--ink-3)" }}>
    <Icon name={icon} size={14} color="var(--ink-3)" />
    <span>{children}</span>
  </div>
);

/* A bordered callout for safety copy. */
const ApprovalCallout = ({ tone = "neutral", children }) => (
  <div role={tone === "warn" ? "note" : undefined} style={{
    marginTop: 14, padding: "12px 14px", borderRadius: 14, fontFamily: "var(--f-display)", fontSize: 13, lineHeight: 1.45,
    color: "var(--ink)", background: tone === "warn" ? "color-mix(in srgb, var(--signal-neg) 7%, var(--bg-card))" : "var(--bg-2)",
    border: `1px solid ${tone === "warn" ? "color-mix(in srgb, var(--signal-neg) 28%, transparent)" : "var(--rule-2)"}`
  }}>{children}</div>
);

const ChoiceTile = ({ glyph, title, detail, onClick }) => (
  <button type="button" className="press ld-funding-tile" onClick={onClick}>
    <span className="ld-funding-icon" style={{ color: "var(--ink-2)" }}>{glyph}</span>
    <span className="ld-funding-copy"><strong>{title}</strong><small>{detail}</small></span>
    <img className="ld-funding-chevron" src="assets/lucid-chevron.svg" alt="" />
  </button>
);

const StatusLine = ({ done, waiting, doneText }) => (
  <div role="status" style={{ marginTop: 16, display: "flex", alignItems: "center", gap: 10, fontFamily: "var(--f-display)", fontSize: 14, color: done ? "var(--ink)" : "var(--ink-3)" }}>
    {done
      ? <span style={{ width: 22, height: 22, borderRadius: 999, background: "var(--ink)", color: "var(--bg)", display: "grid", placeItems: "center" }}><CheckGlyph size={13} /></span>
      : <span className="ld-approval-pulse" aria-hidden="true" style={{ width: 10, height: 10, margin: "0 6px", borderRadius: 999, background: "var(--ink-3)" }} />}
    <span>{done ? doneText : waiting}</span>
  </div>
);

/* ---------------------------------------------------------------------------
   07 · SECURITY (Face ID variant) — enabling Face ID creates the phone's approval key behind the scenes.
   --------------------------------------------------------------------------- */
const FaceIdSecurity = ({ onNext }) => {
  const [faceId, turnOn] = useFaceIdTile();
  const [notifs, setNotifs] = useState(false);
  return (
    <Screen>
      <Body>
        <H>Keep your money <Accent>secure.</Accent></H>
        <Sub>Use Face ID to approve transactions.</Sub>
        <div style={{ display: "grid", gap: 11, marginTop: 22 }}>
          <FaceIdTile state={faceId} onTurnOn={turnOn} />
          <NotifToggle on={notifs} onToggle={() => setNotifs((n) => !n)} />
        </div>
        <ApprovalNote>If Face ID isn’t available, you can use your iPhone passcode. Notifications are optional and you can enable them later in settings.</ApprovalNote>
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <Btn full disabled={faceId !== "done"} onClick={onNext}>Continue</Btn>
      </Dock>
    </Screen>
  );
};

/* ---------------------------------------------------------------------------
   LINK THIS IPHONE — sign-in in the app on an iPhone with no key: signed up on web,
   a new iPhone, a reinstall or restore, or an iPhone removed in Settings.
   The phone is stopped here until it is linked. The QR code always shows on the
   desktop web app (Settings › Security › Link a new phone) and this phone scans it. No typed codes.
   choose → desktop (Settings › Security on the web app) → scan → approve on computer → Face ID
          → other iPhone (this phone shows a QR code, the other phone scans it) → Face ID
          → verify identity → Face ID
   --------------------------------------------------------------------------- */
const START_VIEW = new URLSearchParams(location.search).get("view");

/* Simulated camera viewfinder. It shows no QR code, so nobody mistakes it for a code to scan. */
const Viewfinder = () => (
  <div aria-label="Camera viewfinder" style={{ marginTop: 24, aspectRatio: "1 / 1", maxWidth: "100%", borderRadius: 28, background: "#16181b", display: "grid", placeItems: "center", position: "relative", overflow: "hidden" }}>
    <span style={{ fontFamily: "var(--f-display)", fontSize: 12, color: "rgb(255 255 255 / 60%)" }}>Camera</span>
    {[["top", "left"], ["top", "right"], ["bottom", "left"], ["bottom", "right"]].map(([v, h]) => (
      <span key={v + h} aria-hidden="true" style={{ position: "absolute", [v]: "14%", [h]: "14%", width: 34, height: 34,
        [`border${v[0].toUpperCase() + v.slice(1)}`]: "3px solid #fff", [`border${h[0].toUpperCase() + h.slice(1)}`]: "3px solid #fff",
        [`border${v[0].toUpperCase() + v.slice(1)}${h[0].toUpperCase() + h.slice(1)}Radius`]: 10 }} />
    ))}
  </div>
);

const DetailRows = ({ rows }) => (
  <div style={{ marginTop: 22, borderRadius: 24, background: "var(--bg-card)", border: "1px solid var(--rule-2)", padding: "4px 18px" }}>
    {rows.map(([k, v], i) => (
      <div key={k} style={{ display: "flex", justifyContent: "space-between", gap: 16, padding: "13px 0", borderTop: i ? "1px solid var(--rule)" : "none", fontFamily: "var(--f-display)", fontSize: 14 }}>
        <span style={{ color: "var(--ink-3)" }}>{k}</span><span style={{ textAlign: "right" }}>{v}</span>
      </div>
    ))}
  </div>
);

const NewPhoneSetup = ({ onDone }) => {
  const [view, setView] = useState(START_VIEW || "choose");
  const [approved, setApproved] = useState(false);
  const [checking, setChecking] = useState("idle"); // idle → checking → done
  const [faceId, turnOn] = useFaceIdTile();

  useEffect(() => {
    if (view !== "scan") return;
    const t = setTimeout(() => setView("waiting"), 2400);   // simulated scan of the web app's code
    return () => clearTimeout(t);
  }, [view]);
  useEffect(() => {
    if ((view !== "waiting" && view !== "otherPhone") || approved) return;
    const t = setTimeout(() => setApproved(true), 4000);    // simulated passkey approval on yoshi.ai
    return () => clearTimeout(t);
  }, [view, approved]);
  useEffect(() => {
    if (checking !== "checking") return;
    const t = setTimeout(() => setChecking("done"), 2200);
    return () => clearTimeout(t);
  }, [checking]);

  if (view === "desktop") return (
    <Screen>
      <Body>
        <H>Open Yoshi on your <Accent>computer.</Accent></H>
        <Sub>Get a code from the Yoshi web app on your computer.</Sub>
        <ol className="ld-verification-steps">
          {[["display", "Sign in on yoshi.ai", "On your computer"], ["lock", "Go to Settings › Security", "Choose Link a new phone"], ["eye", "Scan its code", "With this iPhone"]].map(([icon, t, s]) => (
            <li key={t}>
              <span className="ld-step-icon" aria-hidden="true"><Icon name={icon} size={22} stroke={1.7} /></span>
              <div><h3>{t}</h3><p>{s}</p></div>
            </li>
          ))}
        </ol>
        <ApprovalNote>The code expires in 10 minutes. You’ll approve on your computer with the passkey you already use there.</ApprovalNote>
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <Btn full onClick={() => setView("scan")}>Scan code</Btn>
        <SkipLink onClick={() => setView("identity")}>Verify your identity instead</SkipLink>
      </Dock>
    </Screen>
  );

  if (view === "otherPhone") return (
    <Screen>
      <Body>
        <H>Scan this code with your <Accent>other iPhone.</Accent></H>
        <Sub>On the iPhone you already use, point the camera at the code. Check the details in Yoshi and confirm with Face ID.</Sub>
        <div aria-label="QR code for linking this iPhone" style={{ margin: "24px auto 0", width: "62%", aspectRatio: "1 / 1", padding: 14, borderRadius: 24, background: "#fff", border: "1px solid var(--rule-2)", boxSizing: "border-box" }}><DemoQr /></div>
        <StatusLine done={approved} waiting="Waiting for your other iPhone…" doneText="Approved on your other iPhone" />
        <ApprovalNote>This code expires in 10 minutes. Never let anyone else scan it.</ApprovalNote>
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <Btn full disabled={!approved} onClick={() => setView("faceid")}>Continue</Btn>
        <SkipLink onClick={() => setView("identity")}>Verify your identity instead</SkipLink>
      </Dock>
    </Screen>
  );

  if (view === "scan") return (
    <Screen>
      <Body>
        <H>Scan the code on your <Accent>computer.</Accent></H>
        <Sub>Point your camera at the code in Settings › Security on yoshi.ai.</Sub>
        <Viewfinder />
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <Btn kind="ghost" full onClick={() => setView("desktop")}>Cancel</Btn>
      </Dock>
    </Screen>
  );

  if (view === "waiting") return (
    <Screen>
      <Body>
        <H>Approve on your <Accent>computer.</Accent></H>
        <Sub>Your computer now shows this iPhone’s details. Check them there and approve with your passkey.</Sub>
        <DetailRows rows={[["This iPhone", "iPhone 16 Pro"], ["Approving on", "Chrome on Mac"]]} />
        <StatusLine done={approved} waiting="Waiting for your computer…" doneText="Approved on your computer" />
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <Btn full disabled={!approved} onClick={() => setView("faceid")}>Continue</Btn>
        <SkipLink onClick={() => setView("identity")}>Verify your identity instead</SkipLink>
      </Dock>
    </Screen>
  );

  if (view === "identity") return (
    <Screen>
      <Body>
        <H>Verify your <Accent>identity.</Accent></H>
        <Sub>Take a quick selfie so we can match it to your account. Have a photo ID ready in case we ask for it.</Sub>
        <div style={{ display: "grid", gap: 11, marginTop: 22 }}>
          <button className="press ld-funding-tile" type="button" disabled={checking !== "idle"} onClick={() => setChecking("checking")}>
            <span className="ld-funding-icon" style={{ color: "var(--ink-2)" }}><PersonGlyph /></span>
            <span className="ld-funding-copy"><strong>{checking === "idle" ? "Start verification" : checking === "checking" ? "Checking your selfie…" : "Identity verified"}</strong><small>Usually takes under a minute</small></span>
            {checking === "done" ? <CheckGlyph size={18} /> : <img className="ld-funding-chevron" src="assets/lucid-chevron.svg" alt="" />}
          </button>
        </div>
        <ApprovalNote>Verifying links this iPhone only. Your other devices keep working.</ApprovalNote>
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <Btn full disabled={checking !== "done"} onClick={() => setView("faceid")}>Continue</Btn>
      </Dock>
    </Screen>
  );

  if (view === "faceid") return (
    <Screen>
      <Body>
        <H>Enable <Accent>Face ID.</Accent></H>
        <Sub>This iPhone is linked. From now on you’ll approve trades and money movements here with Face ID.</Sub>
        <div style={{ display: "grid", gap: 11, marginTop: 22 }}>
          <FaceIdTile state={faceId} onTurnOn={turnOn} />
        </div>
        <ApprovalNote>We’ve let you know by text and on your other devices that this iPhone was added.</ApprovalNote>
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <Btn full disabled={faceId !== "done"} onClick={onDone}>Continue</Btn>
      </Dock>
    </Screen>
  );

  return (
    <Screen style={{ position: "relative", isolation: "isolate", overflow: "hidden" }}>
      <div className="ld-welcome-wash ld-wait-wash" aria-hidden="true" />
      <Body>
        <div style={{ marginTop: 18 }}><MotionLogo size={64} /></div>
        <H>Link <Accent>this iPhone.</Accent></H>
        <Sub>Link this iPhone to your account before you use Yoshi here.</Sub>
        <SubHead>Choose how to link</SubHead>
        <div style={{ display: "grid", gap: 9 }}>
          <ChoiceTile glyph={<Icon name="display" size={24} stroke={1.75} />} title="Link with the desktop web app" detail="Scan a code on your computer" onClick={() => setView("desktop")} />
          <ChoiceTile glyph={<PhoneGlyph size={24} stroke={1.75} />} title="Link with your other iPhone" detail="Scan this iPhone’s code with the one you already use" onClick={() => setView("otherPhone")} />
          <ChoiceTile glyph={<Icon name="profile" size={24} stroke={1.75} />} title="Verify your identity" detail="We will reverify your identity" onClick={() => setView("identity")} />
        </div>
        <ApprovalNote>Never approve because someone asked you to, even if they say they’re from Yoshi.</ApprovalNote>
      </Body>
    </Screen>
  );
};

/* Decorative QR-style mark for the scan demo. It encodes nothing. */
const DemoQr = () => {
  const n = 25;
  const cells = [];
  let seed = 7;
  const rand = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff; };
  const inFinder = (x, y) => [[0, 0], [n - 7, 0], [0, n - 7]].some(([fx, fy]) => x >= fx - 1 && x < fx + 8 && y >= fy - 1 && y < fy + 8);
  for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) if (!inFinder(x, y) && rand() > 0.52) cells.push(<rect key={x + "-" + y} x={x} y={y} width="1" height="1" />);
  const finder = (fx, fy) => <g key={fx + ":" + fy}><rect x={fx} y={fy} width="7" height="7" /><rect x={fx + 1} y={fy + 1} width="5" height="5" fill="#fff" /><rect x={fx + 2} y={fy + 2} width="3" height="3" /></g>;
  return <svg viewBox={`0 0 ${n} ${n}`} width="100%" height="100%" shapeRendering="crispEdges" fill="#111" aria-hidden="true">{cells}{finder(0, 0)}{finder(n - 7, 0)}{finder(0, n - 7)}</svg>;
};

/* iOS's own Face ID prompt, shown the moment the user taps an approve button. Simulated: it succeeds, then calls onDone. */
const FaceIdPrompt = ({ onDone }) => {
  const [done, setDone] = useState(false);
  useEffect(() => {
    const scan = setTimeout(() => setDone(true), 1100);
    const finish = setTimeout(onDone, 1700);
    return () => { clearTimeout(scan); clearTimeout(finish); };
  }, []);
  return (
    <div role="status" aria-label={done ? "Face ID recognized" : "Face ID"} style={{ position: "absolute", inset: 0, zIndex: 70, display: "grid", placeItems: "center", background: "rgba(0,0,0,0.12)" }}>
      <div style={{ width: 150, height: 150, borderRadius: 30, background: "rgba(245,245,245,0.94)", backdropFilter: "blur(20px)", WebkitBackdropFilter: "blur(20px)", boxShadow: "0 12px 40px rgba(0,0,0,0.22)", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 14, color: "#111" }}>
        {done ? <span style={{ width: 64, height: 64, display: "grid", placeItems: "center" }}><CheckGlyph size={52} /></span> : <span className="ld-approval-pulse" style={{ display: "grid" }}><FaceIdGlyph size={64} stroke={1.4} /></span>}
        <span style={{ fontFamily: "-apple-system, BlinkMacSystemFont, var(--f-display)", fontSize: 15, fontWeight: 500 }}>Face ID</span>
      </div>
    </div>
  );
};

/* ---------------------------------------------------------------------------
   CAMERA DEEP LINK (Nov 25 2026). The web app's code is a universal link
   (https://yoshi.ai/link/<one-time code>), so the iPhone Camera can scan it too.
   `?approvals=faceid&camera=1` opens on the Camera with the app installed;
   `camera=noapp` starts without it. Add `account=other` to see the refusal when
   the code belongs to a different account.
   App installed:  banner "Open in Yoshi" → Log in sheet → approve on the computer → enable
   No app:         banner opens the link, which redirects straight to TestFlight (https://testflight.apple.com/join/NmyVUp6H); after installing, scan again
   --------------------------------------------------------------------------- */
const AppMark = ({ size = 26 }) => (
  <span aria-hidden="true" style={{ width: size, height: size, borderRadius: size * 0.24, background: "#111", color: "#fff", display: "grid", placeItems: "center", fontFamily: "var(--f-display)", fontWeight: 600, fontSize: size * 0.5, flex: "none" }}>Y</span>
);

const CameraScan = ({ installed: startInstalled, onOpenApp }) => {
  const installed = startInstalled;
  const [found, setFound] = useState(false);
  useEffect(() => {
    const t = setTimeout(() => setFound(true), 1400);   // simulated: the camera recognizes the code
    return () => clearTimeout(t);
  }, []);
  // No app: yoshi.ai/link/<code> redirects straight to the app's store page (TestFlight until launch).
  const getApp = () => window.open("https://testflight.apple.com/join/NmyVUp6H", "_blank", "noopener");
  const page = { position: "absolute", inset: 0, zIndex: 60, display: "flex", flexDirection: "column", fontFamily: "var(--f-display)" };

  return (
    <div style={{ ...page, background: "#0b0b0b", color: "#fff", alignItems: "center" }}>
      <div style={{ marginTop: 58, fontSize: 13, letterSpacing: "0.08em", color: "#f5c542" }}>PHOTO</div>
      <div style={{ position: "relative", marginTop: 80, width: 210, height: 210 }}>
        <div aria-label="The code on your computer, in the camera" style={{ position: "absolute", inset: 22, background: "#fff", borderRadius: 10, padding: 10, transform: "rotate(-4deg)", opacity: 0.92 }}><DemoQr /></div>
        {found && <div aria-hidden="true" style={{ position: "absolute", inset: 10, border: "2px solid #f5c542", borderRadius: 14 }} />}
      </div>
      {found ? (
        <button type="button" className="press" onClick={installed ? onOpenApp : getApp}
          style={{ marginTop: 26, display: "flex", alignItems: "center", gap: 10, padding: "8px 16px 8px 8px", borderRadius: 999, border: "none", background: "#f5c542", color: "#111", fontFamily: "var(--f-display)", fontSize: 15, fontWeight: 500, cursor: "pointer" }}>
          {installed ? <AppMark size={26} /> : <span style={{ width: 8 }} />}
          {installed ? "Open in Yoshi" : "Open “yoshi.ai” in Safari"}
        </button>
      ) : (
        <div role="status" style={{ marginTop: 34, fontSize: 14, color: "rgba(255,255,255,.6)" }}>Point your camera at the code on your computer</div>
      )}
      <div style={{ marginTop: "auto", marginBottom: 40, width: 68, height: 68, borderRadius: 999, border: "4px solid #fff", display: "grid", placeItems: "center" }}>
        <div style={{ width: 54, height: 54, borderRadius: 999, background: "#fff" }} />
      </div>
    </div>
  );
};

Object.assign(window, { FaceIdPrompt, CameraScan, FACE_ID_APPROVALS, FaceIdGlyph, FaceIdSecurity, NewPhoneSetup, DemoQr });
