// tutorial.jsx — first-run interactive coach-mark tour for PsyFit.
// Spotlights real controls one at a time and asks the user to tap through.
// Lives as a top-level fixed overlay so it lines up with the (scaled) phone
// using raw getBoundingClientRect viewport coordinates.

// Each step either highlights a control ([data-tour=...]) or is a centered
// card (welcome / finish). `round` → circular spotlight, else rounded rect.
const TOUR_STEPS = [
  {
    id: 'welcome', center: true,
    eyebrow: 'Quick tour',
    title: 'Welcome to PsyFit',
    body: 'A 30-second walkthrough of the essentials. Tap each highlighted button to move along — you can leave anytime.',
    cta: 'Show me around',
  },
  {
    id: 'home', target: 'nav-home', place: 'top',
    eyebrow: 'Home',
    title: 'Your daily base',
    body: "Today's workout, your streak and quick stats live here. It's the screen you'll open most.",
    tap: 'Tap Home to continue',
  },
  {
    id: 'plan', target: 'nav-plan', place: 'top',
    eyebrow: 'Plans',
    title: 'Programs & workouts',
    body: 'Your training plans live here — switch between multi-week Programs and single Daily Workouts up top, then build or edit them from a library of 800+ exercises.',
    tap: 'Tap Plans to continue',
  },
  {
    id: 'log', target: 'nav-log', place: 'top', round: true,
    eyebrow: 'Log',
    title: 'Start training',
    body: 'The big button jumps straight into logging. Tick off sets, rest with the built-in timer, then finish to bank the session.',
    tap: 'Tap the bolt to continue',
  },
  {
    id: 'calendar', target: 'nav-calendar', place: 'top',
    eyebrow: 'Calendar',
    title: 'Plan your week',
    body: 'Schedule workouts onto days, mark rest days, and look back on everything you’ve logged.',
    tap: 'Tap Calendar to continue',
  },
  {
    id: 'progress', target: 'nav-progress', place: 'top',
    eyebrow: 'Progress',
    title: 'See your progress',
    body: 'Volume, personal records and trends — every finished workout updates them instantly.',
    tap: 'Tap Progress to continue',
  },
  {
    id: 'profile', target: 'nav-profile', place: 'bottom', round: true,
    eyebrow: 'Profile',
    title: 'You & your settings',
    body: 'Your photo, units, weekly goal, backups — and a button to replay this tour — all live in here.',
    tap: 'Tap your avatar to continue',
  },
  {
    id: 'done', center: true,
    eyebrow: "You're set",
    title: 'Go get after it',
    body: 'That’s the tour. Replay it anytime from Profile → Settings → Replay tutorial.',
    cta: 'Start training',
  },
];

function Tutorial({ open, go, onClose }) {
  const c = useTheme();
  const [i, setI] = React.useState(0);
  const [rect, setRect] = React.useState(null);
  const [shake, setShake] = React.useState(0);
  const step = TOUR_STEPS[i];
  const last = i === TOUR_STEPS.length - 1;

  // Reset to the start and land on Home (where every anchor is visible)
  // each time the tour opens.
  React.useEffect(() => {
    if (!open) return;
    setI(0);
    try { go('home'); } catch (e) {}
  }, [open]);

  // Measure the current target. Re-measure across the screen-enter animation
  // and on resize so the spotlight tracks the control precisely.
  React.useLayoutEffect(() => {
    if (!open) return;
    let raf, cancelled = false;
    const measure = () => {
      if (cancelled) return;
      const s = TOUR_STEPS[i];
      if (!s || s.center || !s.target) { setRect(null); return; }
      const el = document.querySelector('[data-tour="' + s.target + '"]');
      if (!el) { setRect(null); return; }
      const r = el.getBoundingClientRect();
      setRect({ top: r.top, left: r.left, width: r.width, height: r.height });
    };
    measure();
    // settle passes (entrance animation runs ~320ms)
    const timers = [80, 200, 360, 520].map(d => setTimeout(measure, d));
    const onWin = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(measure); };
    window.addEventListener('resize', onWin);
    return () => {
      cancelled = true;
      timers.forEach(clearTimeout);
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', onWin);
    };
  }, [i, open]);

  if (!open) return null;

  const advance = () => {
    haptic('light');
    if (last) { onClose(true); return; }
    setI(n => Math.min(TOUR_STEPS.length - 1, n + 1));
  };
  const skip = () => { haptic('light'); onClose(true); };
  const nudge = () => { haptic('warn'); setShake(s => s + 1); };

  const PAD = step.round ? 8 : 10;
  const spot = rect && {
    top: rect.top - PAD, left: rect.left - PAD,
    width: rect.width + PAD * 2, height: rect.height + PAD * 2,
    radius: step.round ? 999 : 14,
  };

  // ── Tooltip placement ──────────────────────────────────────
  const CARD_W = Math.min(312, (typeof window !== 'undefined' ? window.innerWidth : 360) - 28);
  let cardStyle = {};
  if (step.center || !spot) {
    cardStyle = { top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: CARD_W };
  } else {
    const cx = spot.left + spot.width / 2;
    let left = cx - CARD_W / 2;
    left = Math.max(14, Math.min(left, window.innerWidth - CARD_W - 14));
    if (step.place === 'bottom') {
      cardStyle = { top: spot.top + spot.height + 16, left, width: CARD_W };
    } else {
      cardStyle = { bottom: window.innerHeight - spot.top + 16, left, width: CARD_W };
    }
  }
  const caretX = spot ? Math.max(18, Math.min(spot.left + spot.width / 2 - (cardStyle.left || 0), CARD_W - 18)) : 0;

  // ── Scrim: four dim panels around the spotlight (leaving a real hole) ──
  const dim = 'rgba(7,8,10,0.74)';
  const panel = (s) => <div key={JSON.stringify(s)} onClick={nudge}
    style={{ position: 'fixed', background: dim, backdropFilter: 'blur(1.5px)', WebkitBackdropFilter: 'blur(1.5px)', ...s }} />;

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 9000, ...cssVars(c), fontFamily: 'var(--font-body)' }}>
      {spot ? (
        <>
          {panel({ top: 0, left: 0, right: 0, height: Math.max(0, spot.top) })}
          {panel({ top: spot.top + spot.height, left: 0, right: 0, bottom: 0 })}
          {panel({ top: spot.top, left: 0, width: Math.max(0, spot.left), height: spot.height })}
          {panel({ top: spot.top, left: spot.left + spot.width, right: 0, height: spot.height })}
          {/* glow ring */}
          <div style={{ position: 'fixed', top: spot.top, left: spot.left, width: spot.width, height: spot.height,
            borderRadius: spot.radius, border: '2.5px solid ' + c.accent, boxShadow: '0 0 0 4px ' + c.accent + '44, 0 0 26px 2px ' + c.accent + '66',
            pointerEvents: 'none', animation: 'psytourpulse 1.6s ease-in-out infinite' }} />
          {/* invisible tap-catcher: advances without firing the real control */}
          <button onClick={advance} aria-label="Continue" style={{ position: 'fixed', top: spot.top, left: spot.left,
            width: spot.width, height: spot.height, borderRadius: spot.radius, background: 'transparent', border: 'none', cursor: 'pointer' }} />
        </>
      ) : (
        <div onClick={step.center ? undefined : nudge} style={{ position: 'fixed', inset: 0, background: dim, backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)' }} />
      )}

      {/* Tooltip / card */}
      <div key={i + '-' + shake} style={{ position: 'fixed', ...cardStyle,
        background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--radius)',
        padding: 18, boxShadow: '0 22px 60px -18px rgba(0,0,0,0.7)', zIndex: 1, opacity: 1,
        animation: shake ? 'psytourshake .4s' : 'none' }}>
        {/* caret toward target */}
        {spot && !step.center && (
          <div style={{ position: 'absolute', left: caretX - 7,
            ...(step.place === 'bottom' ? { top: -7 } : { bottom: -7 }),
            width: 14, height: 14, background: 'var(--surface)',
            borderLeft: '1px solid var(--border)', borderTop: '1px solid var(--border)',
            transform: step.place === 'bottom' ? 'rotate(45deg)' : 'rotate(225deg)' }} />
        )}

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 9 }}>
          <Eyebrow style={{ color: c.accent }}>{step.eyebrow}</Eyebrow>
          <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--dim)', letterSpacing: 0.4, whiteSpace: 'nowrap' }}>{i + 1} / {TOUR_STEPS.length}</span>
        </div>

        <Display size={25} style={{ marginBottom: 10, lineHeight: 1.04 }}>{step.title}</Display>
        <div style={{ fontSize: 13.5, lineHeight: 1.5, color: 'var(--muted)' }}>{step.body}</div>

        {/* progress dots */}
        <div style={{ display: 'flex', gap: 5, margin: '15px 0 14px' }}>
          {TOUR_STEPS.map((_, k) => (
            <span key={k} style={{ height: 4, flex: k === i ? 2.2 : 1, borderRadius: 999,
              background: k === i ? c.accent : (k < i ? c.accent + '66' : 'var(--surface-3)'), transition: 'all .2s' }} />
          ))}
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <button onClick={skip} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '6px 2px',
            fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13.5, color: 'var(--dim)' }}>
            {last ? '' : 'Skip tour'}
          </button>
          <div style={{ flex: 1 }} />
          {step.tap && (
            <span style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--dim)', marginRight: 2, textAlign: 'right', maxWidth: 120, lineHeight: 1.25 }}>{step.tap}</span>
          )}
          <button onClick={advance} style={{ display: 'inline-flex', alignItems: 'center', gap: 6,
            fontFamily: 'var(--font-display)', fontSize: 15, letterSpacing: 0.5, textTransform: 'uppercase',
            background: c.accent, color: c.accentInk, border: 'none', borderRadius: 'var(--radius-sm)',
            padding: '10px 16px', cursor: 'pointer', boxShadow: '0 6px 18px -8px ' + c.accent }}>
            {step.cta || (last ? 'Done' : 'Next')}
            {!step.center && !last && <Icon name="chevR" size={15} />}
          </button>
        </div>
      </div>
    </div>
  );
}

// Inject keyframes once.
(function () {
  if (typeof document === 'undefined' || document.getElementById('psytour-kf')) return;
  const s = document.createElement('style');
  s.id = 'psytour-kf';
  s.textContent = '@keyframes psytourpulse{0%,100%{opacity:1}50%{opacity:.5}}' +
    '@keyframes psytourin{from{opacity:0}to{opacity:1}}' +
    '@keyframes psytourshake{0%,100%{transform:translateX(0)}20%,60%{transform:translateX(-6px)}40%,80%{transform:translateX(6px)}}';
  document.head.appendChild(s);
})();

Object.assign(window, { Tutorial, TOUR_STEPS });
