// SQSEO ScanThinking — the onboarding "we're reading your site" moment
// (onboarding revamp Phase 9, docs/plans/ONBOARDING-REVAMP-PLAN.md).
//
// Shown right after the user submits their website URL. While the Site
// Intelligence crawler works, a pure-CSS-3D wireframe globe spins under a
// sweeping emerald scanline and small evidence cards assemble in orbit as the
// scan advances through its REAL phases (robots -> sitemap -> crawl ->
// profile). Polls GET /api/onboarding/autofill and hands the suggestions to
// the wizard the moment they're ready; a hard max-wait means the user is
// never trapped (we proceed with whatever we have).
//
// House rules: every number is real (live pages_crawled / pages_total from
// the scan row); near-monochrome with emerald only as lines/dots; the whole
// scene is decorative (aria-hidden) with an aria-live status line carrying
// the accessible narrative; everything freezes under prefers-reduced-motion.
// Registered as window.LTQ.ScanThinking.
(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 = 1500;
  const MAX_WAIT_MS = 15_000; // proceed with partial/empty autofill after this
  const MIN_SHOW_MS = 2600;   // let the moment land even on instant profiles

  // The scan's real phases, in order, mapped to the three orbiting cards.
  const PHASE_ORDER = ["robots", "sitemap", "crawl", "profile"];
  const phaseRank = (phase) => {
    const i = PHASE_ORDER.indexOf(phase);
    return i === -1 ? 0 : i;
  };

  const CSS = `
  .lt-scn-stage{position:relative;display:grid;place-items:center;min-height:340px;padding:30px 0 10px;perspective:900px;}
  .lt-scn-orbwrap{position:relative;width:230px;height:230px;}
  /* ---- the wireframe globe: nested hairline rings on 3D axes ---- */
  .lt-scn-orb{position:absolute;inset:0;transform-style:preserve-3d;animation:lt-scn-spin 16s linear infinite;}
  .lt-scn-ring{position:absolute;inset:0;border-radius:999px;border:1.4px solid var(--ink-200);}
  .lt-scn-ring.m1{transform:rotateY(60deg);}
  .lt-scn-ring.m2{transform:rotateY(120deg);}
  .lt-scn-ring.p1{transform:rotateX(75deg) scale(0.92);border-color:var(--ink-100);}
  .lt-scn-ring.p2{transform:rotateX(75deg) scale(0.62);border-color:var(--ink-100);}
  .lt-scn-ring.eq{transform:rotateX(75deg);border:1.6px solid var(--accent-500);opacity:0.85;
    box-shadow:0 0 18px rgba(14,138,95,0.18), inset 0 0 18px rgba(14,138,95,0.12);}
  /* counter-rotating inner cage for depth */
  .lt-scn-orb-inner{position:absolute;inset:26px;transform-style:preserve-3d;animation:lt-scn-spin-r 11s linear infinite;}
  .lt-scn-orb-inner .lt-scn-ring{border-color:var(--ink-100);}
  /* the core: a calm emerald pulse */
  .lt-scn-core{position:absolute;top:50%;left:50%;width:10px;height:10px;margin:-5px 0 0 -5px;border-radius:999px;
    background:var(--accent-500);animation:lt-scn-pulse 2.2s ease-in-out infinite;}
  /* ---- the scanline sweeping the globe ---- */
  .lt-scn-sweep{position:absolute;inset:-8px;overflow:hidden;border-radius:999px;pointer-events:none;}
  .lt-scn-sweep i{position:absolute;top:0;bottom:0;width:34%;
    background:linear-gradient(90deg,transparent, rgba(14,138,95,0.13) 45%, rgba(14,138,95,0.30) 50%, rgba(14,138,95,0.13) 55%, transparent);
    animation:lt-scn-sweep 2.8s cubic-bezier(0.45,0,0.55,1) infinite;}
  @keyframes lt-scn-sweep{0%{left:-40%;}55%,100%{left:106%;}}
  @keyframes lt-scn-spin{from{transform:rotateX(-12deg) rotateY(0);}to{transform:rotateX(-12deg) rotateY(360deg);}}
  @keyframes lt-scn-spin-r{from{transform:rotateX(18deg) rotateY(360deg);}to{transform:rotateX(18deg) rotateY(0);}}
  @keyframes lt-scn-pulse{0%,100%{box-shadow:0 0 0 0 rgba(14,138,95,0.30);}50%{box-shadow:0 0 0 12px rgba(14,138,95,0);}}
  /* ---- evidence cards assembling in orbit ---- */
  .lt-scn-card{position:absolute;width:104px;padding:9px 10px;border-radius:11px;background:var(--paper);
    border:1px solid var(--border-subtle);box-shadow:var(--shadow-md);opacity:0;transform:translateY(10px) scale(0.92);}
  .lt-scn-card.on{animation:lt-scn-card-in .55s cubic-bezier(0.34,1.4,0.5,1) both;}
  @keyframes lt-scn-card-in{from{opacity:0;transform:translateY(10px) scale(0.92);}to{opacity:1;transform:none;}}
  .lt-scn-card .k{display:flex;align-items:center;gap:5px;font-size:10px;font-weight:700;letter-spacing:0.04em;
    text-transform:uppercase;color:var(--text-faint);margin-bottom:6px;}
  .lt-scn-card .b{height:6px;border-radius:4px;background:var(--ink-100);margin-top:4px;}
  .lt-scn-card .b.live{background:linear-gradient(90deg,var(--ink-100) 25%,var(--ink-50) 50%,var(--ink-100) 75%);
    background-size:200% 100%;animation:lt-scn-shimmer 1.6s linear infinite;}
  @keyframes lt-scn-shimmer{from{background-position:200% 0;}to{background-position:-200% 0;}}
  .lt-scn-c1{top:6px;left:-96px;}
  .lt-scn-c2{top:84px;right:-104px;}
  .lt-scn-c3{bottom:-4px;left:-72px;}
  /* ---- progress ---- */
  .lt-scn-bar{width:min(320px,80%);height:4px;border-radius:99px;background:var(--ink-100);overflow:hidden;margin:22px auto 0;}
  .lt-scn-bar i{display:block;height:100%;border-radius:99px;background:var(--accent-500);
    transition:width .6s var(--ease-out);}
  .lt-scn-bar i.indet{width:38% !important;animation:lt-scn-indet 1.5s ease-in-out infinite;}
  @keyframes lt-scn-indet{0%{margin-left:-38%;}100%{margin-left:100%;}}
  @media (prefers-reduced-motion: reduce){
    .lt-scn-orb,.lt-scn-orb-inner,.lt-scn-sweep i,.lt-scn-core,.lt-scn-card.on,.lt-scn-bar i.indet,.lt-scn-card .b.live{animation:none !important;}
    .lt-scn-card.on{opacity:1;transform:none;}
  }
  @media (max-width: 640px){
    .lt-scn-c1{left:-64px;} .lt-scn-c2{right:-70px;} .lt-scn-c3{left:-48px;}
    .lt-scn-card{width:92px;}
  }
  `;

  function EvidenceCard({ cls, on, icon, label, lines }) {
    return (
      <div className={`lt-scn-card ${cls}${on ? " on" : ""}`}>
        <div className="k"><Icon name={icon} size={11} /> {label}</div>
        {Array.from({ length: lines }).map((_, i) => (
          <div key={i} className={`b${on ? "" : " live"}`} style={{ width: `${88 - i * 24}%` }} />
        ))}
      </div>
    );
  }

  function ScanThinking({ onDone }) {
    const [scan, setScan] = React.useState(null);
    const doneRef = React.useRef(false);
    const startRef = React.useRef(Date.now());

    React.useEffect(() => {
      let alive = true;
      const finish = (suggestions) => {
        if (doneRef.current) return;
        doneRef.current = true;
        // Let the entrance settle so the moment never strobes.
        const wait = Math.max(0, MIN_SHOW_MS - (Date.now() - startRef.current));
        setTimeout(() => { if (alive) onDone(suggestions); }, wait);
      };
      const poll = async () => {
        if (!alive || doneRef.current) return;
        const r = await api.get("/api/onboarding/autofill");
        if (!alive || doneRef.current) return;
        if (r.ok) {
          if (r.data.scan) setScan(r.data.scan);
          if (r.data.ready) return finish(r.data.suggestions || null);
        }
        if (Date.now() - startRef.current >= MAX_WAIT_MS) return finish(null); // never trap
        setTimeout(poll, POLL_MS);
      };
      poll();
      return () => { alive = false; };
    }, []);

    const rank = scan ? phaseRank(scan.phase) : 0;
    const pages = scan ? scan.pages_crawled : 0;
    const total = scan ? scan.pages_total : 0;
    const pct = total > 0 ? Math.min(96, Math.round((pages / total) * 100)) : 0;

    return (
      <div style={{ textAlign: "center" }}>
        <style>{CSS}</style>

        {/* SQ does the scanning — search pose (magnifier sweep) with a little
            speech balloon. The status line below narrates for AT users. */}
        <div aria-hidden="true" style={{ display: "flex", justifyContent: "center", alignItems: "flex-end", minHeight: 250, paddingTop: 26 }}>
          {window.LTQ.SQ
            ? <window.LTQ.SQ state="search" width={172} say={t("scanthink.sq_say")} saySide="top" interactive bubble={false} />
            : <div className="lt-scn-stage"><div className="lt-scn-orbwrap"><div className="lt-scn-orb"><span className="lt-scn-ring" /><span className="lt-scn-ring m1" /><span className="lt-scn-ring m2" /></div><span className="lt-scn-core" /></div></div>}
        </div>

        <h2 style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-strong)", marginTop: 6 }}>
          {t("scanthink.title")}
        </h2>
        <p style={{ fontSize: 13.5, color: "var(--text-muted)", marginTop: 6, lineHeight: 1.55 }}>
          {t("scanthink.sub")}
        </p>

        {/* The real numbers, narrated politely for screen readers. */}
        <div aria-live="polite" style={{ marginTop: 10, minHeight: 20, fontSize: 12.5, color: "var(--text-faint)", fontFamily: "var(--font-mono)" }}>
          {pages > 0 ? t("scanthink.pages_read", { n: pages }) : t("scanthink.starting")}
        </div>

        <div className="lt-scn-bar" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={total > 0 ? pct : undefined}>
          <i className={total > 0 ? "" : "indet"} style={{ width: total > 0 ? pct + "%" : undefined }} />
        </div>
      </div>
    );
  }

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