/* flow_approvals.jsx — Face ID approvals exploration (proposed, Nov 16 2026), web side.
   Phones approve with a Face ID key held by the Yoshi app; web keeps passkeys.
   Enabled with `?approvals=faceid`. The web onboarding Security step stays as it is today.

   Screens:
   - ApprovalSetup            the linking steps after the login screen's passkey test fails
   - ApprovePhone             the web Brief whose QR code a new iPhone scans, then the passkey approves
   - ApproveWithPhone         a QR code at each transaction for a computer set to "Use my phone for approvals" 
   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}`;
};

const PhoneGlyph = ({ 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="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 passkey switch for this computer; same Lucid tile and switch art as Security. */
const ComputerPasskeyTile = ({ state, onCreate }) => {
  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 ? "Passkey for this computer created" : "Create a passkey for this computer · Required"}
    disabled={working || done} onClick={onCreate}>
    <span className="ld-funding-icon"><img src="assets/lucid-security-shield.svg" alt="" /></span>
    <span className="ld-funding-copy"><strong>{working ? "Setting up…" : done ? "Passkey on" : "Create a passkey for this computer"}</strong>{!done && <small>Required</small>}</span>
    <SecuritySwitchArt on={done} />
  </button>;
};

const useTimedState = (from, to, ms) => {
  const [state, setState] = useState("idle");
  useEffect(() => {
    if (state !== from) return;
    const t = setTimeout(() => setState(to), ms);
    return () => clearTimeout(t);
  }, [state]);
  return [state, setState];
};

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

const ApprovalCallout = ({ tone = "neutral", children }) => (
  <div role={tone === "warn" ? "note" : undefined} style={{
    marginTop: 14, padding: "12px 14px", borderRadius: 14, maxWidth: 560, 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>
);

/* Selectable option; selected state is a black outline, matching the Lucid choice treatment. */
const OptionTile = ({ glyph, title, detail, selected, onClick }) => (
  <button type="button" className="press ld-funding-tile" role="radio" aria-checked={selected} onClick={onClick}
    style={{ gridTemplateColumns: "48px minmax(0, 1fr) 22px", outline: selected ? "2px solid var(--ink)" : "none", outlineOffset: -2 }}>
    <span className="ld-funding-icon" style={{ color: "var(--ink-2)" }}>{glyph}</span>
    <span className="ld-funding-copy"><strong>{title}</strong><small>{detail}</small></span>
    <span aria-hidden="true" style={{ width: 20, height: 20, borderRadius: 999, border: `1.5px solid ${selected ? "var(--ink)" : "var(--rule-2)"}`, display: "grid", placeItems: "center" }}>
      {selected && <span style={{ width: 10, height: 10, borderRadius: 999, background: "var(--ink)" }} />}
    </span>
  </button>
);

const StatusLine = ({ done, waiting, doneText }) => (
  <div role="status" style={{ marginTop: 18, 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>
);

/* Decorative QR-style mark for the 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>;
};

/* ---------------------------------------------------------------------------
   LINK THIS COMPUTER — after a failed passkey test on the login screen (flow1.jsx Welcome),
   which hands over the option picked there. `choose` remains as a deep link.
   choose → scan (QR, approved on the phone) → passkey → done
          → use my phone for approvals → done (a QR code shows at each transaction)
          → verify identity → passkey → done
   The computer is stopped until it is linked. There are no typed codes.
   --------------------------------------------------------------------------- */
const START_VIEW = new URLSearchParams(location.search).get("view");

/* Simulated browser passkey sheet; the real one is drawn by the browser, not Yoshi. */
const BrowserPasskeySheet = ({ none, onUse, onCancel }) => (
  <div role="dialog" aria-label="Browser passkey prompt" style={{ position: "fixed", inset: 0, zIndex: 400, display: "grid", placeItems: "start center", paddingTop: 90, background: "rgba(0,0,0,0.18)" }}>
    <div style={{ width: 380, maxWidth: "calc(100% - 32px)", padding: 20, borderRadius: 14, background: "#fff", boxShadow: "0 18px 50px rgba(0,0,0,0.22)", fontFamily: "system-ui, -apple-system, sans-serif", color: "#1f1f1f" }}>
      <div style={{ fontSize: 12, color: "#5f6368" }}>yoshi.ai</div>
      <div style={{ marginTop: 6, fontSize: 17, fontWeight: 600 }}>{none ? "No passkeys available" : "Use your passkey for yoshi.ai?"}</div>
      <div style={{ marginTop: 8, fontSize: 13.5, lineHeight: 1.45, color: "#444" }}>{none
        ? "There aren’t any passkeys for yoshi.ai on this device."
        : "You’ll use Touch ID or your password manager to confirm it’s you."}</div>
      <div style={{ marginTop: 18, display: "flex", justifyContent: "flex-end", gap: 8 }}>
        <button type="button" onClick={onCancel} style={{ padding: "8px 16px", borderRadius: 999, border: "1px solid #dadce0", background: "#fff", fontSize: 14, cursor: "pointer" }}>Cancel</button>
        {!none && <button type="button" onClick={onUse} style={{ padding: "8px 16px", borderRadius: 999, border: "none", background: "#1a73e8", color: "#fff", fontSize: 14, cursor: "pointer" }}>Continue</button>}
      </div>
    </div>
  </div>
);

const QrGlyph = ({ size = 20, color = "currentColor" }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <rect x="3.5" y="3.5" width="6.5" height="6.5" rx="1" /><rect x="14" y="3.5" width="6.5" height="6.5" rx="1" /><rect x="3.5" y="14" width="6.5" height="6.5" rx="1" />
    <path d="M14 14h2.5v2.5" /><path d="M20.5 14v6.5H17" /><path d="M14 20.5v-1.5" />
  </svg>
);

const QrFrame = ({ label, size = 196 }) => (
  <div aria-label={label} style={{ width: size, height: size, padding: 14, borderRadius: 20, background: "#fff", border: "1px solid var(--rule-2)", boxSizing: "border-box", flex: "none" }}><DemoQr /></div>
);

const DetailRows = ({ rows }) => (
  <div style={{ maxWidth: 560, 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 ApprovalSetup = ({ onDone, initialView = null }) => {
  const [view, setView] = useState(initialView || START_VIEW || "choose");
  const [choice, setChoice] = useState(null);   // "scan" | "phone" | "identity"
  const [via, setVia] = useState("phone");          // "phone" | "identity" | "passkey"
  const [scan, setScan] = useTimedState("waiting", "approved", 5000);
  const [check, setCheck] = useTimedState("checking", "done", 2200);
  const [pass, setPass] = useTimedState("working", "done", 1500);

  useEffect(() => { if (view === "scan" && scan === "idle") setScan("waiting"); }, [view]);
  useEffect(() => {
    if (view !== "scan" || scan !== "approved") return;
    const t = setTimeout(() => { setVia("phone"); setView("passkey"); }, 900);   // approval moves straight on, no Continue
    return () => clearTimeout(t);
  }, [view, scan]);
  const next = { scan: "scan", phone: "phoneDone", identity: "identity" };

  if (view === "scan") return (
    <Screen>
      <Body>
        <H>Scan this code with <Accent>your iPhone.</Accent></H>
        <Sub style={{ maxWidth: 560 }}>This links this computer to your account. Scan it with your iPhone’s camera.</Sub>
        <div style={{ marginTop: 24, display: "flex", flexWrap: "wrap", gap: 28, alignItems: "center" }}>
          <QrFrame label="QR code for linking this computer" />
          <ol style={{ margin: 0, paddingLeft: 20, display: "grid", gap: 10, fontFamily: "var(--f-display)", fontSize: 15, lineHeight: 1.45, color: "var(--ink-2)", maxWidth: 300 }}>
            <li>Point your iPhone’s camera at this code.</li>
            <li>Tap Open in Yoshi.</li>
            <li>Check the details and confirm with Face ID.</li>
          </ol>
        </div>
        <StatusLine done={scan === "approved"} waiting="Waiting for your iPhone…" doneText="Approved on your iPhone" />
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <SkipLink onClick={() => setView("identity")}>Can’t use your phone? Verify your identity</SkipLink>
      </Dock>
    </Screen>
  );

  if (view === "identity") return (
    <Screen>
      <Body>
        <H>Verify your <Accent>identity.</Accent></H>
        <Sub style={{ maxWidth: 560 }}>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={check !== "idle"} onClick={() => setCheck("checking")}>
            <span className="ld-funding-icon" style={{ color: "var(--ink-2)" }}><PersonGlyph /></span>
            <span className="ld-funding-copy"><strong>{check === "idle" ? "Start verification" : check === "checking" ? "Checking your selfie…" : "Identity verified"}</strong><small>Usually takes under a minute</small></span>
            {check === "done" ? <CheckGlyph size={18} /> : <img className="ld-funding-chevron" src="assets/lucid-chevron.svg" alt="" />}
          </button>
        </div>
        <ApprovalNote>This links this computer only. Your iPhone keeps working.</ApprovalNote>
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <Btn full disabled={check !== "done"} onClick={() => { setVia("identity"); setView("passkey"); }}>Continue</Btn>
      </Dock>
    </Screen>
  );

  if (view === "passkey") return (
    <Screen>
      <Body>
        <H>Create a passkey for <Accent>this computer.</Accent></H>
        <Sub style={{ maxWidth: 560 }}>You’ll use it to approve trades and money movements here, without your phone.</Sub>
        <div style={{ display: "grid", gap: 11, marginTop: 22 }}>
          <ComputerPasskeyTile state={pass} onCreate={() => setPass("working")} />
        </div>
        <ApprovalNote>Your passkey is saved by your browser or password manager and only works on yoshi.ai.</ApprovalNote>
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <Btn full disabled={pass !== "done"} onClick={() => setView("done")}>Continue</Btn>
      </Dock>
    </Screen>
  );

  if (view === "done" || view === "phoneDone") {
    const byPhone = view === "phoneDone";
    return (
      <Screen>
        <Body>
          <H>{byPhone ? <>You’re all <Accent>set.</Accent></> : <>This computer is <Accent>linked.</Accent></>}</H>
          <Sub style={{ maxWidth: 560 }}>{byPhone
            ? "When you trade or move money here, we’ll show a code on this screen. Scan it with your iPhone’s camera and confirm in Yoshi with Face ID."
            : "You’ll approve on this computer with your passkey. Your iPhone still approves with Face ID."}</Sub>
          {!byPhone && via === "phone" && <ApprovalCallout>We sent a text and a notification to your iPhone about this computer.</ApprovalCallout>}
          {!byPhone && <ApprovalCallout>To remove this computer, go to Settings › Security.</ApprovalCallout>}
        </Body>
        <Dock style={{ paddingBottom: 31 }}>
          <Btn full onClick={onDone}>Go to Yoshi</Btn>
        </Dock>
      </Screen>
    );
  }

  return (
    <Screen>
      <Body>
        <H>Link this <Accent>computer.</Accent></H>
        <Sub style={{ maxWidth: 560 }}>We couldn’t find your passkey on this computer. Link it another way before you use Yoshi here.</Sub>
        <div role="radiogroup" aria-label="How to link this computer" style={{ display: "grid", gap: 11, marginTop: 22 }}>
          <OptionTile glyph={<QrGlyph />} title="Scan with your iPhone" detail="Scan a code with your iPhone’s camera, then approve here with a passkey" selected={choice === "scan"} onClick={() => setChoice("scan")} />
          <OptionTile glyph={<PhoneGlyph />} title="Use my phone for approvals" detail="Scan a code with your iPhone each time you transact" selected={choice === "phone"} onClick={() => setChoice("phone")} />
          <OptionTile glyph={<PersonGlyph />} title="Verify your identity" detail="We will reverify your identity" selected={choice === "identity"} onClick={() => setChoice("identity")} />
        </div>
        <ApprovalNote>Never approve because someone asked you to, even if they say they’re from Yoshi.</ApprovalNote>
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <Btn full disabled={!choice} onClick={() => setView(next[choice])}>Continue</Btn>
      </Dock>
    </Screen>
  );
};

/* ---------------------------------------------------------------------------
   LINK A NEW IPHONE — a Brief on the web app (signed up on web, now in the app).
   The Brief shows the QR code, the new iPhone scans it, then web shows the
   phone's details and the passkey approves.
   brief (QR) → review → (linked | declined)
   --------------------------------------------------------------------------- */
const ApprovePhone = ({ onDone }) => {
  const [view, setView] = useState(START_VIEW || "brief");
  const [scan, setScan] = useTimedState("waiting", "scanned", 5000);
  const [confirming, setConfirming] = useTimedState("working", "done", 1200);
  useEffect(() => { if (view === "brief" && scan === "idle") setScan("waiting"); }, [view]);
  useEffect(() => { if (confirming === "done") setView("approved"); }, [confirming]);

  if (view === "approved" || view === "declined") {
    const ok = view === "approved";
    return (
      <Screen>
        <Body>
          <H>{ok ? <>iPhone <Accent>linked.</Accent></> : <>Not <Accent>linked.</Accent></>}</H>
          <Sub style={{ maxWidth: 560 }}>{ok
            ? "Finish on your iPhone by turning on Face ID approvals."
            : "Nothing changed on your account. If you didn’t just sign in on a phone, change your email password and contact Support."}</Sub>
          {ok && <ApprovalCallout>To remove that iPhone, go to Settings › Security.</ApprovalCallout>}
        </Body>
        <Dock style={{ paddingBottom: 31 }}>
          <Btn full onClick={onDone}>Done</Btn>
        </Dock>
      </Screen>
    );
  }

  if (view === "review") return (
    <Screen>
      <Body>
        <H>Link this <Accent>iPhone?</Accent></H>
        <Sub style={{ maxWidth: 560 }}>This iPhone just scanned your code. Check that it’s yours, then approve with your passkey.</Sub>
        <div style={{ marginTop: 22 }}>
          <DetailRows rows={[["Device", "iPhone 16 Pro"], ["Location", "San Francisco, CA"], ["Signed in", "Just now"]]} />
        </div>
        <ApprovalCallout tone="warn"><strong>Never approve because someone asked you to,</strong> even if they say they’re from Yoshi.</ApprovalCallout>
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <Btn full disabled={confirming === "working"} onClick={() => setConfirming("working")}>{confirming === "working" ? "Waiting for your passkey…" : "Approve with passkey"}</Btn>
        <Btn kind="ghost" full disabled={confirming === "working"} onClick={() => setView("declined")}>Don’t approve</Btn>
      </Dock>
    </Screen>
  );

  return (
    <Screen>
      <Body>
        <div style={{ display: "inline-block", marginBottom: 12, padding: "4px 10px", borderRadius: 999, border: "1px solid var(--rule-2)", fontFamily: "var(--f-display)", fontSize: 11, letterSpacing: "0.04em", color: "var(--ink-3)" }}>Brief</div>
        <H>Link your new <Accent>iPhone.</Accent></H>
        <Sub style={{ maxWidth: 560 }}>You just signed in to the Yoshi mobile app on a new iPhone. Scan this code with that iPhone to link it.</Sub>
        <div style={{ marginTop: 24, display: "flex", flexWrap: "wrap", gap: 28, alignItems: "center" }}>
          <QrFrame label="QR code for linking your new iPhone" />
          <ol style={{ margin: 0, paddingLeft: 20, display: "grid", gap: 10, fontFamily: "var(--f-display)", fontSize: 15, lineHeight: 1.45, color: "var(--ink-2)", maxWidth: 300 }}>
            <li>On your new iPhone, tap Scan code.</li>
            <li>Point it at this code.</li>
            <li>Come back here and approve with your passkey.</li>
          </ol>
        </div>
        <ApprovalCallout tone="warn"><strong>Only continue if you’re setting up a new phone right now.</strong> Yoshi will never ask you to scan this code or send a picture of it.</ApprovalCallout>
        <StatusLine done={scan === "scanned"} waiting="Waiting for your new iPhone… This code expires in 10 minutes." doneText="Scanned by iPhone 16 Pro" />
      </Body>
      <Dock style={{ paddingBottom: 31 }}>
        <Btn full disabled={scan !== "scanned"} onClick={() => setView("review")}>Continue</Btn>
        <Btn kind="ghost" full onClick={() => setView("declined")}>This wasn’t me</Btn>
      </Dock>
    </Screen>
  );
};

/* ---------------------------------------------------------------------------
   APPROVE WITH PHONE — a computer set to "Use my phone for approvals".
   Each trade or money movement shows a QR code. The phone scans it, shows the
   exact transaction, and approves with Face ID. Sketch in the onboarding style.
   --------------------------------------------------------------------------- */
/* "Use my phone for approvals": the web app's own transfer approval, where Approve pops up a QR code
   for the phone (web/runtime/src/approval.js, `approve=phone`). */
const ApproveWithPhone = () => {
  useEffect(() => { window.location.href = prototypeUrl("web", "runtime/approval.html?id=example-transfer&approvals=faceid-phone"); }, []);
  return null;
};

Object.assign(window, { FACE_ID_APPROVALS, setApprovalsMode, prototypeUrl, ApprovalSetup, ApprovePhone, ApproveWithPhone });
