// SQSEO Deep Dive — the reveal that closes onboarding. While the wizard was
// being filled in, the Site Intelligence scanner (Phase 16) crawled the user's
// site in the background; this screen turns that into the product's first
// "it actually read my site" moment: a calm scanning stage with REAL progress,
// then a staged reveal of who they are, what they sell, the keywords their
// pages target, and the seed topics we'd research first — ending in a CTA that
// drops the best seed straight into Keyword Research.
//
// House rules: every number on screen is real (crawled pages, mined keywords —
// nothing invented); near-monochrome, coral only as an accent dot/chip; Lucide
// icons; motion is staggered fade-ups that respect prefers-reduced-motion.
// Registered as window.LTQ.DeepDive; rendered by Onboarding after activation.
(function init() {
  if (!window.LongtailIQDesignSystem_ae8f12 || !window.LTQ || !window.LTQ.api || !window.LTQ.t) { return setTimeout(init, 30); }
  const React = window.React;
  const DS = window.LongtailIQDesignSystem_ae8f12;
  const { Icon } = DS;
  const { api, t } = window.LTQ;

  const POLL_MS = 1800;
  const MAX_WAIT_MS = 90_000; // then we stop holding the user hostage

  // ---- tiny shared pieces (match the wizard's inline-token vocabulary) ----
  function Primary({ children, onClick, icon, trailingIcon }) {
    return (
      <button onClick={onClick} className="lt-btn-3d" style={{ height: 44, padding: "0 20px", borderRadius: 10, border: "none", background: "var(--ink-900)",
        color: "#fff", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 8 }}>
        {icon ? <Icon name={icon} size={16} /> : null}{children}{trailingIcon ? <Icon name={trailingIcon} size={16} /> : null}
      </button>
    );
  }
  function Ghost({ children, onClick, icon }) {
    return (
      <button onClick={onClick} style={{ height: 44, padding: "0 18px", borderRadius: 10, border: "1px solid var(--border-strong)",
        background: "var(--paper)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, color: "var(--text-body)",
        display: "inline-flex", alignItems: "center", gap: 7 }}>
        {icon ? <Icon name={icon} size={16} /> : null}{children}
      </button>
    );
  }
  // Staggered section: each block fades up in order (delay in ms).
  function Reveal({ delay, children }) {
    return <div className="lt-fade-up" style={{ animationDelay: (delay || 0) + "ms" }}>{children}</div>;
  }
  function Chip({ children, accent }) {
    return (
      <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "5px 11px", borderRadius: 999,
        border: "1px solid " + (accent ? "var(--accent-200,var(--accent-100))" : "var(--border-subtle)"),
        background: accent ? "var(--accent-50,#ecfdf5)" : "var(--ink-50)", fontSize: 12.5, fontWeight: 600,
        color: accent ? "var(--accent-600,var(--accent-500))" : "var(--text-body)", whiteSpace: "nowrap", maxWidth: 260,
        overflow: "hidden", textOverflow: "ellipsis" }}>
        {accent && <span style={{ width: 5, height: 5, borderRadius: 999, background: "var(--accent-500)", flex: "none" }} />}
        {children}
      </span>
    );
  }
  function SectionLabel({ icon, children }) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
        <span style={{ width: 26, height: 26, flex: "none", borderRadius: 7, display: "grid", placeItems: "center", background: "var(--ink-900)", color: "#fff" }}>
          <Icon name={icon} size={13.5} />
        </span>
        <span style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-faint)" }}>{children}</span>
      </div>
    );
  }
  const card = { background: "var(--paper)", border: "1px solid var(--border-subtle)", borderRadius: "var(--r-xl)", boxShadow: "var(--shadow-sm)", padding: "26px 28px" };

  // ------------------------------------------------------------ scan stage ----
  // Real progress: pages crawled / planned from the live scan row. The status
  // line advances with actual progress — never a fake percentage.
  function ScanStage({ domain, scan }) {
    const total = scan && scan.pages_total > 0 ? scan.pages_total : 0;
    const done = (scan && scan.pages_crawled) || 0;
    const frac = total > 0 ? Math.min(1, done / total) : 0;
    const statusKey = !scan || scan.status === "pending" ? "deepdive.scan.connecting"
      : frac < 0.25 ? "deepdive.scan.reading"
      : frac < 0.55 ? "deepdive.scan.offerings"
      : frac < 0.85 ? "deepdive.scan.keywords"
      : "deepdive.scan.finishing";
    return (
      <div style={{ ...card, padding: "48px 32px", textAlign: "center" }}>
        <div style={{ position: "relative", width: 72, height: 72, margin: "0 auto 22px" }}>
          <span style={{ position: "absolute", left: "50%", top: "50%", width: 72, height: 72, borderRadius: 20, transform: "translate(-50%,-50%)",
            border: "1px solid var(--border-subtle)", animation: "lt-pulse-ring 2.6s var(--ease-out) infinite" }} />
          <span style={{ position: "absolute", inset: 0, borderRadius: 20, display: "grid", placeItems: "center", background: "var(--ink-900)", color: "#fff" }}>
            <Icon name="radar" size={30} />
          </span>
        </div>
        <div className="lt-pill-label" style={{ margin: "0 auto 14px" }}>{t("deepdive.pill")}</div>
        <h2 style={{ fontFamily: "var(--font-display)", fontSize: 24, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-strong)" }}>
          {t("deepdive.scan.title")}
        </h2>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--text-muted)", marginTop: 6 }}>{domain}</div>

        <div style={{ maxWidth: 380, margin: "26px auto 0" }}>
          <div style={{ height: 6, borderRadius: 999, background: "var(--ink-100)", overflow: "hidden" }}>
            {total > 0
              ? <div style={{ height: "100%", width: Math.max(6, Math.round(frac * 100)) + "%", borderRadius: 999, background: "var(--ink-900)", transition: "width 0.9s var(--ease-out)" }} />
              : <div className="fx-syncbar" style={{ height: "100%", width: "42%", borderRadius: 999, background: "linear-gradient(90deg, transparent, var(--accent-500), transparent)" }} />}
          </div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 10 }}>
            <span key={statusKey} className="lt-fade-up" style={{ fontSize: 12.5, color: "var(--text-muted)" }}>{t(statusKey)}</span>
            {total > 0 && (
              <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 600, color: "var(--text-strong)" }}>
                {done}/{total} {t("deepdive.scan.pages")}
              </span>
            )}
          </div>
        </div>
      </div>
    );
  }

  // ---------------------------------------------------------- reveal stage ----
  function StatTile({ icon, label, value, delay }) {
    return (
      <Reveal delay={delay}>
        <div style={{ border: "1px solid var(--border-subtle)", borderRadius: 14, padding: "18px 20px", background: "var(--paper)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 8 }}>
            <Icon name={icon} size={14} style={{ color: "var(--text-faint)" }} />
            <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.07em", textTransform: "uppercase", color: "var(--text-faint)" }}>{label}</span>
          </div>
          {(() => {
            const Odometer = window.LTQ.Odometer;
            const numStyle = { fontFamily: "var(--font-mono)", fontSize: 26, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-strong)" };
            return Odometer
              ? <Odometer value={Number(value) || 0} className="lt-num" style={numStyle} />
              : <div className="lt-num" style={numStyle}>{value}</div>;
          })()}
        </div>
      </Reveal>
    );
  }

  function KeywordRow({ k, max, delay }) {
    const w = Math.max(4, Math.round((k.score / (max || 100)) * 100));
    const reduced = typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const [grown, setGrown] = React.useState(reduced);
    React.useEffect(() => {
      if (reduced) return;
      const id = setTimeout(() => setGrown(true), (delay || 0) + 100);
      return () => clearTimeout(id);
    }, []);
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "7px 0" }}>
        <span style={{ flex: "0 0 44%", minWidth: 0, fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{k.keyword}</span>
        <span style={{ flex: 1, height: 5, borderRadius: 999, background: "var(--ink-100)", overflow: "hidden" }}>
          {/* GPU-friendly fill: scaleX from the left, spring (no width animation) */}
          <span style={{ display: "block", height: "100%", width: w + "%", borderRadius: 999, background: "var(--ink-900)",
            transformOrigin: "left", transform: grown ? "scaleX(1)" : "scaleX(0)", transition: reduced ? "none" : "transform 0.85s var(--ease-spring)" }} />
        </span>
        <span className="lt-num" style={{ flex: "none", width: 34, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 600, color: "var(--text-muted)" }}>{k.score}</span>
      </div>
    );
  }

  function RevealStage({ data, onResearch, onFinish }) {
    const p = data.profile || {};
    const identity = p.identity || {};
    const name = (identity.name && identity.name.value) || p.domain || "";
    const tagline = identity.tagline && identity.tagline.value;
    const keywords = (p.keywords || []).slice(0, 8);
    const maxScore = keywords[0] ? keywords[0].score : 100;
    const offerings = p.offerings || {};
    const sellChips = []
      .concat((offerings.products || []).map((x) => x.name))
      .concat((offerings.categories || []).map((x) => x.value))
      .concat((offerings.services || []).map((x) => x.value))
      .slice(0, 10);
    const offeringsCount = (offerings.products || []).length + (offerings.categories || []).length + (offerings.services || []).length;
    const seeds = (p.seedTopics || []).slice(0, 5);
    const langs = (p.locale && p.locale.languages) || [];
    const platform = p.tech && p.tech.platform && p.tech.platform.value;

    let d = 0; // reveal choreography: each block 110ms after the previous
    const next = () => (d += 110);

    // First-win reward moment — the profile is in, the site was read. Plays once.
    const Celebrate = window.LTQ.Celebrate;
    const [celebrating, setCelebrating] = React.useState(true);

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {Celebrate && celebrating && (
          <div style={{ position: "fixed", inset: 0, zIndex: 90, display: "grid", placeItems: "center", pointerEvents: "none" }}>
            <Celebrate size={78} onDone={() => setCelebrating(false)} />
          </div>
        )}
        {/* hero */}
        <Reveal delay={0}>
          <div style={{ textAlign: "center", padding: "10px 0 8px" }}>
            <div className="lt-pill-label" style={{ margin: "0 auto 14px" }}>{t("deepdive.pill")}</div>
            <h1 style={{ fontFamily: "var(--font-display)", fontSize: "clamp(1.7rem, 1.3rem + 1.6vw, 2.3rem)", fontWeight: 700, letterSpacing: "-0.03em", lineHeight: 1.12, color: "var(--text-strong)" }}>
              {t("deepdive.hero.title", { name })}
            </h1>
            <p style={{ fontSize: 14, color: "var(--text-muted)", marginTop: 8, maxWidth: 480, marginLeft: "auto", marginRight: "auto", lineHeight: 1.55 }}>
              {t("deepdive.hero.sub")}
            </p>
            <div style={{ display: "flex", justifyContent: "center", flexWrap: "wrap", gap: 8, marginTop: 14 }}>
              <Chip>{t("deepdive.type." + (p.siteType || "other"))}</Chip>
              {platform && <Chip>{platform}</Chip>}
              {langs.slice(0, 4).map((l) => <Chip key={l}>{l.toUpperCase()}</Chip>)}
            </div>
          </div>
        </Reveal>

        {/* stat row */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(140px,1fr))", gap: 12 }}>
          <StatTile delay={next()} icon="file-search" label={t("deepdive.stats.pages")} value={data.pages_crawled} />
          <StatTile delay={next()} icon="key-round" label={t("deepdive.stats.keywords")} value={(p.keywords || []).length} />
          <StatTile delay={next()} icon="package" label={t("deepdive.stats.offerings")} value={offeringsCount} />
          <StatTile delay={next()} icon="languages" label={t("deepdive.stats.languages")} value={Math.max(1, langs.length)} />
        </div>

        {/* who you are */}
        {tagline && (
          <Reveal delay={next()}>
            <div style={card}>
              <SectionLabel icon="fingerprint">{t("deepdive.identity.label")}</SectionLabel>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 600, letterSpacing: "-0.01em", lineHeight: 1.5, color: "var(--text-strong)" }}>
                “{tagline}”
              </div>
              <div style={{ fontSize: 12, color: "var(--text-faint)", marginTop: 8 }}>{t("deepdive.identity.source")}</div>
            </div>
          </Reveal>
        )}

        {/* what you sell */}
        {sellChips.length > 0 && (
          <Reveal delay={next()}>
            <div style={card}>
              <SectionLabel icon="package">{t("deepdive.sell.label")}</SectionLabel>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {sellChips.map((x) => <Chip key={x}>{x}</Chip>)}
                {offeringsCount > sellChips.length && <span style={{ fontSize: 12.5, color: "var(--text-faint)", alignSelf: "center" }}>+{offeringsCount - sellChips.length}</span>}
              </div>
            </div>
          </Reveal>
        )}

        {/* keywords your pages target */}
        {keywords.length > 0 && (
          <Reveal delay={next()}>
            <div style={card}>
              <SectionLabel icon="key-round">{t("deepdive.keywords.label")}</SectionLabel>
              <div>
                {keywords.map((k, i) => <KeywordRow key={k.keyword} k={k} max={maxScore} delay={i * 60} />)}
              </div>
              <div style={{ fontSize: 12, color: "var(--text-faint)", marginTop: 10 }}>{t("deepdive.keywords.note")}</div>
            </div>
          </Reveal>
        )}

        {/* where to strike first */}
        <Reveal delay={next()}>
          <div style={{ ...card, background: "var(--ink-900)", border: "none" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
              <span style={{ width: 26, height: 26, flex: "none", borderRadius: 7, display: "grid", placeItems: "center", background: "rgba(255,255,255,0.1)", color: "#fff" }}>
                <Icon name="crosshair" size={13.5} />
              </span>
              <span style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: "rgba(255,255,255,0.55)" }}>{t("deepdive.seeds.label")}</span>
            </div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 600, letterSpacing: "-0.01em", color: "#fff", marginBottom: 14, lineHeight: 1.45 }}>
              {t("deepdive.seeds.title")}
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 20 }}>
              {(seeds.length ? seeds : [name]).map((s) => (
                <span key={s} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "6px 13px", borderRadius: 999,
                  border: "1px solid rgba(255,255,255,0.16)", background: "rgba(255,255,255,0.06)", fontSize: 13, fontWeight: 600, color: "#fff" }}>
                  <span style={{ width: 5, height: 5, borderRadius: 999, background: "var(--accent-500)", flex: "none" }} />{s}
                </span>
              ))}
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
              <button onClick={() => onResearch(seeds[0] || name)} className="lt-btn-3d-light" style={{ height: 44, padding: "0 20px", borderRadius: 10, border: "none",
                background: "#fff", color: "var(--ink-900)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 700,
                display: "inline-flex", alignItems: "center", gap: 8 }}>
                <Icon name="sparkles" size={16} />{t("deepdive.cta.research")}
              </button>
              <button onClick={onFinish} style={{ height: 44, padding: "0 18px", borderRadius: 10, border: "1px solid rgba(255,255,255,0.4)",
                background: "rgba(255,255,255,0.12)", color: "#fff", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600,
                display: "inline-flex", alignItems: "center", gap: 7 }}>
                {t("deepdive.cta.dashboard")}<Icon name="arrow-right" size={16} />
              </button>
            </div>
          </div>
        </Reveal>
      </div>
    );
  }

  // ------------------------------------------------------------ fallback ------
  function FallbackStage({ onFinish }) {
    return (
      <div style={{ ...card, padding: "40px 32px", textAlign: "center" }}>
        <span style={{ width: 52, height: 52, margin: "0 auto 16px", borderRadius: 14, display: "grid", placeItems: "center", background: "var(--ink-50)", color: "var(--text-muted)" }}>
          <Icon name="hourglass" size={24} />
        </span>
        <h2 style={{ fontFamily: "var(--font-display)", fontSize: 20, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-strong)" }}>{t("deepdive.fallback.title")}</h2>
        <p style={{ fontSize: 13.5, color: "var(--text-muted)", marginTop: 8, maxWidth: 400, marginLeft: "auto", marginRight: "auto", lineHeight: 1.55 }}>{t("deepdive.fallback.sub")}</p>
        <div style={{ marginTop: 20, display: "flex", justifyContent: "center" }}>
          <Primary onClick={onFinish} trailingIcon="arrow-right">{t("deepdive.cta.dashboard")}</Primary>
        </div>
      </div>
    );
  }

  // ------------------------------------------------------------- container ----
  function DeepDive({ siteUrl, onFinish, onResearch }) {
    const [phase, setPhase] = React.useState("scan"); // scan | reveal | fallback
    const [scan, setScan] = React.useState(null);
    const [data, setData] = React.useState(null);
    const startRef = React.useRef(Date.now());
    let domain = siteUrl || "";
    try { domain = new URL(/^https?:/i.test(siteUrl) ? siteUrl : "https://" + siteUrl).hostname.replace(/^www\./, ""); } catch (e) {}

    React.useEffect(() => {
      let live = true, timer = null;
      const showProfile = async () => {
        const r = await api.get("/api/site-intel/profile");
        if (live && r.ok && r.data && r.data.profile) { setData(r.data); setPhase("reveal"); return true; }
        return false;
      };
      const tick = async () => {
        const r = await api.get("/api/site-intel/scan");
        if (!live) return;
        const s = r.ok ? r.data.scan : null;
        if (s) setScan(s);
        const active = s && (s.status === "pending" || s.status === "running");
        if (!active) {
          if (await showProfile()) return; // done (or an older profile exists)
          if (!live) return;
          if (!s || s.status === "failed") { setPhase("fallback"); return; }
        }
        if (Date.now() - startRef.current > MAX_WAIT_MS) {
          if (!(await showProfile()) && live) setPhase("fallback");
          return;
        }
        timer = setTimeout(tick, POLL_MS);
      };
      tick();
      return () => { live = false; if (timer) clearTimeout(timer); };
    }, []);

    return (
      <div style={{ maxWidth: 720, margin: "0 auto", paddingBottom: 24 }}>
        <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 10 }}>
          <button onClick={onFinish} style={{ height: 32, padding: "0 12px", borderRadius: 8, border: "1px solid var(--border-subtle)",
            background: "var(--paper)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600, color: "var(--text-faint)" }}>
            {t("deepdive.skip")}
          </button>
        </div>
        {phase === "scan" && <ScanStage domain={domain} scan={scan} />}
        {phase === "reveal" && data && <RevealStage data={data} onResearch={onResearch} onFinish={onFinish} />}
        {phase === "fallback" && <FallbackStage onFinish={onFinish} />}
      </div>
    );
  }

  window.LTQ.DeepDive = DeepDive;
})();
