// Main App for F1 StratLab landing page

const TWEAKS_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "agent_graph",
  "showMeta": true,
  "accentStyle": "purple_blue"
}/*EDITMODE-END*/;

const NAV_SECTIONS = [
  { id: 'how',       label: 'Architecture' },
  { id: 'agents',    label: 'Agents' },
  { id: 'telemetry', label: 'Telemetry' },
  { id: 'surfaces',  label: 'Surfaces' },
  { id: 'install',   label: 'Install' },
];

function App() {
  const [tweaks, setTweaks] = useState(() => {
    try {
      const saved = localStorage.getItem('f1sm_tweaks');
      return saved ? { ...TWEAKS_DEFAULTS, ...JSON.parse(saved) } : TWEAKS_DEFAULTS;
    } catch { return TWEAKS_DEFAULTS; }
  });
  const [tweaksOpen, setTweaksOpen] = useState(false);

  // ── Scrollspy: highlight nav link + animated underline bar ──
  const [activeSection, setActiveSection] = useState(null);
  const navLinksRef = useRef(null);
  const linkRefs = useRef({});
  const [barStyle, setBarStyle] = useState({ left: 0, width: 0, opacity: 0 });

  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      // Choose the entry whose midline is closest to the viewport midline
      const visible = entries.filter(e => e.isIntersecting);
      if (visible.length === 0) return;
      visible.sort((a, b) => Math.abs(a.boundingClientRect.top) - Math.abs(b.boundingClientRect.top));
      setActiveSection(visible[0].target.id);
    }, { rootMargin: '-45% 0px -45% 0px', threshold: 0 });

    NAV_SECTIONS.forEach(s => {
      const el = document.getElementById(s.id);
      if (el) io.observe(el);
    });
    return () => io.disconnect();
  }, []);

  useEffect(() => {
    const compute = () => {
      const link = activeSection ? linkRefs.current[activeSection] : null;
      if (link && navLinksRef.current) {
        const parentRect = navLinksRef.current.getBoundingClientRect();
        const linkRect = link.getBoundingClientRect();
        setBarStyle({ left: linkRect.left - parentRect.left, width: linkRect.width, opacity: 1 });
      } else {
        setBarStyle(s => ({ ...s, opacity: 0 }));
      }
    };
    compute();
    window.addEventListener('resize', compute);
    return () => window.removeEventListener('resize', compute);
  }, [activeSection]);

  // Tweaks protocol
  useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', handler);
    // announce availability AFTER listener is live
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  const updateTweak = (key, value) => {
    const next = { ...tweaks, [key]: value };
    setTweaks(next);
    try { localStorage.setItem('f1sm_tweaks', JSON.stringify(next)); } catch {}
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: value } }, '*');
  };

  // Scroll reveal
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.12, rootMargin: '-40px 0px' });
    document.querySelectorAll('section').forEach(s => {
      s.classList.add('reveal');
      io.observe(s);
    });
    return () => io.disconnect();
  }, []);

  // Auto-close the mobile hamburger when the user taps a link inside it.
  // Without this, tapping a section just updates the hash but leaves the
  // dropdown open, blocking the page content.
  useEffect(() => {
    const onClick = (e) => {
      const a = e.target.closest('.nav-mobile-panel a');
      if (!a) return;
      const details = a.closest('details');
      if (details) details.open = false;
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, []);

  const HeroViz = tweaks.heroVariant === 'dashboard' ? DashboardViz
                : tweaks.heroVariant === 'cinematic' ? CinematicViz
                : AgentGraphViz;

  return (
    <div id="top">
      {/* NAV */}
      <nav className="nav">
        <div className="nav-inner">
          <a href="#top" className="logo">
            <span>F1 StratLab</span>
          </a>
          <div className="nav-links" ref={navLinksRef}>
            {NAV_SECTIONS.map(s => (
              <a key={s.id}
                 ref={el => { linkRefs.current[s.id] = el; }}
                 href={`#${s.id}`}
                 className={activeSection === s.id ? 'active' : ''}>
                {s.label}
              </a>
            ))}
            <span className="nav-bar" style={{
              left: `${barStyle.left}px`,
              width: `${barStyle.width}px`,
              opacity: barStyle.opacity
            }}/>
          </div>
          <div className="nav-right">
            <a className="btn btn-ghost btn-sm" href="https://github.com/VforVitorio/F1_Strat_Manager" target="_blank">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .3a12 12 0 0 0-3.8 23.4c.6.1.8-.3.8-.6v-2c-3.3.7-4-1.6-4-1.6-.5-1.4-1.3-1.8-1.3-1.8-1.1-.7.1-.7.1-.7 1.2.1 1.8 1.2 1.8 1.2 1.1 1.8 2.8 1.3 3.5 1 .1-.8.4-1.3.8-1.6-2.7-.3-5.5-1.3-5.5-5.9 0-1.3.5-2.4 1.2-3.2-.1-.3-.5-1.5.1-3.2 0 0 1-.3 3.3 1.2a11.5 11.5 0 0 1 6 0C17.3 4.7 18.3 5 18.3 5c.6 1.7.2 2.9.1 3.2.8.8 1.2 1.9 1.2 3.2 0 4.6-2.8 5.6-5.5 5.9.4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6A12 12 0 0 0 12 .3"/></svg>
              GitHub
            </a>
            <a className="btn btn-primary btn-sm" href="#install">Get started</a>
          </div>
          {/* Mobile hamburger — native <details> toggle, no JS/state needed.
              Visible only on mobile via CSS; on desktop the nav-links and
              nav-right above cover navigation. */}
          <details className="nav-mobile">
            <summary aria-label="Open menu">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                <line x1="4" y1="7"  x2="20" y2="7"/>
                <line x1="4" y1="12" x2="20" y2="12"/>
                <line x1="4" y1="17" x2="20" y2="17"/>
              </svg>
            </summary>
            <div className="nav-mobile-panel">
              {NAV_SECTIONS.map(s => (
                <a key={s.id} href={`#${s.id}`} className={activeSection === s.id ? 'active' : ''}>
                  {s.label}
                </a>
              ))}
              <hr/>
              <a href="https://github.com/VforVitorio/F1_Strat_Manager" target="_blank" rel="noopener">GitHub</a>
              <a href="#install" className="primary">Get started</a>
            </div>
          </details>
        </div>
      </nav>

      {/* HERO */}
      <section className="hero">
        <div className="hero-halo"/>
        <div className="hero-grid-lines"/>
        <div className="container-wide">
          <div className="hero-inner">
            <span className="eyebrow hero-eyebrow">
              <span className="eyebrow-bar"/>
              F1 StratLab · Multi-agent strategy · open source · <span style={{ textTransform: 'none' }}>v0.1.1</span>
              <span className="eyebrow-bar"/>
            </span>
            <h1>
              Race strategy,<br/>
              <span className="accent">decided by six agents.</span>
            </h1>
            <p className="hero-sub">
              F1 StratLab orchestrates seven ML models and a LangGraph multi-agent system
              to produce real-time Formula 1 strategy recommendations — from lap time prediction
              to tire degradation, radio NLP, and RAG over FIA regulations.
            </p>
            <div className="hero-ctas">
              <a className="btn btn-primary btn-lg" href="#install">
                <span className="mono" style={{fontSize: 12, opacity: 0.7}}>$</span>
                uv run f1-strat
              </a>
              <a className="btn btn-ghost btn-lg" href="#how">
                See how it works
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
              </a>
            </div>
            {tweaks.showMeta && (
              <div className="hero-meta">
                <span><strong style={{ color: 'var(--purple-300)' }}>7</strong> ML models</span>
                <span style={{ color: 'var(--fg-4)' }}>·</span>
                <span><strong style={{ color: 'var(--purple-300)' }}>6</strong> LangGraph sub-agents</span>
                <span style={{ color: 'var(--fg-4)' }}>·</span>
                <span><strong style={{ color: 'var(--purple-300)' }}>71</strong> Grand Prix · 2023–25</span>
                <span style={{ color: 'var(--fg-4)' }}>·</span>
                <span><strong style={{ color: 'var(--purple-300)' }}>Open</strong> Source</span>
              </div>
            )}
          </div>

          <div className="hero-viz" key={tweaks.heroVariant}>
            <HeroViz/>
          </div>
        </div>
      </section>

      {/* HOW IT WORKS */}
      <HowItWorksSection/>

      {/* AGENTS — one mini viz per sub-agent */}
      <AgentsSection/>

      {/* TELEMETRY — actual (solid) vs predicted (dashed) */}
      <TelemetrySection/>

      {/* CIRCUIT — animated track */}
      <CircuitSection/>

      {/* PINNED SCROLL NARRATIVE */}
      <ScrollPinnedSection/>

      {/* MODELS */}
      <ModelsSection/>

      {/* RAG DEMO */}
      <RagSection/>

      {/* SURFACES — CLI / Arcade / Streamlit */}
      <SurfacesSection/>

      {/* CLI INSTALL */}
      <CliSection/>

      {/* STACK */}
      <StackSection/>

      {/* PAPER */}
      <PaperSection/>

      {/* CONTRIBUTING */}
      <ContributingSection/>

      {/* MEET THE AUTHOR */}
      <AboutAuthor/>

      {/* FOOTER */}
      <Footer/>

      {/* TWEAKS PANEL */}
      {tweaksOpen && (
        <div className="tweaks-panel">
          <h4>Tweaks</h4>
          <div className="tweak-row">
            <div className="tweak-label">Hero centerpiece</div>
            <div className="tweak-opts">
              {[
                ['agent_graph', 'Agents'],
                ['dashboard',   'Dashboard'],
                ['cinematic',   'Cinematic']
              ].map(([val, label]) => (
                <button key={val}
                        className={`tweak-opt ${tweaks.heroVariant === val ? 'active' : ''}`}
                        onClick={() => updateTweak('heroVariant', val)}>{label}</button>
              ))}
            </div>
          </div>
          <div className="tweak-row">
            <div className="tweak-label">Hero meta row</div>
            <div className="tweak-opts">
              {[[true, 'On'], [false, 'Off']].map(([val, label]) => (
                <button key={String(val)}
                        className={`tweak-opt ${tweaks.showMeta === val ? 'active' : ''}`}
                        onClick={() => updateTweak('showMeta', val)}>{label}</button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
