/* MitaOS · Spotlight guided tour.
   A coach-mark system that walks a first-time viewer through the whole
   lifecycle across screens. Launch from the topbar ("Guided tour") or
   the first-run prompt. Each step navigates to a screen, spotlights the
   key element, and explains the userflow in plain language. */

const TOUR_STEPS = [
  { route: 'command', sel: '.mt-northstar', title: 'Start with the North Star',
    body: 'Every view answers a question. The cockpit opens with the one that matters: attributed paid conversions — installs + subscriptions the engine can trace to a specific asset, creator and account.' },
  { route: 'command', sel: '.mt-tree', title: 'Follow the funnel',
    body: 'The production-to-conversion chain: creators → QA-passed assets → posts → views → installs → subscriptions. Every number traces back to its source.' },
  { route: 'command', sel: '.mt-queues', title: 'The engine runs on queues',
    body: 'Agents do the volume; humans hold judgment. These are the only things needing a person right now — click any tile to jump straight to that queue.' },
  { route: 'command', sel: '.mt-switch', title: 'One operator, many products',
    body: "Switch between Mike's own apps and the Phase-2 prospect roster. Every screen re-scopes to the product you pick." },
  { route: 'discovery', sel: '.ad-dt__row', title: 'Acquire · sourced & scored creators',
    body: 'Module A ranks candidates across platforms by niche fit, audience, style and predicted performance. Expand any row to see exactly why it scored that way, then push to outreach.' },
  { route: 'outreach', sel: '.ad-card', title: 'Acquire · outreach that qualifies itself',
    body: 'Module B sends from approved templates, classifies replies, and routes only edge cases to a human. New creators clear a US$150 / 10-video trial gate before joining the roster.' },
  { route: 'briefs', sel: '.ad-card', title: 'Produce · generate a winning brief',
    body: 'Module C turns a product + hook + format into a full brief — concept, shot list, script and checklist — seeded by what the Learning Loop already knows converts.' },
  { route: 'qa', sel: '.ad-card', title: 'Produce · QA before anything ships',
    body: 'Module D checks every asset for technical, brand and brief compliance. Fails return to the creator with notes; only borderline or sensitive items reach a human.' },
  { route: 'publishing', sel: '.mt-section .mt-grid', title: 'Distribute · post at volume, safely',
    body: 'Module E schedules across many accounts, adapts per platform, and watches account health — auto-throttling and re-routing when an account is rate-limited.' },
  { route: 'performance', sel: '.ad-chart-frame', title: 'Measure · what actually drove growth',
    body: 'Module F stitches platform + app metrics and attributes outcomes — best-effort, and honest about it — to the asset, creator, account and hook behind every conversion.' },
  { route: 'learning', sel: '.ad-card', title: 'Learn · the compounding moat',
    body: 'Module G turns each campaign into explainable recommendations that feed back into Discovery, Briefing and Publishing. This is what makes every campaign smarter than the last.' },
  { route: 'guide', sel: '[data-tour="guide-nav"]', title: 'Not sure about a metric?',
    body: 'The Guide explains every metric — the formula, why it matters, when to use it, and the benchmark numbers that define success. Look for the “?” help-tips throughout the app too.' },
];

const findEl = (sel, tries = 40) => new Promise((resolve) => {
  let n = 0;
  const tick = () => {
    const el = document.querySelector(sel);
    if (el) return resolve(el);
    if (n++ > tries) return resolve(null);
    setTimeout(tick, 25);        // setTimeout (not rAF) so it fires even unfocused
  };
  tick();
});

const Tour = () => {
  const [idx, setIdx] = React.useState(-1);          // -1 = inactive
  const [rect, setRect] = React.useState(null);
  const active = idx >= 0;
  const step = active ? TOUR_STEPS[idx] : null;

  // expose launcher globally
  React.useEffect(() => { window.__mitaStartTour = () => setIdx(0); return () => { delete window.__mitaStartTour; }; }, []);

  // drive each step: navigate → find target → measure
  React.useEffect(() => {
    if (!active) return;
    let cancelled = false;
    const run = async () => {
      if (window.location.hash.replace('#/', '') !== step.route) window.location.hash = '#/' + step.route;
      await new Promise((r) => setTimeout(r, 360));
      const el = await findEl(step.sel);
      if (cancelled) return;
      if (el) {
        el.scrollIntoView({ block: 'center', behavior: 'auto' });
        await new Promise((r) => setTimeout(r, 180));
        if (!cancelled) measure(el);
      } else { setRect(null); }
    };
    const measure = (el) => {
      const r = el.getBoundingClientRect();
      setRect({ top: r.top, left: r.left, width: r.width, height: r.height });
    };
    run();
    const onScroll = () => { const el = document.querySelector(step.sel); if (el) measure(el); };
    window.addEventListener('scroll', onScroll, true);
    window.addEventListener('resize', onScroll);
    return () => { cancelled = true; window.removeEventListener('scroll', onScroll, true); window.removeEventListener('resize', onScroll); };
  }, [idx]);

  React.useEffect(() => {
    if (!active) return;
    const onKey = (e) => {
      if (e.key === 'Escape') setIdx(-1);
      else if (e.key === 'ArrowRight') next();
      else if (e.key === 'ArrowLeft') setIdx((i) => Math.max(0, i - 1));
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [idx]);

  const next = () => setIdx((i) => (i >= TOUR_STEPS.length - 1 ? -1 : i + 1));
  const close = () => setIdx(-1);
  if (!active) return null;

  const pad = 8;
  const spot = rect ? { top: rect.top - pad, left: rect.left - pad, width: rect.width + pad * 2, height: rect.height + pad * 2 } : null;

  // tooltip placement: below the spot if room, else above; clamp horizontally
  const vh = window.innerHeight, vw = window.innerWidth, tipW = 360;
  let tipTop, tipLeft, arrow = 'up';
  if (spot) {
    const below = spot.top + spot.height + 14;
    if (below + 220 < vh) { tipTop = below; arrow = 'up'; }
    else { tipTop = Math.max(14, spot.top - 14 - 200); arrow = 'down'; }
    tipLeft = Math.min(Math.max(14, spot.left + spot.width / 2 - tipW / 2), vw - tipW - 14);
  } else { tipTop = vh / 2 - 120; tipLeft = vw / 2 - tipW / 2; }

  return (
    <div className="mt-tour" role="dialog" aria-label="Product tour">
      {/* backdrop with spotlight cut-out via big box-shadow */}
      {spot ? (
        <div className="mt-tour__spot" style={{ top: spot.top, left: spot.left, width: spot.width, height: spot.height }} onClick={close} />
      ) : (
        <div className="mt-tour__scrim" onClick={close} />
      )}
      <div className={`mt-tour__pop mt-tour__pop--${arrow}`} style={{ top: tipTop, left: tipLeft, width: tipW }}>
        <div className="mt-tour__meta">
          <span className="mt-tour__badge">{step.route === 'command' ? 'Command' : step.route}</span>
          <span className="mt-tour__count mono">{idx + 1} / {TOUR_STEPS.length}</span>
        </div>
        <h3 className="mt-tour__title">{step.title}</h3>
        <p className="mt-tour__body">{step.body}</p>
        <div className="mt-tour__bar"><span className="mt-tour__bar-fill" style={{ width: ((idx + 1) / TOUR_STEPS.length * 100) + '%' }} /></div>
        <div className="mt-tour__ctas">
          <button className="mt-tour__skip" onClick={close}>Skip tour</button>
          <div className="mt-cluster" style={{ gap: 8 }}>
            {idx > 0 && <button className="ad-btn ad-btn--secondary ad-btn--sm" onClick={() => setIdx(idx - 1)}><span className="ad-btn__label">Back</span></button>}
            <button className="ad-btn ad-btn--primary ad-btn--sm" onClick={next}><span className="ad-btn__label">{idx >= TOUR_STEPS.length - 1 ? 'Finish' : 'Next'}</span></button>
          </div>
        </div>
      </div>
    </div>
  );
};

/* First-run nudge — a small card offering the tour once. */
const TourNudge = () => {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    let seen = false; try { seen = localStorage.getItem('mita_tour_seen') === '1'; } catch (e) {}
    if (!seen) { const t = setTimeout(() => setShow(true), 900); return () => clearTimeout(t); }
  }, []);
  // never let the nudge cover another screen — dismiss as soon as they navigate
  React.useEffect(() => {
    const onNav = () => { setShow(false); try { localStorage.setItem('mita_tour_seen', '1'); } catch (e) {} };
    window.addEventListener('hashchange', onNav);
    return () => window.removeEventListener('hashchange', onNav);
  }, []);
  const dismiss = () => { setShow(false); try { localStorage.setItem('mita_tour_seen', '1'); } catch (e) {} };
  const startTour = () => { dismiss(); window.__mitaStartTour && window.__mitaStartTour(); };
  if (!show) return null;
  return (
    <div className="mt-nudge mt-fade">
      <div className="mt-nudge__icon">{I.bolt}</div>
      <div style={{ flex: 1 }}>
        <p className="mt-nudge__title">New here? Take the 90-second tour</p>
        <p className="mt-nudge__body">See the whole growth engine — discover → brief → QA → publish → learn — in one guided walkthrough.</p>
        <div className="mt-cluster" style={{ gap: 8, marginTop: 10 }}>
          <button className="ad-btn ad-btn--primary ad-btn--sm" onClick={startTour}><span className="ad-btn__label">Start tour</span></button>
          <button className="ad-btn ad-btn--ghost ad-btn--sm" onClick={dismiss}><span className="ad-btn__label">Maybe later</span></button>
        </div>
      </div>
      <button className="mt-nudge__x" aria-label="Dismiss" onClick={dismiss}>{I.x}</button>
    </div>
  );
};

Object.assign(window, { Tour, TourNudge });
