/* landing_welcome.jsx — the web pre-login screen as production shows it (Nov 24 2026).
   The Lucid landing page (prototypes/lucid-dreaming-splash-page, the source production
   ported in apps/web-app/src/features/landing) fills the screen. Its Log in and Join the
   waitlist buttons open the production dialog (landing-auth-modal.tsx) instead of the
   landing prototype's own. Under `approvals=faceid`, Log in on a computer we don't know
   keeps the dialog up: Test your passkey, then three ways to link if that fails. Scan shows
   its QR code in the dialog, Verify your identity opens Plaid, and both end by creating
   this computer's passkey; Use my phone for approvals goes straight to Home.
   It is the web welcome step for everyone; only the passkey test and linking need the flag.
   `&login=signin|test|options` opens the dialog at that stage for review; `&auth=signup` opens Join the waitlist.
   `&passkey=` sets what the account has: (default) a passkey on this computer;
   `elsewhere` a passkey on another computer only; `none` no passkey at all (most
   phone-first people), which skips the test. `&browser=chrome` uses Chrome's
   device-only passkey request, which returns silently when this computer has none. */

// The splash page is its own Pages project: next door when every prototype is served from one root, else its public URL.
const LANDING_SRC = /\/web-onboarding\//.test(location.pathname) ? location.pathname.replace(/\/web-onboarding\/.*$/, "/lucid-dreaming-splash-page/landing.html") : "https://yoshi-lucid-splash-page.pages.dev/landing.html";
const REVIEW = new URLSearchParams(window.location.search);
const ACCOUNT_PASSKEY = REVIEW.get("passkey") || "here";   // here | elsewhere | none
const CHROME_DEVICE_ONLY = REVIEW.get("browser") === "chrome";

// The provider this computer last logged in with. Review with `&lastUsed=google|apple`; `none` clears it.
const LAST_SIGN_IN_KEY = "yoshi_onboarding_last_sign_in";
const LAST_SIGN_IN_PROVIDERS = ["google", "apple"];
const readLastSignIn = () => {
  const param = REVIEW.get("lastUsed");
  try {
    if (param === "none") localStorage.removeItem(LAST_SIGN_IN_KEY);
    else if (LAST_SIGN_IN_PROVIDERS.includes(param)) localStorage.setItem(LAST_SIGN_IN_KEY, param);
    const saved = localStorage.getItem(LAST_SIGN_IN_KEY);
    return LAST_SIGN_IN_PROVIDERS.includes(saved) ? saved : null;
  } catch {
    return LAST_SIGN_IN_PROVIDERS.includes(param) ? param : null;
  }
};
const rememberSignIn = (provider) => { try { localStorage.setItem(LAST_SIGN_IN_KEY, provider); } catch {} };
const providerName = (provider) => provider === "apple" ? "Apple" : "Google";
const orderBySignIn = (lastSignIn) => lastSignIn ? [lastSignIn, ...LAST_SIGN_IN_PROVIDERS.filter((p) => p !== lastSignIn)] : LAST_SIGN_IN_PROVIDERS;

// Lucid context chip (lucid-dreaming-vFinal/src/context-chip.css) at its native 14px size, pinned inside the button's right end.
const LastUsedChip = () => (
  <span data-last-used-chip style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)", display: "inline-flex", isolation: "isolate", fontSize: 14, fontWeight: 500, lineHeight: "20px", letterSpacing: 0 }}>
    <span aria-hidden="true" style={{ position: "absolute", inset: "5px 1px -7px", borderRadius: 40, background: "linear-gradient(90deg, var(--ld-sky-300), var(--ld-cyan-300) 50%, var(--ld-lime-300))", filter: "blur(6px)", opacity: 0.8, zIndex: -2 }} />
    <span aria-hidden="true" style={{ position: "absolute", inset: -1, borderRadius: 41, background: "linear-gradient(var(--ld-sky-100), var(--ld-cyan-300) 55%, var(--ld-lime-500))", filter: "blur(1.5px)", opacity: 0.9, zIndex: -1 }} />
    <span style={{ padding: "6px 12px", borderRadius: 40, background: "#ffffff", color: "rgb(0 0 0 / 64%)", boxShadow: "0 1px 1px rgb(0 0 0 / 4%)" }}>Last used</span>
  </span>
);

/* Disc geometry from production's footer-symbol.ts, drawn at rest. */
const symbolPose = (index) => {
  const tilt = (31 * Math.PI) / 180;
  const phase = index * (Math.PI / 4);
  const s2 = Math.sin(phase) ** 2;
  const x = 169 * Math.cos(phase), y = 131 * Math.sin(phase);
  const cx = 180 + x * Math.cos(tilt) - y * Math.sin(tilt);
  const cy = 180 + x * Math.sin(tilt) + y * Math.cos(tilt);
  const rotation = (Math.atan2(cy - 180, cx - 180) * 180) / Math.PI + 90 - 18 * Math.sin(2 * phase);
  return { cx, cy, rx: 61 - 7.7 * s2, ry: 6 + 44 * s2, transform: `rotate(${rotation} ${cx} ${cy})` };
};
const LandingAuthSymbol = () => (
  <svg className="landing-auth-symbol" viewBox="0 0 360 360" overflow="visible" aria-hidden="true" fill="white">
    {[0, 1, 2, 3, 4, 5, 6, 7].map((i) => <ellipse key={i} {...symbolPose(i)} />)}
  </svg>
);

const GoogleMark = () => (
  <svg viewBox="0 0 48 48" width="20" height="20" aria-hidden="true"><path fill="#FFC107" d="M43.611 20.083H42V20H24v8h11.303c-1.649 4.657-6.08 8-11.303 8-6.627 0-12-5.373-12-12s5.373-12 12-12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.046 6.053 29.268 4 24 4 12.955 4 4 12.955 4 24s8.955 20 20 20 20-8.955 20-20c0-1.341-.138-2.65-.389-3.917z"/><path fill="#FF3D00" d="M6.306 14.691l6.571 4.819C14.655 15.108 18.961 12 24 12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.046 6.053 29.268 4 24 4 16.318 4 9.656 8.337 6.306 14.691z"/><path fill="#4CAF50" d="M24 44c5.166 0 9.86-1.977 13.409-5.192l-6.19-5.238C29.211 35.091 26.715 36 24 36c-5.202 0-9.619-3.317-11.283-7.946l-6.522 5.025C9.505 39.556 16.227 44 24 44z"/><path fill="#1976D2" d="M43.611 20.083H42V20H24v8h11.303c-.792 2.237-2.231 4.166-4.087 5.571l.003-.002 6.19 5.238C36.971 39.205 44 34 44 24c0-1.341-.138-2.65-.389-3.917z"/></svg>
);
const AppleMark = () => (
  <svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path fill="currentColor" d="M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"/></svg>
);
const KeyMark = () => (
  <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <circle cx="8" cy="12" r="4" /><path d="M12 12h9" /><path d="M18 12v3" /><path d="M15 12v2" />
  </svg>
);

const LINK_OPTIONS = [
  { view: "scan", glyph: <QrGlyph size={22} />, title: "Scan with your iPhone", detail: "Scan a code with your iPhone’s camera, then approve here with a passkey" },
  { view: "phone", glyph: <PhoneGlyph size={22} />, title: "Use my phone for approvals", detail: "Scan a code with your iPhone each time you transact" },
  { view: "identity", glyph: <PersonGlyph size={22} />, title: "Verify your identity", detail: "We will reverify your identity" },
];

const DarkStatus = ({ done, waiting, doneText }) => (
  <p className="landing-auth-status" role="status">
    {done ? <span className="landing-auth-status-check" aria-hidden="true"><CheckGlyph size={12} /></span> : <span className="ld-approval-pulse landing-auth-status-dot" aria-hidden="true" />}
    {done ? doneText : waiting}
  </p>
);

const LandingAuthModal = ({ mode, onMode, stage, onStage, onClose, onJoin, onLogIn, onPasskey, onTest, onNoPasskey, onLink, onHome }) => {
  const [showEmail, setShowEmail] = useState(false);
  const [lastSignIn] = useState(readLastSignIn);
  const [scan, setScan] = useState("waiting");     // waiting → approved (simulated iPhone approval)
  const [creating, setCreating] = useState(false);
  useEffect(() => {
    if (stage !== "scan") return;
    setScan("waiting");
    const t = setTimeout(() => setScan("approved"), 5000);
    const next = setTimeout(() => onStage("create"), 5900);   // approval moves straight on, no Continue
    return () => { clearTimeout(t); clearTimeout(next); };
  }, [stage]);
  useEffect(() => {
    if (!creating) return;
    const t = setTimeout(onHome, 1400);   // simulated browser passkey creation
    return () => clearTimeout(t);
  }, [creating]);
  const join = mode === "join";
  let title = join ? "Join the waitlist" : "Welcome back";
  let description = join ? "Sign up to get early access to Yoshi." : "Log in to your Yoshi account.";
  if (!join && stage === "test") { title = "Test your passkey"; description = "We don’t recognize this computer yet. If your Yoshi passkey works here, you’re in."; }
  if (!join && stage === "options") { title = "Link this computer"; description = "Link this device to approve transactions here."; }
  if (!join && stage === "scan") { title = "Scan with your iPhone"; description = "Point your iPhone’s camera at this code, then confirm in the Yoshi app with Face ID."; }
  if (!join && stage === "create") { title = "Create a passkey"; description = "You’ll use it to approve transactions on this computer."; }
  const compact = !join && stage !== "signin";
  const submitEmail = (event) => { event.preventDefault(); onLogIn(); };

  return (
    <>
      <div className="landing-auth-backdrop" onClick={onClose} />
      <div className="landing-auth-modal" role="dialog" aria-modal="true" aria-labelledby="landing-auth-title">
        <button className="landing-auth-close" type="button" aria-label="Close" onClick={onClose}>
          <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 3l10 10M13 3L3 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" /></svg>
        </button>
        <div className={compact ? "landing-auth-state is-compact" : "landing-auth-state"}>
          <div className="landing-auth-head">
            <LandingAuthSymbol />
            <h2 className="landing-auth-title" id="landing-auth-title">{title}</h2>
            <p className="landing-auth-description">{description}</p>
          </div>

          {!join && stage === "test" ? (
            <div className="landing-auth-buttons">
              <button className="landing-auth-sso google" type="button" onClick={onTest}><KeyMark />Test your passkey</button>
              <button className="landing-auth-sso secondary" type="button" onClick={onNoPasskey}>I don’t have a passkey</button>
            </div>
          ) : !join && stage === "scan" ? (
            <div className="landing-auth-buttons">
              <div className="landing-auth-qr" aria-label="QR code for linking this computer"><DemoQr /></div>
              <DarkStatus done={scan === "approved"} waiting="Waiting for your iPhone…" doneText="Approved on your iPhone" />
              <button className="landing-auth-email-toggle" type="button" onClick={() => onStage("options")}>Choose another way</button>
            </div>
          ) : !join && stage === "create" ? (
            <div className="landing-auth-buttons">
              <button className="landing-auth-sso google" type="button" disabled={creating} onClick={() => setCreating(true)}><KeyMark />{creating ? "Creating your passkey…" : "Create passkey"}</button>
            </div>
          ) : !join && stage === "options" ? (
            <div className="landing-auth-buttons">
              {LINK_OPTIONS.map((o) => (
                <button key={o.view} className="landing-auth-option" type="button" onClick={() => onLink(o.view)}>
                  <span className="landing-auth-option-icon">{o.glyph}</span>
                  <span className="landing-auth-option-copy"><strong>{o.title}</strong><small>{o.detail}</small></span>
                </button>
              ))}
            </div>
          ) : (
            <div className="landing-auth-buttons">
              {orderBySignIn(lastSignIn).map((provider) => (
                <button key={provider} className={`landing-auth-sso ${provider}${provider === lastSignIn ? " is-last-used" : ""}`} type="button" onClick={() => { rememberSignIn(provider); (join ? onJoin : onLogIn)(); }}>
                  {provider === "apple" ? <AppleMark /> : <GoogleMark />}Continue with {providerName(provider)}
                  {provider === lastSignIn && <LastUsedChip />}
                </button>
              ))}
              {!join && onPasskey && <button className="landing-auth-sso passkey" type="button" onClick={onPasskey}><KeyMark />Continue with a passkey</button>}
              {!join && (showEmail ? (
                <form className="landing-auth-email-form" aria-label="Email sign in" onSubmit={submitEmail}>
                  <label htmlFor="landing-auth-email">Email</label>
                  <input id="landing-auth-email" name="email" type="email" autoComplete="username webauthn" required autoFocus />
                  <label htmlFor="landing-auth-password">Password</label>
                  <input id="landing-auth-password" name="password" type="password" autoComplete="current-password" required />
                  <button className="landing-auth-sso google" type="submit">Sign in</button>
                </form>
              ) : (
                <button className="landing-auth-email-toggle" type="button" onClick={() => setShowEmail(true)}>Sign in with email</button>
              ))}
            </div>
          )}

          {!join && stage === "signin" && (
            <p className="landing-auth-swap">New to Yoshi? <button type="button" onClick={() => { setShowEmail(false); onMode("join"); }}>Join the waitlist</button></p>
          )}
          <p className="landing-auth-legal">
            By continuing, you agree to our <a href="https://yoshi.ai/termsofservice" target="_blank" rel="noopener noreferrer">Terms</a> and <a href="https://yoshi.ai/privacypolicy" target="_blank" rel="noopener noreferrer">Privacy Policy</a>.
          </p>
        </div>
      </div>
    </>
  );
};

const LandingWelcome = ({ onJoin, onLogIn, onHome, passkeyFirst }) => {
  const startStage = new URLSearchParams(window.location.search).get("login");
  const joinFirst = new URLSearchParams(window.location.search).get("auth") === "signup";
  const [modal, setModal] = useState(startStage ? "login" : joinFirst ? "join" : null);   // null | "login" | "join"
  const [stage, setStage] = useState(startStage || "signin");        // signin | test | options
  const [sheet, setSheet] = useState(null);   // null | "signin" | "test": where the browser's passkey prompt was opened
  const [plaid, setPlaid] = useState(false);
  const [standalone, setStandalone] = useState(false);   // hosted apart from the landing page: the dialog is the whole screen
  const [idv, setIdv] = useState(() => freshIdv());   // the board's sample identity, so Plaid's review step has details
  // We store every passkey an account registers, so an account with none skips the test.
  const afterSignIn = () => setStage(ACCOUNT_PASSKEY === "none" ? "options" : "test");
  const askBrowser = (from) => {
    // The test uses Chrome's device-only request; the sign-in button keeps the full prompt, which can offer another device.
    if (from === "test" && ACCOUNT_PASSKEY !== "here" && CHROME_DEVICE_ONLY) { setStage("options"); return; }
    setSheet(from);
  };

  // The landing's own buttons open this dialog; its prototype dialog and app promotions stay hidden, as in production.
  const wire = (event) => {
    let doc = null;
    try { doc = event.currentTarget.contentDocument; } catch {}
    // Hosted on another site the landing can't be wired, so its Log in dialog opens straight away.
    if (!doc) { setStandalone(true); setStage((current) => current || "signin"); setModal((current) => current || "login"); return; }
    const style = doc.createElement("style");
    style.textContent = "#qrfloat, #signup, .fbottom .appstore { display: none !important; }";
    doc.head.appendChild(style);
    doc.addEventListener("click", (e) => {
      const target = e.target.closest && e.target.closest(".btn-login, [data-modal]");
      if (!target) return;
      e.preventDefault();
      e.stopPropagation();
      setStage("signin");
      setModal(target.classList.contains("btn-login") ? "login" : "join");
    }, true);
  };

  return (
    <Screen style={{ position: "relative", overflow: "hidden" }}>
      <iframe className="landing-frame" src={LANDING_SRC} title="Yoshi landing page" allow="autoplay" onLoad={wire} />
      {modal && !plaid && <LandingAuthModal mode={modal} onMode={setModal} stage={stage}
        onClose={() => { if (!standalone) setModal(null); setStage("signin"); }}
        onJoin={onJoin}
        onStage={setStage}
        onLogIn={passkeyFirst ? afterSignIn : onLogIn}
        onPasskey={() => askBrowser("signin")}
        onTest={() => askBrowser("test")}
        onNoPasskey={() => setStage("options")}
        onHome={onHome}
        onLink={(view) => {
          if (view === "phone") onHome();
          else if (view === "identity") setPlaid(true);
          else setStage(view);
        }} />}
      {plaid && <div className="landing-auth-backdrop" />}
      {plaid && (
        <div className="landing-plaid-frame">
          <PlaidIDV data={idv} setData={setIdv} fail={false}
            onDone={() => { setPlaid(false); setStage("create"); }}
            onFail={() => setPlaid(false)}
            onExit={() => setPlaid(false)} />
        </div>
      )}
      {sheet && <BrowserPasskeySheet none={ACCOUNT_PASSKEY !== "here"}
        onUse={() => { setSheet(null); onHome(); }}
        onCancel={() => { const from = sheet; setSheet(null); if (from === "test") setStage("options"); }} />}
    </Screen>
  );
};

Object.assign(window, { LandingWelcome });
