/* flow2.jsx — Income · Checks (screening) · Security (Face ID + Passkey). */

const SubHead = ({ children, style }) => (
  <div style={{ marginTop: 22, marginBottom: 11, ...style }}><Eyebrow color="var(--ink-2)">{children}</Eyebrow></div>
);

const Pill = ({ on, children, onClick }) => (
  <button className="press" onClick={onClick} style={{
    padding: "10px 14px", cursor: "pointer", borderRadius: 999,
    background: on ? "var(--bg-card)" : "var(--bg-2)",
    border: `1px solid ${on ? "var(--ink)" : "var(--rule-2)"}`,
    fontFamily: "var(--f-display)", fontSize: 13.5, fontWeight: 600, letterSpacing: "-0.01em", whiteSpace: "nowrap",
    color: on ? "var(--ink)" : "var(--ink-2)" }}>{children}</button>
);

/* Faux document upload — dashed dropzone → uploaded chip with remove. */
const UploadBox = ({ value, label, hint, onPick, onClear }) => (
  value ? (
    <div className="yo-enter" style={{ display: "flex", alignItems: "center", gap: 13, padding: "13px 14px", background: "var(--bg-card)", border: "1px solid var(--accent)", borderRadius: 12 }}>
      <span style={{ width: 38, height: 38, flex: "none", borderRadius: 10, border: "1px solid var(--accent)", display: "grid", placeItems: "center", color: "var(--accent)" }}><Icon name="doc" size={20} color="var(--accent)" /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: "var(--f-display)", fontSize: 14, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{value}</div>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 5, marginTop: 2 }}>
          <Icon name="check" size={12} stroke={2.4} color="var(--accent)" />
          <span style={{ fontFamily: "var(--f-display)", fontSize: 11, fontWeight: 700, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--accent)" }}>Uploaded</span>
        </div>
      </div>
      <button className="press" onClick={onClear} aria-label="Remove" style={{ background: "none", border: "none", cursor: "pointer", color: "var(--ink-3)", display: "flex", padding: 4 }}><Icon name="close" size={18} color="var(--ink-3)" /></button>
    </div>
  ) : (
    <button className="press" onClick={onPick} style={{ width: "100%", display: "flex", alignItems: "center", gap: 13, padding: "16px 15px", background: "var(--bg-2)", border: "1px dashed var(--rule-2)", borderRadius: 12, cursor: "pointer", textAlign: "left" }}>
      <span style={{ width: 38, height: 38, flex: "none", display: "grid", placeItems: "center", color: "var(--accent)" }}><Icon name="download" size={22} color="var(--accent)" /></span>
      <span style={{ flex: 1 }}>
        <span style={{ display: "block", fontFamily: "var(--f-display)", fontSize: 14.5, fontWeight: 600 }}>{label}</span>
        <span style={{ display: "block", fontFamily: "var(--f-display)", fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{hint}</span>
      </span>
    </button>
  )
);

/* =============================================================
   iMessage banner — a fake iOS notification that drops down from
   the top of the screen mid-flow: Yoshi texts the freshly-verified
   number. Rendered as authentic OS chrome (system font, light
   frosted material, green Messages glyph) — not a Yoshi surface.
   Slides in, lingers, then auto-dismisses (tap to dismiss).
   ============================================================= */
const MessagesGlyph = () => (
  <span style={{ width: 21, height: 21, flex: "none", borderRadius: 5, display: "grid", placeItems: "center",
    background: "linear-gradient(180deg, #5BF675 0%, #1FD24A 100%)" }}>
    <svg width="13" height="13" viewBox="0 0 24 24" style={{ display: "block" }}>
      <path fill="#fff" d="M12 3C6.9 3 3 6.6 3 11c0 2.5 1.3 4.7 3.3 6.1 0 .9-.5 2.2-1.3 3.2-.2.2 0 .6.3.5 1.9-.4 3.3-1.1 4.1-1.6.7.2 1.6.3 2.3.3 5.1 0 9-3.6 9-8S17.1 3 12 3z" />
    </svg>
  </span>
);

const IOS_UI = '-apple-system, "SF Pro Text", "SF Pro", system-ui, "Segoe UI", sans-serif';

const IMessageBanner = ({ phone }) => {
  const [shown, setShown] = useState(false);
  const [gone, setGone] = useState(false);
  useEffect(() => {
    const tIn = setTimeout(() => setShown(true), 700);
    const tOut = setTimeout(() => setShown(false), 7000);
    const tGone = setTimeout(() => setGone(true), 7700);
    return () => { clearTimeout(tIn); clearTimeout(tOut); clearTimeout(tGone); };
  }, []);
  if (gone) return null;
  return (
    <div
      onClick={() => setShown(false)}
      style={{
        position: "absolute", top: 12, left: 9, right: 9, zIndex: 40, cursor: "pointer",
        transform: shown ? "translateY(0)" : "translateY(-160%)",
        opacity: shown ? 1 : 0,
        transition: "transform 540ms cubic-bezier(0.22,1.08,0.36,1), opacity 300ms ease",
        background: "rgba(247,247,247,0.82)",
        WebkitBackdropFilter: "blur(24px) saturate(1.4)", backdropFilter: "blur(24px) saturate(1.4)",
        borderRadius: 24,
        boxShadow: "0 16px 38px -10px rgba(0,0,0,0.40), 0 1px 3px rgba(0,0,0,0.10)",
        padding: "13px 15px 14px",
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 5 }}>
        <MessagesGlyph />
        <span style={{ fontFamily: IOS_UI, fontSize: 12, fontWeight: 600, letterSpacing: "0.03em", textTransform: "uppercase", color: "#8a8a8e" }}>Messages</span>
        <span style={{ marginLeft: "auto", fontFamily: IOS_UI, fontSize: 12.5, color: "#8a8a8e" }}>now</span>
      </div>
      <div style={{ fontFamily: IOS_UI, fontSize: 15, fontWeight: 600, color: "#000", letterSpacing: "-0.01em", marginBottom: 1 }}>Yoshi</div>
      <div style={{ fontFamily: IOS_UI, fontSize: 14.5, color: "#1c1c1e", lineHeight: 1.32, textWrap: "pretty" }}>
        Hey, it's Yoshi! Text me anytime to chat about your finances wherever you are.
      </div>
    </div>
  );
};

/* =============================================================
   05 · INCOME — "How do you earn?"  (net worth removed;
   annual income is a ranged dropdown using the former NW bands)
   ============================================================= */
const STATUSES = ["Employed", "Self-employed", "Retired", "Student", "Not employed"];
const SOURCES = ["Salary", "Self-employed", "Investments", "Retirement", "Gifts", "Other"];
const INCOME_BANDS = ["Under $50,000", "$50,000 – $250,000", "$250,000 – $1,000,000", "Over $1,000,000"];
const INDUSTRIES = [
  "Technology or information services",
  "Healthcare",
  "Education",
  "Retail or consumer goods",
  "Hospitality or food services",
  "Construction or real estate",
  "Finance or insurance",
  "Manufacturing",
  "Transportation",
  "Government",
  "Other",
];

const Income = ({ data, setData, phone, onNext }) => {
  const set = (k) => (v) => setData((d) => ({ ...d, [k]: v }));
  const [showContact, setShowContact] = useState(false);
  const employed = data.status === "Employed";
  const selfEmp = data.status === "Self-employed";
  const ready = data.status && data.source && data.incomeBand;
  return (
    <Screen style={{ position: "relative" }}>
      <Body>
        <H>How do you<Brk /><Accent>earn?</Accent></H>
        <Sub>We need to ask this for regulatory purposes.</Sub>

        <SubHead>Employment status</SubHead>
        <Select value={data.status} onChange={set("status")} options={STATUSES} placeholder="Choose one" />

        {employed && (
          <div className="yo-enter" style={{ marginTop: 14, display: "grid", gap: 14, position: "relative", zIndex: 20 }}>
            <Field label="Employer" value={data.company} onChange={set("company")} placeholder="Where you work" />
            <Select label="Industry" value={data.industry} onChange={set("industry")} options={INDUSTRIES} placeholder="Select an industry" />
          </div>
        )}
        {selfEmp && (
          <div className="yo-enter" style={{ marginTop: 14 }}>
            <Field label="Business name" value={data.company} onChange={set("company")} placeholder="Your business or DBA" />
          </div>
        )}

        <SubHead>Main income source</SubHead>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          {SOURCES.map((s) => <Pill key={s} on={data.source === s} onClick={() => set("source")(s)}>{s}</Pill>)}
        </div>

        <SubHead>Annual income, before tax</SubHead>
        <Select value={data.incomeBand} onChange={set("incomeBand")} options={INCOME_BANDS} placeholder="Select a range" />

        {/* Optional · trusted contact — a compact checkbox that drops down the
            fields when ticked. Never gates Continue. */}
        <div style={{ marginTop: 16 }}>
          <button className="press" onClick={() => setShowContact((v) => !v)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "4px 2px", background: "none", border: "none", cursor: "pointer", textAlign: "left" }}>
            <span style={{ width: 20, height: 20, flex: "none", borderRadius: 6, border: `1.5px solid ${showContact ? "var(--accent)" : "var(--rule-2)"}`, background: showContact ? "var(--accent)" : "transparent", display: "grid", placeItems: "center", transition: "background 160ms ease, border-color 160ms ease" }}>
              {showContact && <Icon name="check" size={13} stroke={2.4} color="var(--accent-ink)" />}
            </span>
            <span style={{ fontFamily: "var(--f-display)", fontSize: 10, fontWeight: 600, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-2)" }}>Add a trusted contact <span style={{ color: "var(--ink-3)" }}>· optional</span></span>
          </button>
          {showContact && (
            <div className="yo-enter" style={{ display: "grid", gap: 12, marginTop: 12 }}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <Field label="First name" value={data.tcFirst || ""} onChange={set("tcFirst")} placeholder="First" />
                <Field label="Last name" value={data.tcLast || ""} onChange={set("tcLast")} placeholder="Last" />
              </div>
              <Field label="Email" value={data.tcEmail || ""} onChange={set("tcEmail")} placeholder="name@email.com" inputMode="email" />
            </div>
          )}
        </div>
      </Body>
      <Dock>
        <Btn full disabled={!ready} onClick={onNext}>Continue <Icon name="arrow" size={15} color={ready ? "var(--accent-ink)" : "var(--ink-3)"} /></Btn>
      </Dock>
    </Screen>
  );
};

/* =============================================================
   06 · CHECKS — PEP / affiliation screening (kept as-is)
   ============================================================= */
const SCREEN_OPTS = [
  { id: "insider", text: "I, or a family member, am a 10% shareholder or senior executive at a publicly traded company." },
  { id: "finra",   text: "I, or a family member, work for a securities exchange, FINRA, or a registered brokerage firm." },
  { id: "pep",     text: "I, or a family member, am a politically exposed person (PEP) or public official, such as a head of state, diplomat, judge, or government official." },
];

const Checks = ({ data, setData, onNext }) => {
  const flags = data.flags || {};
  const none = data.none;
  const toggle = (id) => setData((d) => ({ ...d, none: false, flags: { ...(d.flags || {}), [id]: !(d.flags || {})[id] } }));
  const pickNone = () => setData((d) => ({ ...d, none: true, flags: {} }));
  const any = Object.values(flags).some(Boolean);
  const needsDoc = flags.finra && !data.finraDoc;
  const needsInsider = flags.insider && !(data.company2 || "").trim();
  const needsPep = flags.pep && !((data.pepOrg || "").trim() || (data.pepName || "").trim());
  const ready = (none || any) && !needsDoc && !needsInsider && !needsPep;
  return (
    <Screen>
      <Body>
        <H>A couple of<Brk /><Accent>checks.</Accent></H>
        <Sub>Select anything that applies to you or a family member. If you're not sure, it probably doesn't.</Sub>

        <div style={{ marginTop: 18, display: "grid", gap: 9 }}>
          <Choice on={none} onClick={pickNone} title="None of these apply" />
          <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "2px 0" }}>
            <span style={{ flex: 1, height: 1, background: "var(--rule)" }} />
            <span style={{ fontFamily: "var(--f-display)", fontSize: 11, fontWeight: 700, letterSpacing: "0.14em", color: "var(--ink-3)" }}>OR</span>
            <span style={{ flex: 1, height: 1, background: "var(--rule)" }} />
          </div>
          {SCREEN_OPTS.map((o) => (
            <Choice key={o.id} multi light on={!!flags[o.id]} onClick={() => toggle(o.id)} title={o.text} />
          ))}
        </div>

        {flags.insider && (
          <div className="yo-enter" style={{ marginTop: 16 }}>
            <SubHead style={{ marginTop: 4 }}>Which public company?</SubHead>
            <Field value={data.company2 || ""} onChange={(v) => setData((d) => ({ ...d, company2: v }))} placeholder="Ticker" />
          </div>
        )}
        {flags.finra && (
          <div className="yo-enter" style={{ marginTop: 16 }}>
            <SubHead style={{ marginTop: 4 }}>Required document</SubHead>
            <div style={{ fontFamily: "var(--f-display)", fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.5, marginBottom: 11 }}>
              FINRA rules require a compliance authorization (a 407 letter) from your employer before we can open a brokerage account.
            </div>
            <UploadBox value={data.finraDoc} label="Upload your 407 letter" hint="PDF, JPG or PNG · up to 10 MB"
              onPick={() => setData((d) => ({ ...d, finraDoc: "407-letter.pdf" }))}
              onClear={() => setData((d) => ({ ...d, finraDoc: null }))} />
          </div>
        )}

        {flags.pep && (
          <div className="yo-enter" style={{ marginTop: 16 }}>
            <SubHead style={{ marginTop: 4 }}>Political organization</SubHead>
            <Field value={data.pepOrg || ""} onChange={(v) => setData((d) => ({ ...d, pepOrg: v }))} placeholder="Organization name" />
            <SubHead>Exposed person's full name</SubHead>
            <Field value={data.pepName || ""} onChange={(v) => setData((d) => ({ ...d, pepName: v }))} placeholder="Full legal name" />
          </div>
        )}

        <Disclosure>We're required to ask for regulatory purposes.</Disclosure>
      </Body>
      <Dock>
        <Btn full disabled={!ready} onClick={onNext}>Continue <Icon name="arrow" size={15} color={ready ? "var(--accent-ink)" : "var(--ink-3)"} /></Btn>
      </Dock>
    </Screen>
  );
};

/* =============================================================
   07 · SECURITY — Passkey + SMS consent.
   Passkey is the phishing-proof credential; text messages are
   optional — user can proceed after passkey if they prefer.
   ============================================================= */
const SecButton = ({ icon, label, doneLabel, state, onCreate, required }) => {
  const creating = state === "creating";
  const done = state === "done";
  return (
    <button className="press" disabled={creating || done} onClick={onCreate} style={{
      width: "100%", height: 56, display: "flex", alignItems: "center", gap: 10,
      padding: "15px 18px", borderRadius: 12, cursor: creating || done ? "default" : "pointer",
      background: done ? "color-mix(in srgb, var(--accent) 10%, var(--bg-2))" : "var(--bg-2)",
      border: `1px solid ${done ? "var(--accent)" : "var(--rule-2)"}`,
      color: done ? "var(--accent)" : "var(--ink)",
      fontFamily: "var(--f-display)", fontSize: 15, fontWeight: 600, letterSpacing: "-0.01em",
      transition: "background 240ms ease, border-color 240ms ease, color 240ms ease" }}>
      {creating ? (
        <><LiveDot size={6} /><span>Setting up…</span></>
      ) : done ? (
        <><Icon name="check" size={18} stroke={2.2} color="var(--accent)" /><span>{doneLabel}</span></>
      ) : (
        <>{icon}<span style={{ whiteSpace: "nowrap" }}>{label}</span>{required && (
          <span style={{ marginLeft: "auto", fontSize: 12, fontWeight: 500, letterSpacing: "-0.005em", color: "var(--ink-3)" }}>Required</span>
        )}</>
      )}
    </button>
  );
};

/* Toggle row for SMS opt-in */
const SmsOptInToggle = ({ on, onToggle }) => {
  return (
  <button type="button" className="press" role="switch" aria-checked={on} onClick={onToggle} style={{
    width: "100%", height: 56, display: "flex", alignItems: "center", gap: 13,
    padding: "15px 18px", borderRadius: 12, cursor: "pointer",
    background: on ? "color-mix(in srgb, var(--accent) 10%, var(--bg-2))" : "var(--bg-2)",
    border: `1px solid ${on ? "var(--accent)" : "var(--rule-2)"}`,
    transition: "background 240ms ease, border-color 240ms ease, color 240ms ease",
    textAlign: "left" }}>
    <span style={{
      width: 19, height: 19, flex: "none",
      display: "grid", placeItems: "center",
      color: on ? "var(--accent)" : "var(--ink-2)" }}>
      <Icon name="message" size={18} color={on ? "var(--accent)" : "var(--ink-2)"} />
    </span>
    <span style={{ flex: 1, minWidth: 0 }}>
      <span style={{
        display: "block",
        fontFamily: "var(--f-display)", fontSize: 15, fontWeight: 600, letterSpacing: "-0.01em",
        color: on ? "var(--accent)" : "var(--ink)" }}>
        Chat with Yoshi over text
      </span>
    </span>
    <span style={{
      width: 44, height: 26, flex: "none", borderRadius: 999,
      background: on ? "var(--accent)" : "var(--rule-2)",
      position: "relative", transition: "background 220ms ease", display: "block" }}>
      <span style={{
        position: "absolute", top: 3, left: on ? 21 : 3,
        width: 20, height: 20, borderRadius: 999, background: "var(--bg-card)",
        transition: "left 220ms cubic-bezier(0.16,1,0.30,1)",
        boxShadow: "0 1px 3px rgba(0,0,0,0.2)" }} />
    </span>
  </button>
  );
};

/* Toggle row for browser notifications */
const NotifToggle = ({ on, onToggle }) => {
  const web = usePlatform() === "web";
  const offLabel = web ? "Enable browser notifications" : "Turn on push notifications";
  const handle = () => {
    if (web && !on && typeof Notification !== "undefined" && Notification.requestPermission) {
      try { Notification.requestPermission(); } catch (e) {}
    }
    onToggle();
  };
  return (
  <button type="button" className="press" role="switch" aria-checked={on} onClick={handle} style={{
    width: "100%", height: 56, display: "flex", alignItems: "center", gap: 13,
    padding: "15px 18px", borderRadius: 12, cursor: "pointer",
    background: on ? "color-mix(in srgb, var(--accent) 10%, var(--bg-2))" : "var(--bg-2)",
    border: `1px solid ${on ? "var(--accent)" : "var(--rule-2)"}`,
    color: on ? "var(--accent)" : "var(--ink)",
    fontFamily: "var(--f-display)", fontSize: 15, fontWeight: 600, letterSpacing: "-0.01em",
    transition: "background 240ms ease, border-color 240ms ease, color 240ms ease",
    textAlign: "left" }}>
    <Icon name="bell" size={19} color={on ? "var(--accent)" : "var(--ink-2)"} />
    <span style={{ flex: 1 }}>{on ? "Browser notifications on" : offLabel}</span>
    <span style={{
      width: 44, height: 26, flex: "none", borderRadius: 999,
      background: on ? "var(--accent)" : "var(--rule-2)",
      position: "relative", transition: "background 220ms ease", display: "block" }}>
      <span style={{
        position: "absolute", top: 3, left: on ? 21 : 3,
        width: 20, height: 20, borderRadius: 999, background: "var(--bg-card)",
        transition: "left 220ms cubic-bezier(0.16,1,0.30,1)",
        boxShadow: "0 1px 3px rgba(0,0,0,0.2)" }} />
    </span>
  </button>
  );
};

const Security = ({ onNext }) => {
  const secWeb = usePlatform() === "web";
  const [pass, setPass] = useState("idle");   // idle → creating → done
  const [smsOptIn, setSmsOptIn] = useState(false);
  const [notifs, setNotifs] = useState(false);

  const makePass = () => {
    setPass("creating");
    setTimeout(() => setPass("done"), 1500);
  };

  return (
    <Screen>
      <Body>
        <H>Ways to<Brk />stay <Accent>secure.</Accent></H>
        <Sub style={{ maxWidth: secWeb ? "58ch" : undefined }}>Money moves safely on Yoshi. Creating a passkey replaces a password. It's stored on your device and can't be phished or reused.</Sub>

        <div style={{ display: "grid", gap: 11, marginTop: 22 }}>
          <SecButton icon={<Icon name="shield" size={18} color="var(--ink-2)" />}
            label="Create passkey" doneLabel="Passkey on" state={pass} onCreate={makePass} required />
          <NotifToggle on={notifs} onToggle={() => setNotifs(n => !n)} />
          <SmsOptInToggle on={smsOptIn} onToggle={() => setSmsOptIn(n => !n)} />
        </div>

        <div style={{
          marginTop: 16,
          fontFamily: "var(--f-display)",
          fontSize: 12,
          lineHeight: 1.5,
          color: "var(--ink-3)",
          width: "100%" }}>
          Your passkey is stored securely in your device keychain. Browser notifications are optional and you can enable them later in settings. By providing my mobile phone number and checking this box, I consent by e-signature to receive automated text messages from Yoshi related to my account, in addition to occasional marketing messages. I understand that I may also send text messages to Yoshi to interact with my account and receive automated responses. Message and data rates may apply. Reply STOP to opt out and HELP for help. Consent is not a condition of purchasing any goods or services.
        </div>
      </Body>
      <Dock>
        <Btn full disabled={pass !== "done"} onClick={onNext}>Continue <Icon name="arrow" size={15} color={pass === "done" ? "var(--accent-ink)" : "var(--ink-3)"} /></Btn>
      </Dock>
    </Screen>
  );
};

Object.assign(window, { SubHead, Pill, Income, Checks, Security, IMessageBanner });
