/* Reeve — cold start. Interactive, animated. Google / Gmail is the ONLY path.
   launch (logo + Google) → Gmail authorization explainer → connecting →
   first scan (reading the forwarded thread) → home. Anchored on 6a222302. */
const { useState: useStateOb, useEffect: useEffectOb, useRef: useRefOb } = React;

function CsStepper({ step }) {
  // step: 0 登录 · 1 连接 · 2 进入首页
  const labels = ["登录", "连接邮箱", "进入首页"];
  return (
    <div className="cs-stepper" aria-hidden="true">
      {labels.map((lb, i) =>
        <React.Fragment key={lb}>
          <span className={`csx-node ${i === step ? "on" : i < step ? "done" : ""}`}>
            <span className="csx-dot">{i < step ? "✓" : i + 1}</span>
            <span className="csx-lb">{lb}</span>
          </span>
          {i < labels.length - 1 ? <span className={`csx-bar ${i < step ? "done" : ""}`} /> : null}
        </React.Fragment>
      )}
    </div>);
}

/* two-concept loop: (A) Reeve auto-runs your open loops — a dot orbits each
   open ring on its own; (B) one long-press auto-closes them — the dots snap
   into each ring's gap (the kept-loop mark) one by one. */
const CA2 = [
  { k: "run", dur: 2100, cap: "Reeve 替你自动跑每条 open loop" },
  { k: "press", dur: 1150, cap: "你只长按一次" },
  { k: "close", dur: 2050, cap: "往后自动闭环 · 少你一份心" },
];
function ConceptAnim() {
  const [i, setI] = useStateOb(0);
  useEffectOb(() => {
    const id = setTimeout(() => setI((v) => (v + 1) % CA2.length), CA2[i].dur);
    return () => clearTimeout(id);
  }, [i]);
  const ph = CA2[i];
  return (
    <div className="concept-anim-wrap" aria-hidden="true">
      <div className={`ca3 ph-${ph.k}`}>
        {[0, 1, 2].map((n) => (
          <svg className="ca3-loop" viewBox="0 0 56 56" key={n} style={{ "--d": n * 0.16 + "s" }}>
            <circle className="ca3-track" cx="28" cy="28" r="20" />
            <path className="ca3-arc" d="M40.9 12.7 A20 20 0 1 1 15.1 12.7" />
            <g className="ca3-spin"><circle className="ca3-run" cx="28" cy="8" r="4" /></g>
            <path className="ca3-check" d="M21 28 l4.6 5 l9.4 -11" />
          </svg>
        ))}
      </div>
      <div className="ca3-hold"><span className="ca3-finger" /></div>
      <div className="concept-cap"><i className="cc-dot" />{ph.cap}</div>
    </div>);

}

/* ===== Gmail authorization → progressive "learning your profile" transition.
   Real corpus: Demarco = insurance agent; clients Sherrell / Marcus / Joe / Adam.
   Phases advance on real timers so it plays in any environment. ===== */
function GlReveal({ className, children }) {
  const [on, setOn] = useStateOb(false);
  useEffectOb(() => { const id = requestAnimationFrame(() => setOn(true)); return () => cancelAnimationFrame(id); }, []);
  return <div className={`${className} ${on ? "in" : ""}`}>{children}</div>;
}

const GL_PHASES = [
  { k: "scan", cap: "正在读取你最近的往来邮件…" },
  { k: "portrait", cap: "在认识你 —— 在做什么、和谁打交道" },
  { k: "threads", cap: "把要替你跟进的线，一条条理出来" },
  { k: "ready", cap: "画像与记忆已生成，确认后进入首页。" },
];
const GL_FACTS = [
  "健康险经纪人 · Demarco",
  "正在跟进 4 位客户",
  "偏好：先给结论、简短",
  "中 / 英 双语往来",
];
const GL_THREADS = [
  { a: "S", n: "Sherrell", k: "健康险报价" },
  { a: "M", n: "Marcus", k: "投保跟进" },
  { a: "J", n: "Joe Comerford", k: "商业险单据" },
  { a: "A", n: "Adam", k: "续约挽留" },
];

/* cold-start specialist recommend — a non-blocking card slipped into the scan
   results. Identifying insurance content → recommend the insurance specialist.
   Local state only (the real persistent control is the profile toggle), so a
   "暂不" here never silently flips the live app's setting. */
function GlSpecCard() {
  const sp = (window.EMBER && window.EMBER.specialist) || {};
  const [st, setSt] = useStateOb("idle"); // idle | in | skip
  return (
    <div className={`gl-spec-card ${st}`}>
      <div className="gl-spec-top">
        <span className="gl-spec-mk"><SpecMark size={20} stroke={2} /></span>
        <div className="gl-spec-hd">
          <div className="gl-spec-h">推荐引入 · <b>{sp.role || "保险专家"}</b></div>
          <div className="gl-spec-kicker">识别自你的往来邮件</div>
        </div>
        {st !== "idle" ? <span className={`gl-spec-state ${st}`} aria-hidden="true">{st === "in" ? "✓" : "—"}</span> : null}
      </div>
      <div className="gl-spec-sub">
        {st === "idle" ? sp.reco
          : st === "in" ? "已引入 · Reeve 会在合理时机自动调度，你仍只批准最终发送"
          : "已跳过 · 可在「个人页 › 专家」随时引入"}
      </div>
      {st === "idle" ?
        <div className="gl-spec-btns">
          <button className="gl-spec-skip" onClick={() => setSt("skip")}>暂不</button>
          <button className="gl-spec-in" onClick={() => setSt("in")}>引入</button>
        </div> : null}
    </div>);

}

function GmailLearning({ onDone }) {
  const [p, setP] = useStateOb(0);
  const ready = p >= GL_PHASES.length - 1;
  useEffectOb(() => {
    if (ready) return; // STOP at the ready state — wait for the user to confirm
    const t = setTimeout(() => setP(p + 1), p === 0 ? 2000 : 1750);
    return () => clearTimeout(t);
  }, [p]);
  const ph = GL_PHASES[p];
  // progress across the whole learning run (segments + a smooth fill)
  const pct = Math.round(((p + (ready ? 1 : 0.55)) / GL_PHASES.length) * 100);

  return (
    <div className="gl">
      <div className="gl-mesh" aria-hidden="true"><i /><i /><i /></div>

      {/* top progress strip — reassures the user they can step away anytime */}
      <div className="gl-top">
        <div className="gl-bar"><span className="gl-bar-fill" style={{ width: (ready ? 100 : pct) + "%" }} /></div>
        <div className="gl-top-row">
          <span className="gl-top-step">{ready ? "已完成" : `第 ${p + 1} / ${GL_PHASES.length} 步`}</span>
          <button className="gl-leave" onClick={onDone}>{ready ? "进入首页" : "先进首页，后台继续 →"}</button>
        </div>
        <div className="gl-top-note">在后台进行 · 随时可以离开，进度会保留</div>
      </div>

      <div className={`gl-core ph-${ph.k}`}>
        <span className="gl-ring r1" /><span className="gl-ring r2" /><span className="gl-ring r3" />
        <div className="gl-orbit" aria-hidden="true">
          {[0, 1, 2, 3, 4, 5].map((i) => <span key={i} className="gl-dot" style={{ "--i": i }} />)}
        </div>
        <div className="gl-mk">{ready ? <span className="gl-check">✓</span> : <ReeveMark size={36} stroke={2} />}</div>
      </div>

      <div className="gl-cap" key={p}>{ph.cap}</div>
      <div className="gl-prog">{GL_PHASES.map((_, i) => <i key={i} className={i <= p ? "on" : ""} />)}</div>

      <div className="gl-stage">
        {p >= 1 &&
          <GlReveal className="gl-facts">
            {GL_FACTS.map((f, i) =>
              <div key={i} className="gl-fact" style={{ transitionDelay: i * 0.13 + "s" }}>
                <span className="gl-fact-dot" />{f}
              </div>)}
          </GlReveal>}

        {p >= 2 &&
          <GlReveal className="gl-threads">
            <div className="gl-threads-h">要替你跟进的 4 条线</div>
            {GL_THREADS.map((t, i) =>
              <div key={i} className="gl-thread" style={{ transitionDelay: i * 0.11 + "s" }}>
                <span className="gl-thread-av">{t.a}</span>
                <span className="gl-thread-n">{t.n}</span>
                <span className="gl-thread-k">{t.k}</span>
                <span className="gl-thread-ok">✓</span>
              </div>)}
          </GlReveal>}

        {p >= 2 &&
          <GlReveal className="gl-specwrap">
            <GlSpecCard />
          </GlReveal>}
      </div>

      {/* confirm gate — must tap to enter the home */}
      <div className={`gl-foot ${ready ? "in" : ""}`}>
        <button className="gl-confirm" onClick={onDone} disabled={!ready}>
          确认，进入首页
        </button>
      </div>
    </div>);
}

function ColdStart({ onEnterApp }) {
  const [step, setStep] = useStateOb(0);     // 0 登录 · 1 连接
  const [authing, setAuthing] = useStateOb(null); // null | "apple" | "google" | "mail" | "gmail"
  const [copied, setCopied] = useStateOb(false);
  const rootRef = useRefOb(null);
  const tRef = useRefOb(null);
  useEffectOb(() => () => clearTimeout(tRef.current), []);
  // strong color background ONLY on the login screen (step 0)
  useEffectOb(() => {
    const ps = rootRef.current && rootRef.current.closest(".phone-screen");
    if (ps) ps.classList.toggle("login-bg", step === 0);
  }, [step]);

  const ADDR = "r-6a22f3@in.reeve.app"; // 专属转发地址（per-run mailbox）

  const signIn = (who) => {
    setAuthing(who);
    tRef.current = setTimeout(() => { setAuthing(null); setStep(1); }, 1350);
  };
  const connect = (how) => {
    setAuthing(how);
    if (how === "gmail") return; // GmailLearning drives onDone itself
    tRef.current = setTimeout(() => { setAuthing(null); onEnterApp(); }, 1250);
  };
  const replay = () => { clearTimeout(tRef.current); setAuthing(null); setCopied(false); setStep(0); };
  const copy = () => {
    setCopied(true);
    if (navigator.clipboard) navigator.clipboard.writeText(ADDR).catch(() => {});
    clearTimeout(tRef.current); tRef.current = setTimeout(() => setCopied(false), 1800);
  };

  let body;
  if (step === 0) {
    /* 登录 — strong color bg · Apple primary + Google (real product order) */
    body =
      <div className="ob ob-launch">
        <div className="ob-spacer" />
        <span className="ob-mk"><ReeveMark size={60} stroke={1.8} /></span>
        <div className="ob-word">Reeve</div>
        <div className="ob-tagline">线交给我穿好，你只拍板。</div>
        <div className="ob-spacer" />
        <div className="ob-auth">
          <button className="auth-btn auth-apple" onClick={() => signIn("apple")}>
            <AppleLogo /><span className="gauth-label">用 Apple 继续</span>
          </button>
          <button className="auth-btn auth-google" onClick={() => signIn("google")}>
            <GoogleG /><span className="gauth-label">用 Google 继续</span>
          </button>
        </div>
        <p className="ob-legal">继续即同意 · 服务条款 · 隐私</p>
      </div>;
  } else {
    /* 连接邮箱 — 第一优先：授权 Gmail（自动同步）；第二优先：专属转发地址（手动） */
    body =
      <div className="ob ob-connect">
        <h1 className="ob-h1">把邮件<br /><em>接给 Reeve</em>。</h1>
        <p className="ob-lede">连接 Gmail，Reeve 自动扫一遍最近往来、渐进式认识你，把要替你跟进的线理出来。</p>

        <div className="cn-card">
          <div className="cn-head">
            <span className="cn-badge">推荐</span>
            <span className="cn-title">连接 Gmail，自动同步往来</span>
          </div>
          <p className="cn-note">用 Google 授权（只读）。Reeve 一次读懂你最近的往来，认识你在做什么、和谁打交道 —— 不改不发，随时一键断开。</p>
          <button className="cn-cta cn-cta-g" onClick={() => connect("gmail")}>
            <GoogleG /><span>授权 Gmail 只读</span>
          </button>
          <p className="cn-sub">只读最近往来 · 不读你没授权的邮件</p>
        </div>

        <div className="cn-or"><span>或，先不连账户</span></div>

        <div className="cn-alt">
          <div className="cn-alt-h">转发一封到你的专属地址</div>
          <button className={`cn-addr ${copied ? "copied" : ""}`} onClick={copy}>
            <span className="cn-addr-tx">{ADDR}</span>
            <span className="cn-addr-act">{copied ? "已复制 ✓" : "复制"}</span>
          </button>
          <div className="cn-alt-row">
            <span className="cn-alt-note">不连账户，只读你转发的那一封。</span>
            <button className="cn-alt-go" onClick={() => connect("mail")}>我已转发，开始 →</button>
          </div>
        </div>
      </div>;
  }

  return (
    <div ref={rootRef} className="cs-root">
      {step >= 1 &&
        <div className="cs-nav">
          <button className="cs-replay" onClick={replay} title="重新开始" aria-label="重新开始">↻</button>
          <CsStepper step={step} />
          <span className="cs-nav-sp" />
        </div>}
      <div className="cs-step" key={step}>{body}</div>
      {authing === "gmail" ?
        <GmailLearning onDone={() => { setAuthing(null); onEnterApp(); }} /> :
       authing ?
        <div className="cs-auth-ov">
          <span className="exec-spin" />
          <div className="cs-auth-tx">
            {authing === "apple" ? "正在通过 Apple 登录…" :
             authing === "google" ? "正在通过 Google 登录…" :
             "正在读取这封邮件…"}
          </div>
        </div> : null}
    </div>);
}

window.ColdStart = ColdStart;