// ============================================================
// ZERANDA — Guided product tour (coachmark engine)
// Mounts into #tour-root and layers over the live dashboard.
// It drives the real app by clicking real nav items ([data-nav])
// and spotlights real DOM elements, so users learn the actual
// product. Auto-starts after sign-in; replayable any time.
// (useState/useEffect/useRef/useLayoutEffect are global via ui.jsx)
// ============================================================

const TOUR_STEPS = [
  {
    id: 'welcome', center: true, glyph: 'sparkles',
    title: 'Welcome to Zeranda',
    body: 'I turn what lands in your inbox into organised dashboards so nothing slips. Here’s a quick look at how it all works.',
    primary: 'Show me around', dismiss: 'Skip for now',
  },
  {
    id: 'briefing', nav: 'overview', target: '.briefing-hero',
    eyebrow: 'Your home base',
    title: 'Start your day here',
    body: 'Every morning I sum up what actually needs you — replies waiting, money due, what’s arriving — in plain language. No digging through email.',
  },
  {
    id: 'sync', target: '.sync',
    eyebrow: 'Private by design',
    title: 'Your inbox stays yours',
    body: 'Your email itself stays in your inbox — Zeranda keeps only the useful details, like an amount or a due date. It’s automatic, start to finish.',
  },
  {
    id: 'mail', nav: 'mail', target: '.coverage',
    eyebrow: 'Inbox, done for you',
    title: 'Skip the inbox',
    body: 'New mail arrives, and the bills, deliveries and to-dos inside it line up here automatically — leaving you just the few that genuinely need you, so you never open Gmail to stay on top of it.',
  },
  {
    id: 'chat', nav: 'chat', target: '[data-nav="chat"]',
    eyebrow: 'Just ask',
    title: 'Chat with your assistant',
    body: 'Ask anything — “what’s due this week?”, “where’s my package?”, “move my 3 PM.” I answer from everything I’ve organised for you.',
  },
  {
    id: 'bills', nav: 'bills', target: '[data-nav="bills"]',
    eyebrow: 'Nothing overdue',
    title: 'Bills, tracked for you',
    body: 'I spot every bill in your inbox, log the amount and the due date, and remind you in good time — so nothing’s ever late.',
  },
  {
    id: 'banking', nav: 'banking', target: '[data-nav="banking"]',
    eyebrow: 'The money view',
    title: 'Accounts in one place',
    body: 'Balances and recent spending pulled together, so you always know where you stand without opening five apps.',
  },
  {
    id: 'people', nav: 'people', target: '[data-nav="people"]',
    eyebrow: 'Who you deal with',
    title: 'People, in context',
    body: 'Everyone you email is gathered here with the threads, bills, and deliveries tied to them — so you always have the full picture of who you’re dealing with.',
  },
  {
    id: 'packages', nav: 'packages', target: '[data-nav="packages"]',
    eyebrow: 'On its way',
    title: 'Track every delivery',
    body: 'From order confirmation to doorstep, I follow your packages — no more hunting through email for tracking links.',
  },
  {
    id: 'calendar', nav: 'calendar', target: '[data-nav="calendar"]',
    eyebrow: 'Never double-booked',
    title: 'Your schedule, filled in',
    body: 'Events and bookings from your email land on your calendar automatically, with any conflicts flagged for you.',
  },
  {
    id: 'tasks', nav: 'tasks', target: '[data-nav="tasks"]',
    eyebrow: 'First things first',
    title: 'What needs doing',
    body: 'I turn “please reply”, “confirm”, and “renew soon” into a simple list, ordered by what’s most urgent right now.',
  },
  {
    id: 'subs', nav: 'subs', target: '[data-nav="subs"]',
    eyebrow: 'No surprise charges',
    title: 'Subscriptions in check',
    body: 'See what’s renewing and what it costs — and catch the ones you forgot you were still paying for.',
  },
  {
    id: 'notifications', nav: 'notifications', target: '[data-nav="notifications"]',
    eyebrow: 'Quiet by default',
    title: 'I nudge, gently',
    body: 'You’ll only hear from me when something genuinely needs you. Everything else stays handled in the background.',
  },
  {
    id: 'bug', target: '[data-nav="bug"]',
    eyebrow: 'We’re listening',
    title: 'Spot something off? Tell us',
    body: 'Hit Report a Bug any time to flag anything that looks wrong — add what happened and how urgent it is, and it goes straight to our team.',
  },
  {
    id: 'finish', center: true, glyph: 'check', done: true,
    title: 'You’re all set',
    body: 'That’s the tour. From here, everything from your inbox stays organised — calmly, in the background. Welcome aboard.',
    primary: 'Start using Zeranda',
  },
];

const TIP_W = 344;

function placeTip(rect, tipH) {
  const gap = 14, m = 16, vw = window.innerWidth, vh = window.innerHeight;
  let left, top;
  if (rect.left + rect.width + gap + TIP_W <= vw - m) {        // right
    left = rect.left + rect.width + gap; top = rect.top;
  } else if (rect.left - gap - TIP_W >= m) {                   // left
    left = rect.left - gap - TIP_W; top = rect.top;
  } else if (rect.top + rect.height + gap + tipH <= vh - m) {  // below
    top = rect.top + rect.height + gap; left = rect.left;
  } else {                                                     // above
    top = rect.top - gap - tipH; left = rect.left;
  }
  left = Math.max(m, Math.min(left, vw - m - TIP_W));
  top = Math.max(m, Math.min(top, vh - m - tipH));
  return { top, left };
}

function Tour() {
  const [phase, setPhase] = useState('idle');   // idle | running | done
  const [idx, setIdx] = useState(0);
  const [rect, setRect] = useState(null);        // padded target rect (or null)
  const [pos, setPos] = useState({ top: 0, left: 0 });
  const tipRef = useRef(null);
  const startedRef = useRef(false);
  const readyRef = useRef(false);    // have we told the parent the tour is ready?

  const step = TOUR_STEPS[idx];
  const total = TOUR_STEPS.length;

  // --- auto-start when the dashboard appears after sign-in -------
  useEffect(() => {
    const check = () => {
      const root = document.getElementById('root');
      if (!root) return;
      const onApp = !!root.querySelector('.app');
      const onLogin = !!root.querySelector('.login');
      if (onLogin) { startedRef.current = false; }     // reset for next login
      if (onApp && !onLogin) {
        // Tell the Next host the tour has painted, so its welcome cover can lift.
        if (!readyRef.current) {
          readyRef.current = true;
          try { window.parent.postMessage({ __tour: 'ready' }, '*'); } catch (e) { }
        }
        if (!startedRef.current) {
          startedRef.current = true;
          setTimeout(() => { setIdx(0); setPhase('running'); }, 280);
        }
      }
    };
    check();
    const mo = new MutationObserver(check);
    mo.observe(document.getElementById('root') || document.body, { childList: true, subtree: true });
    return () => mo.disconnect();
  }, []);

  // --- measure the current step's target -------------------------
  const measure = React.useCallback(() => {
    const s = TOUR_STEPS[idx];
    if (!s || s.center) { setRect(null); return; }
    const el = document.querySelector(s.target);
    if (!el) { setRect(null); return; }
    const r = el.getBoundingClientRect();
    const p = 8;
    setRect({
      top: r.top - p, left: r.left - p,
      width: r.width + 2 * p, height: r.height + 2 * p,
      rr: getComputedStyle(el).borderRadius,
    });
  }, [idx]);

  // --- advance to a step: navigate the app, then measure ---------
  useEffect(() => {
    if (phase !== 'running') return;
    const s = TOUR_STEPS[idx];
    let t;
    if (s.nav) {
      const navBtn = document.querySelector(`[data-nav="${s.nav}"]`);
      if (navBtn) navBtn.click();
      t = setTimeout(measure, 240);
    } else {
      t = setTimeout(measure, 60);
    }
    return () => clearTimeout(t);
  }, [phase, idx, measure]);

  // --- keep things aligned on resize / scroll --------------------
  useEffect(() => {
    if (phase !== 'running') return;
    const on = () => measure();
    window.addEventListener('resize', on);
    window.addEventListener('scroll', on, true);
    return () => { window.removeEventListener('resize', on); window.removeEventListener('scroll', on, true); };
  }, [phase, measure]);

  // --- position the tooltip relative to the (measured) target ----
  React.useLayoutEffect(() => {
    if (phase !== 'running' || !rect || !tipRef.current) return;
    const h = tipRef.current.offsetHeight || 200;
    setPos(placeTip(rect, h));
  }, [rect, phase, idx]);

  // --- keyboard nav ---------------------------------------------
  useEffect(() => {
    if (phase !== 'running') return;
    const onKey = (e) => {
      if (e.key === 'Escape') endTour();
      else if (e.key === 'ArrowRight' || e.key === 'Enter') next();
      else if (e.key === 'ArrowLeft') back();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [phase, idx]);

  function next() { if (idx < total - 1) setIdx(idx + 1); else endTour(); }
  function back() { if (idx > 0) setIdx(idx - 1); }
  // Ending the tour — finish, skip, or Escape — hands control back to the Next host.
  // The host owns what comes next: the real "reading your mail" scan (WorkspaceSetup)
  // for new users, or a route to Settings on replay. We just notify it and render
  // nothing — there is no mock scan screen or replay pill inside the iframe anymore.
  function endTour() {
    try { window.parent.postMessage({ __tour: 'finish' }, '*'); } catch (e) { }
    setRect(null);
    setPhase('done');
  }

  // Only the running phase draws anything; idle (pre-start) and done (post-finish)
  // are transparent so the host's overlays show through.
  if (phase !== 'running') return null;

  // running
  const isCenter = step.center || !rect;
  const pct = Math.round(((idx + 1) / total) * 100);

  return (
    <React.Fragment>
      <div className="tour-blocker" onClick={(e) => e.stopPropagation()} />
      {isCenter
        ? <div className="tour-veil" />
        : <div className="tour-spot" style={{
          top: rect.top, left: rect.left, width: rect.width,
          height: rect.height, borderRadius: rect.rr || '14px',
        }} />}

      {isCenter ? (
        <div className="tour-tip center" ref={tipRef}>
          {step.glyph && (
            <span className={`glyph ${step.done ? 'done' : ''}`}>
              <Icon name={step.glyph} size={28} color="#fff" />
            </span>
          )}
          <h3>{step.title}</h3>
          <p>{step.body}</p>
          {step.id === 'welcome' ? (
            <div className="tour-actions">
              <button className="tour-btn ghost" onClick={endTour}>{step.dismiss}</button>
              <button className="tour-btn primary" onClick={next}>{step.primary}</button>
            </div>
          ) : (
            <div className="tour-actions">
              <button className="tour-btn primary" onClick={endTour}>
                {step.primary} <Icon name="arrow-right" size={15} color="#fff" />
              </button>
            </div>
          )}
        </div>
      ) : (
        <div className="tour-tip" ref={tipRef} style={{ top: pos.top, left: pos.left }}>
          {step.eyebrow && (
            <div className="eyebrow"><Icon name="sparkle" size={12} color="var(--gold-600)" />{step.eyebrow}</div>
          )}
          <h3>{step.title}</h3>
          <p>{step.body}</p>
          <div className="tour-meta">
            <div className="tour-track"><div className="tour-fill" style={{ width: pct + '%' }} /></div>
            <span className="tour-count">{idx + 1} / {total}</span>
          </div>
          <div className="tour-actions">
            <button className="tour-skip" onClick={endTour}>Skip tour</button>
            <span className="grow" />
            {idx > 0 && <button className="tour-btn ghost" onClick={back}>Back</button>}
            <button className="tour-btn primary" onClick={next}>
              Next <Icon name="arrow-right" size={15} color="#fff" />
            </button>
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

(function mountTour() {
  function boot() {
    let host = document.getElementById('tour-root');
    if (!host) { host = document.createElement('div'); host.id = 'tour-root'; document.body.appendChild(host); }
    ReactDOM.createRoot(host).render(<Tour />);
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);
  else boot();
})();
