/* global React, window */
// First-visit onboarding tour. 7 steps with:
//   - spotlight on the specific UI element being explained (cut a hole
//     in the dim backdrop so the target stays bright + pulses);
//   - plain-language explanations (no ROAS/HOOK/CTR jargon unless
//     defined inline; no algorithm formulas in the body — those live
//     in the column ? popovers for users who want to go deeper);
//   - structured visual content (grade cards, action table, row map)
//     instead of run-on text.
// Auto-opens once (localStorage). Re-openable from the «Guide» button
// in the top bar.

const { useState, useEffect, useRef } = React;

// Bumped to v2 for round 4 (Raya step added). Users who completed the v1
// tour will see the new tour once, then the v2 key gets set.
const ONBOARDING_KEY = "atria-proto-onboarded-v2";

// Spotlight padding around the target rect.
const SPOT_PAD = 8;
// Modal width.
const MODAL_W = 640;
// Modal estimated height for placement.
const MODAL_H_EST = 420;

function getSpotRect(selector) {
  if (!selector) return null;
  const el = document.querySelector(selector);
  if (!el) return null;
  const r = el.getBoundingClientRect();
  if (r.width === 0 && r.height === 0) return null;
  return {
    x: Math.max(0, r.left - SPOT_PAD),
    y: Math.max(0, r.top - SPOT_PAD),
    w: r.width + SPOT_PAD * 2,
    h: r.height + SPOT_PAD * 2,
  };
}

// Decide where to place the modal so it doesn't cover the spotlight.
// Returns { left, top, arrow: "up"|"down"|"left"|"right"|null }.
function placeModal(spot) {
  const vw = window.innerWidth;
  const vh = window.innerHeight;
  if (!spot) {
    return {
      left: Math.max(20, (vw - MODAL_W) / 2),
      top: Math.max(20, (vh - MODAL_H_EST) / 2),
      arrow: null,
    };
  }
  const gap = 18;
  const below = spot.y + spot.h + gap + MODAL_H_EST <= vh - 20;
  const above = spot.y - gap - MODAL_H_EST >= 20;
  const right = spot.x + spot.w + gap + MODAL_W <= vw - 20;
  const left = spot.x - gap - MODAL_W >= 20;

  // Prefer below, then right, then above, then left, then center as fallback.
  if (below) {
    const cx = spot.x + spot.w / 2;
    return {
      left: Math.min(Math.max(20, cx - MODAL_W / 2), vw - MODAL_W - 20),
      top: spot.y + spot.h + gap,
      arrow: "up",
      arrowAt: cx,
    };
  }
  if (right) {
    const cy = spot.y + spot.h / 2;
    return {
      left: spot.x + spot.w + gap,
      top: Math.min(Math.max(20, cy - MODAL_H_EST / 2), vh - MODAL_H_EST - 20),
      arrow: "left",
      arrowAt: cy,
    };
  }
  if (above) {
    const cx = spot.x + spot.w / 2;
    return {
      left: Math.min(Math.max(20, cx - MODAL_W / 2), vw - MODAL_W - 20),
      top: spot.y - gap - MODAL_H_EST,
      arrow: "down",
      arrowAt: cx,
    };
  }
  if (left) {
    const cy = spot.y + spot.h / 2;
    return {
      left: spot.x - gap - MODAL_W,
      top: Math.min(Math.max(20, cy - MODAL_H_EST / 2), vh - MODAL_H_EST - 20),
      arrow: "right",
      arrowAt: cy,
    };
  }
  return {
    left: Math.max(20, (vw - MODAL_W) / 2),
    top: Math.max(20, (vh - MODAL_H_EST) / 2),
    arrow: null,
  };
}

// ===== Structured-content building blocks =====

function GradeCard({ letter, color, label, doIt, bg }) {
  return (
    <div style={{
      border: "1px solid var(--rule)",
      background: bg || "var(--card)",
      borderRadius: 6,
      padding: "10px 12px",
      display: "flex",
      alignItems: "flex-start",
      gap: 10,
    }}>
      <span style={{
        display: "grid", placeItems: "center",
        width: 28, height: 28, borderRadius: 4,
        background: color, color: "#fff",
        fontFamily: "IBM Plex Mono, monospace", fontWeight: 700, fontSize: 15,
        flexShrink: 0,
      }}>{letter}</span>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 12, color: "var(--ink)", fontWeight: 600, lineHeight: 1.3 }}>{label}</div>
        <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2, lineHeight: 1.4 }}>{doIt}</div>
      </div>
    </div>
  );
}

function BucketCard({ glyph, name, meaning, color }) {
  return (
    <div style={{
      border: "1px solid var(--rule)",
      borderLeft: `3px solid ${color}`,
      background: "var(--card)",
      borderRadius: 4,
      padding: "8px 12px",
      display: "flex",
      flexDirection: "column",
      gap: 2,
    }}>
      <div style={{ fontSize: 12, fontWeight: 600, color: "var(--ink)" }}>
        {glyph && <span style={{ color, marginRight: 6 }}>{glyph}</span>}
        {name}
      </div>
      <div style={{ fontSize: 11, color: "var(--ink-3)", lineHeight: 1.45 }}>{meaning}</div>
    </div>
  );
}

function ActionRow({ verb, meaning, behavior, color }) {
  return (
    <tr>
      <td style={{ padding: "6px 8px", borderBottom: "1px solid var(--rule)", whiteSpace: "nowrap" }}>
        <span style={{
          display: "inline-block",
          padding: "2px 8px",
          borderRadius: 3,
          background: color || "var(--ink-2)",
          color: "var(--bg)",
          fontSize: 11,
          fontWeight: 500,
        }}>{verb}</span>
      </td>
      <td style={{ padding: "6px 8px", borderBottom: "1px solid var(--rule)", fontSize: 11, color: "var(--ink)" }}>{meaning}</td>
      <td style={{ padding: "6px 8px", borderBottom: "1px solid var(--rule)", fontSize: 11, color: "var(--ink-3)" }}>{behavior}</td>
    </tr>
  );
}

// Visual map of a Radar row: 5 labeled blocks left-to-right, with
// a numbered callout for each so the body text can reference them.
function RowMap({ t }) {
  const blocks = [
    { n: 1, name: t("Creative", "创意"),    sub: t("thumbnail + title + format", "缩略图 + 标题 + 形式"), flex: 2.4 },
    { n: 2, name: t("Diagnosis", "诊断"),    sub: t("one-line problem / strength", "一句话:问题或优势"),  flex: 2.6 },
    { n: 3, name: t("Grade", "评级"),        sub: t("A · B · C · D",         "A · B · C · D"),         flex: 1 },
    { n: 4, name: t("Money", "钱"),          sub: t("spend · ROAS",             "花费 · 投资回报率"),       flex: 1.4 },
    { n: 5, name: t("Action", "动作"),       sub: t("button: what to do",       "按钮:该做什么"),           flex: 1.6 },
  ];
  return (
    <div style={{
      display: "flex",
      gap: 4,
      marginTop: 4,
      border: "1px solid var(--rule)",
      borderRadius: 4,
      overflow: "hidden",
      background: "var(--card)",
    }}>
      {blocks.map((b, i) => (
        <div key={b.n} style={{
          flex: b.flex,
          minWidth: 0,
          padding: "8px 10px",
          borderRight: i < blocks.length - 1 ? "1px dashed var(--rule)" : "0",
          display: "flex", flexDirection: "column", gap: 3,
        }}>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
            <span style={{
              display: "inline-grid", placeItems: "center",
              width: 14, height: 14, borderRadius: "50%",
              background: "var(--accent)", color: "var(--accent-ink)",
              fontFamily: "IBM Plex Mono, monospace", fontSize: 9, fontWeight: 600,
            }}>{b.n}</span>
            <span style={{ fontSize: 11, fontWeight: 600, color: "var(--ink)" }}>{b.name}</span>
          </div>
          <div style={{ fontSize: 10, color: "var(--ink-3)", lineHeight: 1.3, fontFamily: "IBM Plex Sans, sans-serif" }}>{b.sub}</div>
        </div>
      ))}
    </div>
  );
}

// Simple horizontal step flow (3 nodes + arrows).
// Sidebar tour row — used in Step 07 to describe each sidebar entry.
function SidebarTourRow({ kind, name, body, current, hot }) {
  const groupColor = kind === "creation" ? "#7A4D9E" : "var(--accent)";
  return (
    <div style={{
      display: "flex",
      gap: 10,
      alignItems: "flex-start",
      padding: "8px 12px",
      border: current ? "1.5px solid var(--accent)" : "1px solid var(--rule)",
      background: current ? "var(--accent-tint)" : "var(--card)",
      borderRadius: 4,
      borderLeft: `3px solid ${groupColor}`,
    }}>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 2 }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink)" }}>{name}</span>
          {current && (
            <span className="mono" style={{ fontSize: 8, padding: "1px 5px", background: "var(--accent)", color: "#fff", borderRadius: 2, letterSpacing: ".06em", fontWeight: 600 }}>
              YOU ARE HERE
            </span>
          )}
          {hot && (
            <span className="mono" style={{ fontSize: 8, padding: "1px 5px", background: "linear-gradient(135deg, #E03A0C 0%, #F0741C 100%)", color: "#fff", borderRadius: 2, letterSpacing: ".06em", fontWeight: 700 }}>
              HOT
            </span>
          )}
        </div>
        <div style={{ fontSize: 11.5, color: "var(--ink-2)", lineHeight: 1.5 }}>{body}</div>
      </div>
    </div>
  );
}

function FlowSteps({ steps }) {
  return (
    <div style={{ display: "flex", alignItems: "stretch", gap: 6, marginTop: 4 }}>
      {steps.map((s, i) => (
        <React.Fragment key={i}>
          <div style={{
            flex: 1,
            border: "1px solid var(--rule)",
            background: "var(--card)",
            borderRadius: 4,
            padding: "8px 10px",
            display: "flex", flexDirection: "column", gap: 3,
          }}>
            <div style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
              <span style={{
                display: "inline-grid", placeItems: "center",
                width: 16, height: 16, borderRadius: "50%",
                background: "var(--accent)", color: "var(--accent-ink)",
                fontFamily: "IBM Plex Mono, monospace", fontSize: 10, fontWeight: 600,
              }}>{i + 1}</span>
              <span style={{ fontSize: 11.5, fontWeight: 600, color: "var(--ink)" }}>{s.title}</span>
            </div>
            <div style={{ fontSize: 11, color: "var(--ink-3)", lineHeight: 1.45 }}>{s.body}</div>
          </div>
          {i < steps.length - 1 && (
            <div style={{ display: "grid", placeItems: "center", color: "var(--accent)", fontSize: 18, lineHeight: 1, fontWeight: 600 }}>→</div>
          )}
        </React.Fragment>
      ))}
    </div>
  );
}

// ===== Step content =====
// Each step: eyebrow, title, target (CSS selector, optional), body (JSX).

function buildSteps(t) {
  return [
    {
      eyebrow: t("Welcome", "欢迎"),
      title: t("30 seconds to learn the product.", "花 30 秒认识一下这个产品。"),
      target: null,
      body: (
        <>
          <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.65, color: "var(--ink-2)" }}>
            {t(
              "Atria helps you manage your ads. You give it a bunch of ads that are currently running; it tells you which ones are doing well (keep them), which ones aren't (fix them), and ships your fixes straight back to the ad platform.",
              "Atria 帮你管你正在投放的广告。你把现在跑着的广告交给它,它告诉你哪些表现好(继续投)、哪些不好(改一下)、改完直接送回投放平台。"
            )}
          </p>
          <p style={{ margin: "10px 0 0", fontSize: 13.5, lineHeight: 1.65, color: "var(--ink-2)" }}>
            {t(
              "The next 6 steps walk you through this screen — what each part is, and how to actually use it.",
              "接下来 6 步,带你看一遍这个屏幕 —— 每一块是干什么的、怎么用。"
            )}
          </p>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 14, letterSpacing: ".04em" }}>
            {t(
              "Tip: ← → keys or buttons below to walk through. Esc skips. Reopen any time from the «Guide» button (top right).",
              "提示:按 ← → 或下方按钮翻页。Esc 跳过。想再看一次?点顶栏右上角的「新手引导」按钮。"
            )}
          </div>
        </>
      ),
    },
    {
      eyebrow: t("Step 01 · The buckets", "第 1 步 · 4 个分桶"),
      title: t("Your ads are split into 4 buckets.", "你的广告被分成 4 桶。"),
      target: '[data-tour="bucket-tabs"]',
      body: (
        <>
          <p style={{ margin: 0, fontSize: 13, lineHeight: 1.65, color: "var(--ink-2)" }}>
            {t(
              "The tabs at the top of the table split every ad into one of these four groups. Click a tab to see only that group. The number on each tab is how many ads are in that bucket right now.",
              "表格上方的 tab 把每条广告分到下面 4 个组里。点一个 tab,只看那一组。tab 上的数字 = 当前这组里有几条广告。"
            )}
          </p>
          <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 12 }}>
            <BucketCard glyph="★" name={t("Winners", "赢家")} color="var(--accent)"
              meaning={t("Doing better than your other ads. Atria suggests: keep + give them more money.", "比你其他广告都强。Atria 建议:继续投 + 加预算。")} />
            <BucketCard glyph="▴" name={t("Close to winning", "迭代潜力大")} color="var(--accent)"
              meaning={t("Not winners yet, but close — small tweaks could push them over.", "差一点就成赢家了。小改动有机会把它们推过去。")} />
            <BucketCard glyph="·" name={t("Needs work", "待迭代")} color="var(--ink-3)"
              meaning={t("Below average. Atria suggests: change them or stop them.", "低于平均水平。Atria 建议:改一下,或者停掉。")} />
            <BucketCard glyph={null} name={t("All ads", "全部广告")} color="var(--ink-3)"
              meaning={t("Everything in one list — no bucket filter.", "不分桶,所有广告放一起看。")} />
          </div>
        </>
      ),
    },
    {
      eyebrow: t("Step 02 · Reading a row", "第 2 步 · 一行怎么读"),
      title: t("Each row = one ad. Five blocks of info, left to right.", "每一行 = 一条广告。从左到右 5 块信息。"),
      target: 'table.radar tbody tr:first-child',
      body: (
        <>
          <RowMap t={t} />
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 6, fontSize: 12, color: "var(--ink-2)", lineHeight: 1.5 }}>
            <div><strong style={{ color: "var(--accent)" }}>1 {t("Creative", "创意")}.</strong> {t("Which ad this row is. Thumbnail, headline, and whether it's an image or video.", "告诉你这一行是哪条广告。缩略图、标题、是图片还是视频。")}</div>
            <div><strong style={{ color: "var(--accent)" }}>2 {t("Diagnosis", "诊断")}.</strong> {t("A plain-English line — e.g. «Headline isn't hooking people», «Conversion dropped».", "一句白话 —— 比如「标题钩不住人」「转化掉了」。")}</div>
            <div><strong style={{ color: "var(--accent)" }}>3 {t("Grade", "评级")}.</strong> {t("One letter, A to D. (Next step explains.)", "一个字母,A 到 D。(下一步会讲。)")}</div>
            <div><strong style={{ color: "var(--accent)" }}>4 {t("Money", "钱")}.</strong> {t("How much this ad has spent, and how much revenue it brought back per $1 (ROAS = revenue ÷ spend).", "这条广告花了多少钱;每 1 元能挣回多少(ROAS = 营收 ÷ 花费)。")}</div>
            <div><strong style={{ color: "var(--accent)" }}>5 {t("Action", "动作")}.</strong> {t("A button that says what Atria recommends doing next. (Step 4 covers the verbs.)", "一个按钮,写着 Atria 建议你下一步做什么。(第 4 步会讲所有动词。)")}</div>
          </div>
        </>
      ),
    },
    {
      eyebrow: t("Step 03 · The grade", "第 3 步 · 评级"),
      title: t("Every ad gets one letter — A, B, C, or D.", "每条广告都打一个字母 —— A、B、C 或 D。"),
      target: '[data-tour="grade-col"]',
      body: (
        <>
          <p style={{ margin: 0, fontSize: 13, lineHeight: 1.6, color: "var(--ink-2)" }}>
            {t(
              "The letter answers one question: «Compared to your other ads in the same vertical, how is this one doing?» A = top, D = bottom. It's relative — not an absolute pass/fail line.",
              "字母只回答一个问题:「跟你账号下同类目的其他广告比,这条排第几?」A = 排前面,D = 排后面。是相对位置,不是绝对的合格线。"
            )}
          </p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 14 }}>
            <GradeCard letter="A" color="var(--grade-a)"
              label={t("Top 10%",       "排进前 10%")}
              doIt={t("Give it +30% more budget", "建议加 30% 预算")} />
            <GradeCard letter="B" color="var(--grade-b)"
              label={t("Top 25%",       "排进前 25%")}
              doIt={t("Keep running as is", "继续投,别动")} />
            <GradeCard letter="C" color="var(--grade-c)"
              label={t("Bottom half",    "排在后一半")}
              doIt={t("Iterate — change it", "该改改了")} />
            <GradeCard letter="D" color="var(--grade-d)"
              label={t("Bottom 25%",    "排在后 25%")}
              doIt={t("Pause it or rework completely", "暂停,或者整个重做")} />
          </div>
          <div style={{ marginTop: 12, fontSize: 11.5, color: "var(--ink-3)", lineHeight: 1.55, padding: "8px 10px", background: "var(--bg-deep)", borderRadius: 4 }}>
            {t(
              "Want to see the exact formula? Click the small «?» next to the «Grade» column header — it spells out the algorithm and which industry benchmarks (Meta, Google, etc.) inspired it.",
              "想看具体公式?点表头「评级」旁边的小「?」 —— 里面写了完整算法,以及参照的行业标准(Meta、Google 等)。"
            )}
          </div>
        </>
      ),
    },
    {
      eyebrow: t("Step 04 · The action button", "第 4 步 · 右边的动作按钮"),
      title: t("The rightmost column tells you exactly what to do.", "最右边那列写着「该做什么」。"),
      target: '[data-tour="action-col"]',
      body: (
        <>
          <p style={{ margin: 0, fontSize: 13, lineHeight: 1.6, color: "var(--ink-2)" }}>
            {t(
              "Five possible verbs. Light ones confirm right inside the row (2 seconds). Heavy ones open a detail page because they need AI to think.",
              "一共 5 个动词。轻的(只需要在投放平台改个开关)在行内秒确认。重的(需要 AI 思考)会打开详情页。"
            )}
          </p>
          <div style={{ marginTop: 12, border: "1px solid var(--rule)", borderRadius: 4, overflow: "hidden" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", background: "var(--card)" }}>
              <thead>
                <tr style={{ background: "var(--bg-deep)" }}>
                  <th style={{ padding: "6px 8px", textAlign: "left", fontSize: 10, color: "var(--ink-3)", fontFamily: "IBM Plex Mono, monospace", textTransform: "uppercase", letterSpacing: ".08em", borderBottom: "1px solid var(--rule)" }}>{t("Button", "按钮")}</th>
                  <th style={{ padding: "6px 8px", textAlign: "left", fontSize: 10, color: "var(--ink-3)", fontFamily: "IBM Plex Mono, monospace", textTransform: "uppercase", letterSpacing: ".08em", borderBottom: "1px solid var(--rule)" }}>{t("What it means", "什么意思")}</th>
                  <th style={{ padding: "6px 8px", textAlign: "left", fontSize: 10, color: "var(--ink-3)", fontFamily: "IBM Plex Mono, monospace", textTransform: "uppercase", letterSpacing: ".08em", borderBottom: "1px solid var(--rule)" }}>{t("Click → what happens", "点了之后")}</th>
                </tr>
              </thead>
              <tbody>
                <ActionRow color="var(--grade-d)"
                  verb={t("Pause",  "暂停")}
                  meaning={t("Stop spending on this ad", "别再给这条广告烧钱了")}
                  behavior={t("Inline confirm, 2 sec", "行内秒确认")} />
                <ActionRow color="var(--grade-a)"
                  verb={t("Scale +30%",  "扩量 +30%")}
                  meaning={t("Give it 30% more budget", "加 30% 预算")}
                  behavior={t("Inline confirm, 2 sec", "行内秒确认")} />
                <ActionRow color="var(--grade-b)"
                  verb={t("Clone",  "克隆")}
                  meaning={t("Copy it as a brand-new test ad", "拷一份做新测试")}
                  behavior={t("Inline confirm", "行内确认")} />
                <ActionRow color="var(--accent)"
                  verb={t("Iterate",  "迭代")}
                  meaning={t("Change something — get AI to suggest variants", "让 AI 出几个改版")}
                  behavior={t("Opens detail page", "打开详情页")} />
                <ActionRow color="var(--accent)"
                  verb={t("Refresh",  "换素材")}
                  meaning={t("Swap the visual entirely", "把图/视频整个换掉")}
                  behavior={t("Opens detail page", "打开详情页")} />
              </tbody>
            </table>
          </div>
          <div style={{ marginTop: 10, fontSize: 11.5, color: "var(--ink-3)", lineHeight: 1.55 }}>
            {t(
              "Every row also has a «Why?» link. Click it to open the detail page on the «Performance» tab — read first, act after.",
              "每一行还有一个「为什么?」链接。点它会打开详情页并直接落到「投放表现」tab —— 先看懂,再动手。"
            )}
          </div>
        </>
      ),
    },
    {
      eyebrow: t("Step 05 · Create new ads with Raya", "第 5 步 · 用 Raya 创建新广告"),
      title: t("«+ Create ad creative» talks to Raya — Atria's AI agent.", "「+ 创建广告创意」会带你去跟 Raya 对话 —— Atria 的 AI 代理。"),
      target: '[data-tour="create-ad-btn"]',
      body: (
        <>
          <p style={{ margin: 0, fontSize: 13, lineHeight: 1.6, color: "var(--ink-2)" }}>
            {t(
              "See the «+ Create ad creative» button at the top right? Click it and pick «Talk to Raya». You type ONE sentence — «3 variants of my top coffee ad for Gen-Z, urgency tone, ship by Friday» — and Raya pulls your data, generates the variants, and pushes the winner back to Meta.",
              "看到右上角的「+ 创建广告创意」了吗?点它,选「跟 Raya 对话」。你打 1 句话 —— 比如「把我最强的咖啡广告出 3 个 Gen-Z 改版,紧迫感语气,周五前上线」 —— Raya 会自己调数据、出变体、把最好的那个推回 Meta。"
            )}
          </p>
          <FlowSteps steps={[
            { title: t("You type 1 sentence", "你打 1 句话"),
              body: t("Or click a suggestion chip to auto-complete the prompt.", "或者点输入框下面的灵感 chip 自动补全。") },
            { title: t("Raya generates 4 variants", "Raya 出 4 个变体"),
              body: t("Within your brand colors + voice, with estimated ROAS lift on each.", "在你的品牌色 + 语气内,每个都带 ROAS 预估涨幅。") },
            { title: t("Click «Push to platform»", "点「推到平台」"),
              body: t("The new ad shows up at the top of Radar with a «just created» glow.", "新广告会在 Radar 顶部出现,带「刚刚创建」高光。") },
          ]} />
          <div style={{ marginTop: 12, fontSize: 11.5, color: "var(--ink-3)", lineHeight: 1.55, padding: "8px 10px", background: "var(--accent-tint)", borderRadius: 4, borderLeft: "3px solid var(--accent)" }}>
            {t(
              "Look for the «HOT» badge on «AI Playground · Raya» in the left sidebar — that's where the conversation panel lives. You can also open it directly from there.",
              "左边栏「AI 实验场 · Raya」上有一个「HOT」徽标 —— 对话面板就在那里。也可以从那里直接打开。"
            )}
          </div>
        </>
      ),
    },
    {
      eyebrow: t("Step 06 · AI Playground — your sandbox", "第 6 步 · AI 实验场 —— 你的沙盒"),
      title: t("Explore without a brief. Talk to Raya, or pick from saved demos.", "没有 brief 也能先探索。跟 Raya 对话,或者从样例库挑一个。"),
      target: '[data-tour="nav-playground"]',
      body: (
        <>
          <p style={{ margin: 0, fontSize: 13, lineHeight: 1.6, color: "var(--ink-2)" }}>
            {t(
              "Radar = data-grounded — every iteration starts from a specific ad's performance numbers. AI Playground = exploration — try a brand voice, an audience, a visual style you don't have an ad for yet. Output stays here unless you push it.",
              "Radar 是「数据驱动」 —— 每次迭代都从某条广告的具体数据出发。AI 实验场是「自由探索」 —— 试一种品牌语气、一群受众、一种你还没真投过的视觉风格。产出留在这里,除非你主动推上去。"
            )}
          </p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginTop: 14 }}>
            <div style={{ border: "1px solid var(--accent-tint-2)", borderLeft: "3px solid var(--accent)", background: "var(--accent-tint)", padding: "10px 12px", borderRadius: 4 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--ink)", marginBottom: 4 }}>
                {t("Raya · conversational", "Raya · 对话式")}
                <span className="mono" style={{ fontSize: 8, marginLeft: 6, padding: "1px 4px", background: "var(--accent)", color: "#fff", borderRadius: 2, letterSpacing: ".06em", fontWeight: 700 }}>HOT</span>
              </div>
              <div style={{ fontSize: 11, color: "var(--ink-2)", lineHeight: 1.5 }}>
                {t("One sentence in, 4 variants out. Best for fast «what if we tried…».", "一句话进,4 个变体出。适合「要不要试试……」这种快速实验。")}
              </div>
            </div>
            <div style={{ border: "1px solid var(--rule)", background: "var(--card)", padding: "10px 12px", borderRadius: 4 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--ink)", marginBottom: 4 }}>
                {t("Saved demos · curated", "样例库 · 团队精选")}
              </div>
              <div style={{ fontSize: 11, color: "var(--ink-2)", lineHeight: 1.5 }}>
                {t("Six prompt × variant presets the team's been iterating on. See what «good» looks like first.", "团队这阵子在迭代的 6 组 prompt 预设。先看「好的产出」长什么样。")}
              </div>
            </div>
          </div>
          <div style={{ marginTop: 12, fontSize: 11.5, color: "var(--ink-3)", lineHeight: 1.55, padding: "8px 10px", background: "var(--bg-deep)", borderRadius: 4 }}>
            {t(
              "Variants you like → click «Push to platform» → goes live as a new ad in Meta + shows up at the top of Radar with a «just created» glow. Closes the loop visibly.",
              "看上的变体 → 点「推到投放平台」 → 作为新广告上线 Meta + 在 Radar 顶部出现「刚刚创建」高光。闭环肉眼可见。"
            )}
          </div>
        </>
      ),
    },
    {
      eyebrow: t("Step 07 · The rest of the sidebar", "第 7 步 · 左边栏其他模块"),
      title: t("Five more things the sidebar gets you to.", "左边栏还有 5 个模块,看一下分别管什么。"),
      target: '[data-tour="nav-overview"]',
      body: (
        <>
          <p style={{ margin: 0, fontSize: 13, lineHeight: 1.6, color: "var(--ink-2)" }}>
            {t(
              "The sidebar is grouped into «Analytics» (where the data lives) and «Creation» (where new ads come from). Here's what each entry does:",
              "左边栏分两组:「数据分析」(看数据)和「创意生成」(做新广告)。每一项干什么:"
            )}
          </p>
          <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 12 }}>
            <SidebarTourRow
              kind="analytics"
              name={t("Overview · KPI lobby", "总览 · KPI 大厅")}
              body={t("Your week at a glance. Active ads, ROAS, alerts, recent iterations — links into the right deep-dive screen. Start here on Monday.", "本周一图看懂:活跃广告、ROAS、告警、最近迭代 —— 每块都能跳到对应的详情页。周一从这里开。")}
            />
            <SidebarTourRow
              kind="analytics"
              name={t("Radar · where you are now", "Radar · 你现在在的页")}
              body={t("Active ads scored against cohort, sorted by «what's worth doing next». 90% of the workday lives here.", "在跑的广告跟同类比的评分 + 排序的「下一步该做什么」。90% 的工作时间都在这里。")}
              current
            />
            <SidebarTourRow
              kind="analytics"
              name={t("Iteration history · audit trail", "迭代历史 · 完整审计")}
              body={t("Every iteration you've ever shipped: original ad → what changed → which variant won → live performance. The «paper trail» when someone asks «why is this ad doing better now?»", "你做过的每一次迭代:原广告 → 改了什么 → 哪个变体赢了 → 上线表现。有人问「为什么这条现在更好?」,答案在这里。")}
            />
            <SidebarTourRow
              kind="analytics"
              name={t("Pulse · real-time alerts", "Pulse · 实时告警")}
              body={t("Live signal stream — performance drops, spend anomalies, fatigue warnings. Each alert links back to the ad in Radar so you can act on it.", "实时信号流 —— 表现下滑、花费异常、审美疲劳预警。每条告警都连回 Radar 对应的广告,直接动手。")}
            />
            <SidebarTourRow
              kind="creation"
              name={t("Image Ads · creative library", "图片广告 · 创意素材库")}
              body={t("Every image creative ever generated by you / Raya / the team — searchable, taggable, downloadable. The shared archive of «what we've shipped».", "你 / Raya / 团队生成过的所有图片创意 —— 可搜、可打标签、可下载。整盘投放的「已上线素材库」。")}
            />
            <SidebarTourRow
              kind="creation"
              name={t("AI Playground · Raya", "AI 实验场 · Raya")}
              body={t("Step 06 above. The conversational sandbox.", "上面第 6 步讲过。对话式沙盒。")}
              hot
            />
          </div>
          <div style={{ marginTop: 12, fontSize: 11.5, color: "var(--ink-3)", lineHeight: 1.55, padding: "8px 10px", background: "var(--bg-deep)", borderRadius: 4 }}>
            {t(
              "«Brands» (at the very bottom) lets you switch between brands you manage — same UI, different ad inventory. Top-left brand chip also switches.",
              "「品牌」(最下面)在你管理的多个品牌之间切换 —— 同一套界面,不同的广告库。左上角的品牌 chip 也能切。"
            )}
          </div>
        </>
      ),
    },
    {
      eyebrow: t("Step 08 · What happens after you iterate", "第 8 步 · 迭代之后"),
      title: t("Click «Iterate» → AI does 3 things, you stay in the loop.", "点了「迭代」之后,AI 帮你做 3 件事。"),
      target: '[data-tour="nav-iterations"]',
      body: (
        <>
          <FlowSteps steps={[
            { title: t("AI generates 4 variants", "AI 出 4 个改版"),
              body: t("Different headline, different visual, different CTA — same ad, four options.", "不同标题、不同图、不同 CTA —— 同一条广告,4 个候选版本。") },
            { title: t("You pick the winner", "你挑一个"),
              body: t("Compare them side-by-side. Pick the one you like — or pick 2 to A/B.", "并排对比,选一个;也可以选 2 个做 A/B。") },
            { title: t("Push back to Meta", "推回投放平台"),
              body: t("Your pick goes live as a new ad set, A/B-tested against the original.", "你选的那个作为新广告组上线,跟原图自动 A/B。") },
          ]} />
          <p style={{ margin: "14px 0 0", fontSize: 12.5, lineHeight: 1.6, color: "var(--ink-2)" }}>
            {t(
              "Every iteration is logged. The full chain — original ad → what you changed → which variant shipped → how it performs live — lives in the «Iteration history» sidebar entry (highlighted on the left).",
              "每一次迭代都有完整记录。整条链:原广告 → 改了什么 → 哪个改版上线了 → 上线后的表现,都在左侧「迭代历史」里(高亮的那个)。"
            )}
          </p>
        </>
      ),
    },
    {
      eyebrow: t("Step 09 · Help is everywhere", "第 9 步 · 哪里找帮助"),
      title: t("Stuck? Three places to look.", "看不懂?去这 3 个地方。"),
      target: '[data-tour="guide-btn"]',
      body: (
        <>
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 4 }}>
            <div style={{ display: "flex", gap: 10, alignItems: "flex-start", padding: "10px 12px", border: "1px solid var(--rule)", borderRadius: 4, background: "var(--card)" }}>
              <span style={{
                display: "inline-grid", placeItems: "center",
                width: 20, height: 20, borderRadius: "50%",
                border: "1.5px solid var(--ink-3)",
                fontSize: 10, fontWeight: 700, color: "var(--ink-3)",
                flexShrink: 0,
              }}>?</span>
              <div>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink)" }}>{t("The little «?» circles", "小「?」圆圈")}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2, lineHeight: 1.5 }}>
                  {t("On any column header with a non-obvious meaning. Click to see what the score is and how it's calculated.", "出现在含义不太直白的列头旁边。点开看那个分数是什么、怎么算出来的。")}
                </div>
              </div>
            </div>
            <div style={{ display: "flex", gap: 10, alignItems: "flex-start", padding: "10px 12px", border: "1px solid var(--rule)", borderRadius: 4, background: "var(--card)" }}>
              <span style={{
                display: "inline-grid", placeItems: "center",
                width: 20, height: 20, borderRadius: 3,
                background: "var(--ink)", color: "var(--bg)",
                fontFamily: "IBM Plex Mono, monospace", fontSize: 9, fontWeight: 600,
                flexShrink: 0,
              }}>EN | 中</span>
              <div>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink)" }}>{t("Top bar buttons", "顶栏按钮")}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2, lineHeight: 1.5 }}>
                  {t("EN | 中 switches language anywhere. «Design rationale» (why we built it this way). «Docs» (full external documentation).", "EN | 中 随时切语言。「设计思路」看「为什么这么改」。「文档」打开完整外部文档。")}
                </div>
              </div>
            </div>
            <div style={{ display: "flex", gap: 10, alignItems: "flex-start", padding: "10px 12px", border: "1px solid var(--accent-tint-2)", borderRadius: 4, background: "var(--accent-tint)" }}>
              <span style={{
                display: "inline-grid", placeItems: "center",
                width: 20, height: 20, borderRadius: "50%",
                background: "var(--accent)", color: "var(--accent-ink)",
                fontSize: 11, fontWeight: 700,
                flexShrink: 0,
              }}>?</span>
              <div>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink)" }}>{t("«Guide» button — top right", "「新手引导」按钮 —— 在顶栏右上角")}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-2)", marginTop: 2, lineHeight: 1.5 }}>
                  {t("Reopens this whole tour any time. Lost? Forgot something? Click it.", "随时重开整段引导。看忘了?再点一次就行。")}
                </div>
              </div>
            </div>
          </div>
        </>
      ),
    },
  ];
}

// ===== Main component =====

function Onboarding({ onClose }) {
  const t = window.useT();
  const { Icon } = window;
  const [step, setStep] = useState(0);
  const [tick, setTick] = useState(0); // forces spot recompute on resize / step
  const steps = buildSteps(t);
  const cur = steps[step];
  const last = step === steps.length - 1;
  const first = step === 0;

  const [spot, setSpot] = useState(() => getSpotRect(cur.target));

  // Recompute spot when step changes or window resizes. Multiple
  // delayed measurements catch layout shifts from images loading,
  // language toggle, etc.
  useEffect(() => {
    function recompute() {
      setSpot(getSpotRect(cur.target));
    }
    recompute();
    const ids = [setTimeout(recompute, 80), setTimeout(recompute, 280)];
    window.addEventListener("resize", recompute);
    window.addEventListener("scroll", recompute, true);
    return () => {
      ids.forEach(clearTimeout);
      window.removeEventListener("resize", recompute);
      window.removeEventListener("scroll", recompute, true);
    };
  }, [step, tick, cur.target]);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") { finish(); }
      else if (e.key === "ArrowRight") { if (last) finish(); else setStep(s => s + 1); }
      else if (e.key === "ArrowLeft" && !first) { setStep(s => s - 1); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [step, last, first]);

  function finish() {
    try { localStorage.setItem(ONBOARDING_KEY, "1"); } catch {}
    onClose && onClose();
  }

  const pos = placeModal(spot);
  const dim = "rgba(20, 16, 12, 0.55)"; // darker so the spotlight reads as "lit"

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 200, pointerEvents: "none" }}>
      {/* Pulse keyframes — inlined so this component is self-contained. */}
      <style>{`
        @keyframes atria-onboard-pulse {
          0%   { box-shadow: 0 0 0 0 rgba(209, 74, 31, 0.55), 0 0 0 4px rgba(209, 74, 31, 0.18); }
          70%  { box-shadow: 0 0 0 10px rgba(209, 74, 31, 0),     0 0 0 4px rgba(209, 74, 31, 0.18); }
          100% { box-shadow: 0 0 0 0 rgba(209, 74, 31, 0),         0 0 0 4px rgba(209, 74, 31, 0.18); }
        }
      `}</style>

      {/* Dim layer — built from 4 rects so the target stays at full
          brightness (vs. an overlay-with-cutout, which would also dim
          the target). Clicking dim closes the tour. */}
      {spot ? (
        <>
          <div onClick={finish} style={{ position: "fixed", left: 0, top: 0, right: 0, height: spot.y, background: dim, pointerEvents: "auto" }} />
          <div onClick={finish} style={{ position: "fixed", left: 0, top: spot.y, width: spot.x, height: spot.h, background: dim, pointerEvents: "auto" }} />
          <div onClick={finish} style={{ position: "fixed", left: spot.x + spot.w, top: spot.y, right: 0, height: spot.h, background: dim, pointerEvents: "auto" }} />
          <div onClick={finish} style={{ position: "fixed", left: 0, top: spot.y + spot.h, right: 0, bottom: 0, background: dim, pointerEvents: "auto" }} />

          {/* Pulse ring around the spotlight */}
          <div style={{
            position: "fixed",
            left: spot.x, top: spot.y, width: spot.w, height: spot.h,
            border: "2px solid var(--accent)",
            borderRadius: 6,
            pointerEvents: "none",
            animation: "atria-onboard-pulse 1.8s infinite",
            zIndex: 201,
          }} />
        </>
      ) : (
        <div onClick={finish} style={{ position: "fixed", inset: 0, background: dim, pointerEvents: "auto" }} />
      )}

      {/* Arrow pointing from modal toward the spotlight */}
      {spot && pos.arrow && (() => {
        const sz = 14;
        let arrowStyle = {};
        if (pos.arrow === "up") {
          arrowStyle = {
            left: Math.min(Math.max(pos.left + 24, pos.arrowAt - sz / 2), pos.left + MODAL_W - 24 - sz),
            top: pos.top - sz / 2 + 1,
            width: sz, height: sz,
            background: "var(--card)",
            borderLeft: "1px solid var(--rule-strong)",
            borderTop: "1px solid var(--rule-strong)",
            transform: "rotate(45deg)",
          };
        } else if (pos.arrow === "down") {
          arrowStyle = {
            left: Math.min(Math.max(pos.left + 24, pos.arrowAt - sz / 2), pos.left + MODAL_W - 24 - sz),
            top: pos.top + MODAL_H_EST - sz / 2 - 1,
            width: sz, height: sz,
            background: "var(--card)",
            borderRight: "1px solid var(--rule-strong)",
            borderBottom: "1px solid var(--rule-strong)",
            transform: "rotate(45deg)",
          };
        } else if (pos.arrow === "left") {
          arrowStyle = {
            left: pos.left - sz / 2 + 1,
            top: Math.min(Math.max(pos.top + 24, pos.arrowAt - sz / 2), pos.top + MODAL_H_EST - 24 - sz),
            width: sz, height: sz,
            background: "var(--card)",
            borderLeft: "1px solid var(--rule-strong)",
            borderBottom: "1px solid var(--rule-strong)",
            transform: "rotate(45deg)",
          };
        } else if (pos.arrow === "right") {
          arrowStyle = {
            left: pos.left + MODAL_W - sz / 2 - 1,
            top: Math.min(Math.max(pos.top + 24, pos.arrowAt - sz / 2), pos.top + MODAL_H_EST - 24 - sz),
            width: sz, height: sz,
            background: "var(--card)",
            borderRight: "1px solid var(--rule-strong)",
            borderTop: "1px solid var(--rule-strong)",
            transform: "rotate(45deg)",
          };
        }
        return <div style={{ position: "fixed", zIndex: 203, ...arrowStyle }} />;
      })()}

      {/* Modal */}
      <div
        style={{
          position: "fixed",
          left: pos.left, top: pos.top,
          width: MODAL_W, maxWidth: "calc(100vw - 40px)",
          maxHeight: "calc(100vh - 40px)",
          overflow: "auto",
          background: "var(--card)",
          border: "1px solid var(--rule-strong)",
          borderRadius: 8,
          boxShadow: "0 30px 80px rgba(26, 20, 16, 0.35)",
          padding: "22px 24px 18px",
          pointerEvents: "auto",
          zIndex: 202,
          transition: "left .25s ease, top .25s ease",
        }}
      >
        {/* Step progress dots */}
        <div style={{ display: "flex", gap: 4, marginBottom: 16 }}>
          {steps.map((_, i) => (
            <span key={i} style={{
              height: 3, flex: 1,
              borderRadius: 2,
              background: i <= step ? "var(--accent)" : "var(--rule)",
              transition: "background .2s",
            }} />
          ))}
        </div>

        <div className="label" style={{ color: "var(--accent)", marginBottom: 6 }}>
          {cur.eyebrow}
        </div>
        <div className="t-h1" style={{ fontSize: 22, marginBottom: 12, lineHeight: 1.25 }}>
          {cur.title}
        </div>
        <div>
          {cur.body}
        </div>

        <div style={{
          marginTop: 18, paddingTop: 14,
          borderTop: "1px solid var(--rule)",
          display: "flex", alignItems: "center", justifyContent: "space-between",
          gap: 10, flexWrap: "wrap",
        }}>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
            <button className="btn ghost sm" onClick={finish}>
              {t("Skip tour", "跳过")}
            </button>
            <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>
              {step + 1} / {steps.length}
            </span>
          </div>
          <span style={{ display: "inline-flex", gap: 8 }}>
            {!first && (
              <button className="btn sm" onClick={() => setStep(s => s - 1)}>
                <span style={{ transform: "scaleX(-1)", display: "inline-block" }}>
                  <Icon name="chev" size={11} />
                </span>
                {t("Back", "上一步")}
              </button>
            )}
            {!last && (
              <button className="btn primary sm" onClick={() => setStep(s => s + 1)}>
                {t("Next", "下一步")} <Icon name="chev" size={11} />
              </button>
            )}
            {last && (
              <button className="btn primary sm" onClick={finish}>
                {t("Got it · start", "明白了 · 开始用")} <Icon name="arrow" size={11} />
              </button>
            )}
          </span>
        </div>
      </div>
    </div>
  );
}

// Hook used by App: returns [open, setOpen] with localStorage-backed default.
function useOnboarding() {
  const [open, setOpen] = useState(() => {
    try { return !localStorage.getItem(ONBOARDING_KEY); } catch { return false; }
  });
  return [open, setOpen];
}

Object.assign(window, { Onboarding, useOnboarding, ONBOARDING_KEY });
