// WTS Cyprus — Onboarding: homepage banner + guided product tour
const { useState: useStateO, useEffect: useEffectO, useRef: useRefO } = React;

// ── Banner shown at the top of the homepage ───────────────────────────────
const OnboardingBanner = ({ onStart, onDismiss }) => (
  <div className="wts-onboard-banner">
    <div className="wts-onboard-banner__icon"><Icon name="compass" size={20} /></div>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div className="wts-onboard-banner__title">New here? Take the guided tour</div>
      <div className="wts-onboard-banner__sub">A 60-second walkthrough — how to get around the menu, then the four core workflows: creating a PBC engagement, reviewing client submissions, opening a Transfer Pricing study, and recording an analyst verdict.</div>
    </div>
    <div className="wts-onboard-banner__actions">
      <Button onClick={onStart}><Icon name="play" size={14} /> Start tour</Button>
      {onDismiss && <button type="button" className="wts-link" style={{ fontSize: 13, color: 'var(--muted-foreground)' }} onClick={onDismiss}>Not now</button>}
    </div>
  </div>
);

// ── DOM helpers the tour uses ─────────────────────────────────────────────
const _isMobile = () => window.matchMedia('(max-width: 900px)').matches;
const _ensureMenuOpen = () => {
  if (!_isMobile()) return;
  const sb = document.querySelector('.wts-sidebar');
  if (sb && !sb.classList.contains('wts-sidebar--open')) {
    const h = document.querySelector('.wts-hamburger');
    if (h) h.click();
  }
};
const _clickRowContaining = (tableSel, text) => {
  const row = [...document.querySelectorAll(`${tableSel} tbody tr`)].find(r => r.textContent.includes(text));
  if (row) row.click();
};
const _clickFirstCandidate = () => {
  const row = [...document.querySelectorAll('.wts-candidates-table tbody tr')].find(r => !r.querySelector('.wts-skel-line'));
  if (row) row.click();
};

// Build the step list — a couple of extra menu steps up front (and, on mobile,
// a step showing how to open the menu) before the four workflow walkthroughs.
const buildTourSteps = (mobile) => {
  const steps = [
    { title: 'Welcome to WTS Operations',
      body: 'This quick tour shows you how to get around, then walks through the four core workflows. Use Next / Back to move through it, or skip any time.',
      route: { name: 'home' } },
  ];
  if (mobile) {
    steps.push({ title: 'Open the menu',
      body: 'On a phone, the navigation is tucked away. Tap the menu button in the top-left of the header to open the sidebar — we’ll open it for you on the next steps.',
      route: { name: 'home' }, selector: '.wts-hamburger', navDelay: 220 });
  }
  steps.push(
    { title: 'The dashboard',
      body: '“Overview” is your home base — KPIs, recent activity across both modules, and what needs your attention.',
      route: { name: 'home' }, action: _ensureMenuOpen, selector: '.wts-sidebar__nav .wts-sidebar__section:nth-child(1)', navDelay: 220 },
    { title: 'The PBC module',
      body: 'Provided-By-Client document collection lives here — your Engagements, and the cross-engagement Review inbox of everything awaiting your review.',
      route: { name: 'home' }, action: _ensureMenuOpen, selector: '.wts-sidebar__nav .wts-sidebar__section:nth-child(2)', navDelay: 220 },
    { title: 'The Transfer Pricing module',
      body: 'AI-assisted comparable-company studies live under Transfer Pricing → Studies.',
      route: { name: 'home' }, action: _ensureMenuOpen, selector: '.wts-sidebar__nav .wts-sidebar__section:nth-child(3)', navDelay: 220 },
    { title: 'Create a new PBC engagement',
      body: 'An engagement is one client × service line × period. “New engagement” lets you pick a client from the registry, choose one of five templates, set a deadline, and ship a structured request list to the client portal.',
      route: { name: 'pbc-engagements' }, selector: '.ck-page__header .ck-btn--default', navDelay: 440 },
    { title: 'View an engagement, submissions & comments',
      body: 'Open any request item to see its submission history, the latest file or value, and the comment thread with the client. Submitted items can be Accepted or returned with “Request change”.',
      route: { name: 'engagement-detail', id: 'e1' }, action: () => _clickRowContaining('.wts-asks-table', 'Signed FY2024'), selector: '.wts-drawer--open', navDelay: 500 },
    { title: 'Open an existing Transfer Pricing study',
      body: 'Each study lists candidate companies with an AI-generated business description and rule-based criteria flags (Independence, Activity, Geography, Size). Click any row to open a company.',
      route: { name: 'tp-study-detail', id: 's2' }, selector: '.wts-candidates-table tbody tr', navDelay: 480 },
    { title: 'Change an analyst verdict on a company',
      body: 'Open a candidate to read the description and evidence, tick the criteria flags that drove your call, then set Accept or Reject with a required reason. Every change is kept in the candidate’s decision history.',
      route: { name: 'tp-study-detail', id: 's2' }, action: () => _clickFirstCandidate(), selector: '.wts-drawer--open .wts-panel__footer', navDelay: 460, cardTop: true },
    { title: 'You’re all set',
      body: 'That’s the core loop. You can re-run this tour any time from the banner on the overview page.',
      route: { name: 'home' } },
  );
  return steps;
};

// ── The guided tour overlay ───────────────────────────────────────────────
const OnboardingTour = ({ open, onNavigate, onClose }) => {
  const [steps, setSteps] = useStateO([]);
  const [idx, setIdx] = useStateO(0);
  const [rect, setRect] = useStateO(null);
  const idxRef = useRefO(0);
  const stepsRef = useRefO([]);
  const lastRouteRef = useRefO(null);
  idxRef.current = idx;
  stepsRef.current = steps;

  const routeKey = (r) => (r ? `${r.name}:${r.id ?? ''}` : null);

  const measure = (selector) => {
    if (!selector) { setRect(null); return; }
    const el = document.querySelector(selector);
    if (!el) { setRect(null); return; }
    const r = el.getBoundingClientRect();
    setRect({ top: r.top, left: r.left, width: r.width, height: r.height });
  };

  // Build steps + reset whenever the tour opens
  useEffectO(() => { if (open) { setSteps(buildTourSteps(_isMobile())); setIdx(0); lastRouteRef.current = null; } }, [open]);

  // Run the current step: navigate, optionally act, then spotlight the target
  useEffectO(() => {
    if (!open || !steps.length) return;
    let cancelled = false;
    const step = steps[idx];
    setRect(null);
    // Only navigate when the route actually changes — re-navigating to the same
    // route closes the mobile drawer, which would make the menu flicker
    // open/closed across the dashboard → PBC → Transfer Pricing menu steps.
    const rk = routeKey(step.route);
    if (step.route && rk !== lastRouteRef.current) {
      onNavigate(step.route);
      lastRouteRef.current = rk;
    }
    const t1 = setTimeout(() => {
      if (cancelled) return;
      if (step.action) { try { step.action(); } catch (e) {} }
      setTimeout(() => { if (!cancelled) measure(step.selector); }, step.action ? 380 : 80);
    }, step.navDelay ?? 380);
    return () => { cancelled = true; clearTimeout(t1); };
  }, [open, idx, steps]);

  // Keep the spotlight aligned on resize / scroll
  useEffectO(() => {
    if (!open) return;
    const h = () => { const s = stepsRef.current[idxRef.current]; if (s) measure(s.selector); };
    window.addEventListener('resize', h);
    window.addEventListener('scroll', h, true);
    return () => { window.removeEventListener('resize', h); window.removeEventListener('scroll', h, true); };
  }, [open]);

  if (!open || !steps.length) return null;
  const step = steps[idx];
  const isLast = idx === steps.length - 1;
  const finish = () => { onClose(); onNavigate({ name: 'home' }); };

  return (
    <>
      <div style={{ position: 'fixed', inset: 0, zIndex: 1999 }} />
      {rect ? (
        <div style={{
          position: 'fixed', top: rect.top - 6, left: rect.left - 6, width: rect.width + 12, height: rect.height + 12,
          borderRadius: 10, boxShadow: '0 0 0 9999px rgba(15,23,42,0.55)', border: '2px solid hsl(213 80% 62%)',
          zIndex: 2000, pointerEvents: 'none',
        }} />
      ) : (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', zIndex: 2000, pointerEvents: 'none' }} />
      )}
      <div className={cn('wts-tour-card', step.cardTop && 'wts-tour-card--top')}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
          <span className="wts-tour-card__step">Step {idx + 1} of {steps.length}</span>
          <button type="button" className="wts-icon-btn" onClick={finish} aria-label="Close tour"><Icon name="x" size={15} /></button>
        </div>
        <div className="wts-tour-card__title">{step.title}</div>
        <div className="wts-tour-card__body">{step.body}</div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 16, gap: 10 }}>
          <div className="wts-tour-dots">
            {steps.map((_, i) => <span key={i} className={cn('wts-tour-dot', i === idx && 'wts-tour-dot--on')} />)}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {idx > 0 && <Button variant="outline" size="sm" onClick={() => setIdx(i => i - 1)}>Back</Button>}
            {!isLast
              ? <Button size="sm" onClick={() => setIdx(i => i + 1)}>Next</Button>
              : <Button size="sm" onClick={finish}><Icon name="check" size={13} /> Finish</Button>}
          </div>
        </div>
        {!isLast && (
          <button type="button" className="wts-link" style={{ fontSize: 12, color: 'var(--muted-foreground)', marginTop: 10 }} onClick={finish}>Skip tour</button>
        )}
      </div>
    </>
  );
};

Object.assign(window, { OnboardingBanner, OnboardingTour });
