/* SKOPIA Tour — animated product walkthrough, inline on main page */

const TOUR_CHAPTERS = [
  {
    id: 'upload', src: 'assets/demo-01-upload.png',
    eyebrow: '01 · INGEST',
    title: 'Drop in any schedule. Get answers in seconds.',
    caption: 'Native support for P6 XER, Microsoft Project MPP, and MSP XML. No installs, no migrations — drag a file in your browser and the analysis is running.',
    chips: ['XER', 'MPP', 'MSP XML', '0 setup'],
    spots: [
      { x: 33.5, y: 56, w: 18, h: 18, kind: 'ring', label: 'Current schedule', side: 'left' },
      { x: 60.5, y: 56, w: 18, h: 18, kind: 'ring', label: 'Baseline', side: 'right' },
    ],
    duration: 6500,
  },
  {
    id: 'gantt', src: 'assets/demo-02-gantt-critical.png',
    eyebrow: '02 · GANTT',
    title: 'Trace the critical path. End to end.',
    caption: 'Filter to the critical path, scrub the timeline, and follow finish-to-start logic across thousands of activities. Baseline overlay on every bar.',
    chips: ['Critical filter', 'Baseline overlay', 'Logic ties', 'Total float'],
    spots: [
      { x: 8, y: 14, w: 14, h: 9, kind: 'pill', label: 'Critical only', side: 'right' },
      { x: 76, y: 38, w: 22, h: 56, kind: 'frame', label: 'Critical path', side: 'left' },
    ],
    duration: 6500,
  },
  {
    id: 'wbs', src: 'assets/demo-03-wbs-grouping.png',
    eyebrow: '03 · STRUCTURE',
    title: 'Group by WBS. Open any branch.',
    caption: 'Switch instantly between flat list, WBS hierarchy, and custom groupings. Every level rolls up dates, float, and progress.',
    chips: ['WBS tree', 'Roll-up dates', 'Custom groups'],
    spots: [
      { x: 21, y: 8, w: 9, h: 8, kind: 'pill', label: 'WBS view', side: 'right' },
      { x: 4, y: 22, w: 26, h: 30, kind: 'frame', label: 'Hierarchy', side: 'right' },
    ],
    duration: 6000,
  },
  {
    id: 'relationships', src: 'assets/demo-04-relationships.png',
    eyebrow: '04 · LOGIC',
    title: 'Inspect every predecessor and successor.',
    caption: 'Click any activity to see its inbound and outbound relationships, lag, and relationship type — no diving through nested screens.',
    chips: ['Predecessors', 'Successors', 'FS / SS / FF', 'Lag visibility'],
    spots: [
      { x: 4, y: 65, w: 30, h: 8, kind: 'pill', label: 'Selected activity', side: 'right' },
      { x: 1, y: 75, w: 98, h: 22, kind: 'frame', label: 'Relationships drawer', side: 'top' },
    ],
    duration: 6500,
  },
  {
    id: 'logic', src: 'assets/demo-05-logic-modal.png',
    eyebrow: '05 · DCMA HEALTH',
    title: 'Find broken logic. Fix it before the client does.',
    caption: 'Every DCMA check expands into the exact activities that failed, with severity and a recommended remediation path.',
    chips: ['DCMA #1–14', 'Flagged activities', 'Severity', 'Remediation'],
    spots: [
      { x: 14, y: 22, w: 72, h: 50, kind: 'frame', label: 'Logic completeness drill-in', side: 'bottom' },
    ],
    duration: 6500,
  },
  {
    id: 'thresholds', src: 'assets/demo-06-check-settings.png',
    eyebrow: '06 · TUNING',
    title: 'Calibrate every threshold to your contract.',
    caption: 'Tighten or loosen any check to match your client\u2019s spec. The grade and score recalculate the moment you nudge the slider.',
    chips: ['Per-check thresholds', 'Live recalc', 'Save as preset'],
    spots: [
      { x: 26, y: 6, w: 35, h: 50, kind: 'frame', label: 'Check settings', side: 'bottom' },
      { x: 32, y: 32, w: 25, h: 8, kind: 'pill', label: 'Live threshold', side: 'right' },
    ],
    duration: 6500,
  },
  {
    id: 'health', src: 'assets/demo-07-health-dashboard.png',
    eyebrow: '07 · OVERVIEW',
    title: 'Schedule health, at a glance.',
    caption: 'One dashboard shows your overall grade, all 14 DCMA checks, and a radar profile of where your schedule is strongest — and weakest.',
    chips: ['Grade A–F', '14 checks', 'Radar profile'],
    spots: [
      { x: 8, y: 16, w: 17, h: 30, kind: 'ring', label: 'Overall grade', side: 'right' },
      { x: 8, y: 47, w: 17, h: 32, kind: 'frame', label: 'Health profile', side: 'right' },
    ],
    duration: 6500,
  },
  {
    id: 'report', src: 'assets/demo-08-report-wizard.png',
    eyebrow: '08 · DELIVER',
    title: 'Client-ready report. One click.',
    caption: 'Pick the sections, the page size, and the brand. SKOPIA composes a polished PDF — cover, schedule, critical path, and analytics.',
    chips: ['Branded cover', 'A4 / A3 / Letter', 'Critical path trace', 'Analytics'],
    spots: [
      { x: 34, y: 5, w: 36, h: 90, kind: 'frame', label: 'Report wizard', side: 'left' },
    ],
    duration: 7000,
  },
];

const TourHotSpot = ({ spot, index }) => {
  const labelPos = (() => {
    const side = spot.side || 'right';
    const off = '110%';
    if (side === 'right') return { left: off, top: '50%', transform: 'translateY(-50%)' };
    if (side === 'left') return { right: off, top: '50%', transform: 'translateY(-50%)' };
    if (side === 'top') return { left: '50%', bottom: '105%', transform: 'translateX(-50%)' };
    return { left: '50%', top: '105%', transform: 'translateX(-50%)' };
  })();

  const baseStyle = {
    position: 'absolute',
    left: spot.x + '%', top: spot.y + '%',
    width: spot.w + '%', height: spot.h + '%',
    pointerEvents: 'none',
  };

  return (
    <>
      <div style={{
        ...baseStyle,
        border: '2px solid #1EC8D4',
        borderRadius: spot.kind === 'ring' ? '50%' : 6,
        boxShadow: '0 0 0 6px rgba(30,200,212,0.18), 0 0 30px rgba(30,200,212,0.45)',
        animation: 'hot-pulse 1.8s ease-in-out infinite',
        animationDelay: (index * 0.4) + 's',
        opacity: 0,
        animationName: 'hot-pulse, hot-fade-in',
        animationDuration: '1.8s, .55s',
        animationIterationCount: 'infinite, 1',
        animationFillMode: 'both, forwards',
      }} />
      <div style={{ ...baseStyle, border: 'none', boxShadow: 'none' }}>
        <div style={{
          position: 'absolute', ...labelPos,
          padding: '6px 11px',
          background: '#1E1E1E', color: '#fff',
          borderRadius: 4,
          fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 10,
          letterSpacing: 1.3, textTransform: 'uppercase', whiteSpace: 'nowrap',
          boxShadow: '0 8px 24px rgba(0,0,0,0.20)',
          opacity: 0, animation: 'hot-fade-in .7s ease .35s forwards',
        }}>
          {spot.label}
        </div>
      </div>
    </>
  );
};

const TourRail = ({ active, onPick }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
    {TOUR_CHAPTERS.map((c, i) => {
      const isActive = i === active;
      return (
        <button key={c.id} onClick={() => onPick(i)} style={{
          display: 'flex', alignItems: 'center', gap: 14,
          padding: '14px 16px', border: 'none',
          background: isActive ? 'rgba(74,111,232,0.08)' : 'transparent',
          borderLeft: `3px solid ${isActive ? '#4A6FE8' : 'transparent'}`,
          cursor: 'pointer', textAlign: 'left',
          transition: 'background .15s, border-color .15s',
        }}>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: isActive ? '#2A4DCC' : '#9AA0B0', width: 22 }}>
            {String(i + 1).padStart(2, '0')}
          </span>
          <span style={{ fontFamily: 'var(--font-head)', fontSize: 13, fontWeight: 700, color: isActive ? '#1A1A2E' : '#6B7280' }}>
            {c.eyebrow.split('·')[1]?.trim() || c.eyebrow}
          </span>
        </button>
      );
    })}
  </div>
);

const Tour = () => {
  const [idx, setIdx] = useState(0);
  const [playing, setPlaying] = useState(true);
  const [progress, setProgress] = useState(0);
  const [inView, setInView] = useState(false);
  const sectionRef = useRef(null);

  // Pause when off-screen so it doesn't compete with the hero
  useEffect(() => {
    const el = sectionRef.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => setInView(e.isIntersecting), { threshold: 0.25 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const chapter = TOUR_CHAPTERS[idx];
  const shouldPlay = playing && inView;

  useEffect(() => {
    if (!shouldPlay) return;
    const dur = chapter.duration;
    const start = performance.now() - progress * dur;
    let raf;
    const tick = (now) => {
      const p = Math.min(1, (now - start) / dur);
      setProgress(p);
      if (p >= 1) {
        setIdx((i) => (i + 1) % TOUR_CHAPTERS.length);
        setProgress(0);
      } else {
        raf = requestAnimationFrame(tick);
      }
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [idx, shouldPlay]); // eslint-disable-line

  const goTo = (i) => { setIdx(((i % TOUR_CHAPTERS.length) + TOUR_CHAPTERS.length) % TOUR_CHAPTERS.length); setProgress(0); };
  const next = () => goTo(idx + 1);
  const prev = () => goTo(idx - 1);

  const controlBtn = {
    width: 36, height: 36, borderRadius: '50%',
    border: '1px solid #E2E6F0', background: '#fff', cursor: 'pointer', color: '#1A1A2E',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  };

  return (
    <section ref={sectionRef} className="section-pad" id="tour" style={{ background: 'var(--color-bg-light)', position: 'relative' }}>
      <div className="container">
        <Reveal>
          <SectionHeader
            align="center"
            eyebrow="See it work"
            title={<>From raw XER / MSP XML to <span className="grad-text">client-ready PDF.</span></>}
            lede="An animated tour through SKOPIA Lens on a real schedule. Auto-plays — or click any chapter to jump."
          />
        </Reveal>

        <Reveal delay={120}>
          <div className="tour-grid" style={{
            marginTop: 56,
            display: 'grid', gridTemplateColumns: 'minmax(220px, 260px) 1fr',
            gap: 32, alignItems: 'stretch',
          }}>
            {/* Rail */}
            <aside className="tour-rail" style={{
              background: '#fff', border: '1px solid #E2E6F0', borderRadius: 4,
              boxShadow: '0 2px 12px rgba(0,0,0,0.04)',
              padding: '20px 0', height: 'fit-content',
              position: 'sticky', top: 100, alignSelf: 'flex-start',
            }}>
              <div style={{ padding: '0 22px 14px 19px' }}>
                <div style={{ fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 10, letterSpacing: 3, color: '#9AA0B0', textTransform: 'uppercase' }}>Chapters</div>
                <div style={{ fontFamily: 'var(--font-head)', fontWeight: 900, fontSize: 17, color: '#1A1A2E', marginTop: 4 }}>SKOPIA Lens · the tour</div>
              </div>
              <TourRail active={idx} onPick={goTo} />
            </aside>

            {/* Stage */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div key={'cap-' + idx} style={{ animation: 'fade-up .55s ease both' }}>
                <div className="eyebrow" style={{ marginBottom: 14 }}>{chapter.eyebrow}</div>
                <h3 style={{
                  fontFamily: 'var(--font-head)', fontWeight: 900,
                  fontSize: 'clamp(24px, 2.8vw, 34px)', lineHeight: 1.1, letterSpacing: -0.8,
                  color: '#1A1A2E', maxWidth: 820,
                }}>{chapter.title}</h3>
                <p style={{
                  fontFamily: 'var(--font-body)', fontSize: 15, lineHeight: 1.6,
                  color: '#6B7280', maxWidth: 720, marginTop: 10,
                }}>{chapter.caption}</p>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 14 }}>
                  {chapter.chips.map((c) => (
                    <span key={c} style={{
                      padding: '5px 11px', borderRadius: 999,
                      background: '#fff', border: '1px solid #E2E6F0',
                      fontFamily: 'var(--font-mono)', fontSize: 11, color: '#1A1A2E',
                    }}>{c}</span>
                  ))}
                </div>
              </div>

              <div style={{
                position: 'relative', background: '#fff',
                border: '1px solid #E2E6F0', borderRadius: 8, overflow: 'hidden',
                boxShadow: '0 30px 60px -28px rgba(42,77,204,0.30), 0 12px 30px rgba(0,0,0,0.06)',
              }}>
                <div style={{ height: 3, background: 'var(--color-grad)' }}></div>

                {/* Browser chrome */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '11px 14px', borderBottom: '1px solid #EFF1F7', background: '#FAFBFE' }}>
                  <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#FE5F57' }}></span>
                  <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#FEBB2D' }}></span>
                  <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#27C93F' }}></span>
                  <div style={{
                    flex: 1, marginLeft: 18, padding: '4px 12px', borderRadius: 999,
                    background: '#fff', border: '1px solid #E2E6F0',
                    fontFamily: 'var(--font-mono)', fontSize: 10, color: '#6B7280',
                    display: 'flex', alignItems: 'center', gap: 8,
                  }}>
                    <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--color-grad)' }}></span>
                    skopia.com.au / lens / residential-house-build &middot;{' '}
                    <span key={'hint-' + idx} style={{ color: '#2A4DCC', animation: 'fade-up .35s ease' }}>{chapter.id}</span>
                  </div>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: '#9AA0B0' }}>
                    {String(idx + 1).padStart(2, '0')} / {String(TOUR_CHAPTERS.length).padStart(2, '0')}
                  </span>
                </div>

                {/* Screenshot stack */}
                <div style={{ position: 'relative', width: '100%', aspectRatio: '1276 / 602', background: '#0c0d12' }}>
                  {TOUR_CHAPTERS.map((c, i) => (
                    <div key={c.id} style={{
                      position: 'absolute', inset: 0,
                      opacity: i === idx ? 1 : 0,
                      transition: 'opacity .55s ease',
                      pointerEvents: i === idx ? 'auto' : 'none',
                    }}>
                      <img
                        src={c.src}
                        alt={c.title}
                        loading={i === 0 ? 'eager' : 'lazy'}
                        style={{
                          display: 'block', width: '100%', height: '100%', objectFit: 'cover',
                          transform: i === idx ? 'scale(1.005)' : 'scale(1.02)',
                          transition: 'transform 7s ease-out',
                        }}
                      />
                      {i === idx && c.spots.map((s, j) => (
                        <TourHotSpot key={j} spot={s} index={j} />
                      ))}
                    </div>
                  ))}
                </div>

                {/* Controls */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 18px', borderTop: '1px solid #EFF1F7', background: '#fff' }}>
                  <button onClick={() => setPlaying((p) => !p)} aria-label={playing ? 'Pause' : 'Play'} style={{
                    width: 36, height: 36, borderRadius: '50%', border: 'none', cursor: 'pointer',
                    background: 'var(--color-grad)', color: '#fff',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    boxShadow: '0 6px 18px rgba(42,77,204,0.30)',
                  }}>
                    {playing ? (
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="5" width="4" height="14" rx="1" /><rect x="14" y="5" width="4" height="14" rx="1" /></svg>
                    ) : (
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M7 5l12 7-12 7V5z" /></svg>
                    )}
                  </button>
                  <button onClick={prev} aria-label="Previous" style={controlBtn}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 6l-6 6 6 6" /></svg>
                  </button>
                  <button onClick={next} aria-label="Next" style={controlBtn}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 6l6 6-6 6" /></svg>
                  </button>

                  <div style={{ flex: 1, display: 'flex', gap: 4, marginLeft: 6 }}>
                    {TOUR_CHAPTERS.map((_, i) => {
                      const fill = i < idx ? 1 : i === idx ? progress : 0;
                      return (
                        <button key={i} onClick={() => goTo(i)} style={{
                          flex: 1, height: 4, padding: 0, border: 'none',
                          background: '#EFF1F7', borderRadius: 999, position: 'relative',
                          cursor: 'pointer', overflow: 'hidden',
                        }}>
                          <span style={{
                            position: 'absolute', inset: 0,
                            width: (fill * 100) + '%',
                            background: 'var(--color-grad)',
                            transition: i === idx ? 'none' : 'width .2s ease',
                          }}></span>
                        </button>
                      );
                    })}
                  </div>

                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: '#6B7280' }}>
                    {String(idx + 1).padStart(2, '0')} / {String(TOUR_CHAPTERS.length).padStart(2, '0')}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </Reveal>
      </div>

      <style>{`
        @keyframes hot-pulse {
          0%, 100% { box-shadow: 0 0 0 6px rgba(30,200,212,0.18), 0 0 30px rgba(30,200,212,0.45); }
          50%      { box-shadow: 0 0 0 10px rgba(30,200,212,0.06), 0 0 50px rgba(30,200,212,0.55); }
        }
        @keyframes hot-fade-in {
          from { opacity: 0; transform: scale(0.96); }
          to   { opacity: 1; transform: scale(1); }
        }
        @keyframes fade-up {
          from { opacity: 0; transform: translateY(14px); }
          to   { opacity: 1; transform: none; }
        }
        @media (max-width: 900px) {
          #tour .tour-grid { grid-template-columns: 1fr !important; }
          #tour .tour-rail { position: static !important; }
        }
      `}</style>
    </section>
  );
};

Object.assign(window, { Tour });
