/* global React, ReactDOM, MASections, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakToggle, TweakSelect */
const { useEffect, useRef, useState } = React;
const { Hero, BeyondPolicies, Services, Timeline, WhyUs, Insights, Testimonials, FAQ, Contact } = MASections;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "navy",
  "heroVariant": "topo",
  "cursor": true,
  "annotations": false,
  "smoothScroll": true,
  "typePairing": "fraunces-inter"
}/*EDITMODE-END*/;

/* ============================================================
   Custom cursor
   ============================================================ */
function CustomCursor({ enabled }) {
  const dotRef = useRef(null);
  const ringRef = useRef(null);
  useEffect(() => {
    document.body.dataset.cursor = enabled ? 'on' : 'off';
    if (!enabled) return;
    let mx = window.innerWidth/2, my = window.innerHeight/2;
    let rx = mx, ry = my;
    let raf;
    const onMove = (e) => { mx = e.clientX; my = e.clientY; };
    const onOver = (e) => {
      const t = e.target;
      // Don't trigger hover state inside the tweaks panel
      const inTweaks = t.closest && t.closest('.twk-panel');
      const interactive = !inTweaks && t.closest && (t.closest('a,button,[data-cursor-hover],input,textarea'));
      if (ringRef.current) ringRef.current.classList.toggle('is-hover', !!interactive);
      // Hide custom cursor inside tweaks panel so native cursor takes over
      if (dotRef.current) dotRef.current.style.opacity = inTweaks ? '0' : '1';
      if (ringRef.current) ringRef.current.style.opacity = inTweaks ? '0' : '1';
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseover', onOver);
    const tick = () => {
      rx += (mx - rx) * 0.18;
      ry += (my - ry) * 0.18;
      if (dotRef.current) {
        dotRef.current.style.transform = `translate(${mx}px, ${my}px) translate(-50%,-50%)`;
      }
      if (ringRef.current) {
        ringRef.current.style.transform = `translate(${rx}px, ${ry}px) translate(-50%,-50%)`;
      }
      raf = requestAnimationFrame(tick);
    };
    tick();
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseover', onOver);
    };
  }, [enabled]);
  if (!enabled) return null;
  return (
    <>
      <div ref={ringRef} className="cursor-ring"></div>
      <div ref={dotRef} className="cursor-dot"></div>
    </>
  );
}

/* ============================================================
   Lenis-like smooth scroll (lightweight inline impl)
   ============================================================ */
function useSmoothScroll(enabled) {
  useEffect(() => {
    if (!enabled) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    // Touch devices scroll natively with momentum — the rAF scrollTo loop fights
    // that and makes touch scrolling stutter. Skip on touch-first devices.
    const touchFirst = window.matchMedia('(pointer: coarse)').matches
      || window.matchMedia('(hover: none)').matches
      || (navigator.maxTouchPoints || 0) > 0;
    if (touchFirst) return;
    let target = window.scrollY;
    let current = target;
    let raf;
    const onWheel = (e) => {
      // let inputs / focused fields scroll natively
      e.preventDefault();
      target = Math.max(0, Math.min(document.documentElement.scrollHeight - window.innerHeight, target + e.deltaY));
    };
    const tick = () => {
      current += (target - current) * 0.09;
      if (Math.abs(target - current) < 0.4) current = target;
      window.scrollTo(0, current);
      raf = requestAnimationFrame(tick);
    };
    // Sync initial target if user uses keyboard / scrollbar
    const onScrollSync = () => {
      // If the change was external (not from our wheel), sync target
      if (Math.abs(window.scrollY - current) > 4) {
        target = window.scrollY;
        current = window.scrollY;
      }
    };
    // Let in-page anchor clicks drive the same smooth-scroll target
    window.__maScrollTo = (y) => {
      target = Math.max(0, Math.min(document.documentElement.scrollHeight - window.innerHeight, y));
    };
    window.addEventListener('wheel', onWheel, { passive: false });
    window.addEventListener('scroll', onScrollSync, { passive: true });
    raf = requestAnimationFrame(tick);
    return () => {
      cancelAnimationFrame(raf);
      window.__maScrollTo = null;
      window.removeEventListener('wheel', onWheel);
      window.removeEventListener('scroll', onScrollSync);
    };
  }, [enabled]);
}

/* ============================================================
   Smooth in-page anchor navigation (nav links, logo, in-content CTAs)
   ============================================================ */
function useAnchorScroll() {
  useEffect(() => {
    const scrollTo = (y) => {
      if (window.__maScrollTo) window.__maScrollTo(y);
      else window.scrollTo({ top: y, behavior: 'smooth' });
    };
    const onClick = (e) => {
      const a = e.target.closest('a[href^="#"]');
      if (!a) return;
      const href = a.getAttribute('href');
      if (href === '#' || href === '') { e.preventDefault(); scrollTo(0); history.replaceState(null, '', location.pathname); return; }
      const el = document.getElementById(href.slice(1));
      if (!el) return; // no matching section — leave the link alone
      e.preventDefault();
      history.replaceState(null, '', href);
      const goTo = () => {
        const nav = document.querySelector('.nav');
        const navH = nav ? nav.offsetHeight : 0;
        scrollTo(el.getBoundingClientRect().top + window.pageYOffset - navH);
      };
      goTo();
      // Re-aim as late layout settles (web-font swap, async images) can shift the
      // target after the click. Cancel the moment the user scrolls themselves.
      let cancelled = false;
      const cancel = () => {
        cancelled = true;
        window.removeEventListener('wheel', cancel);
        window.removeEventListener('touchstart', cancel);
      };
      window.addEventListener('wheel', cancel, { passive: true });
      window.addEventListener('touchstart', cancel, { passive: true });
      [180, 450, 800].forEach((t) => setTimeout(() => { if (!cancelled) goTo(); }, t));
      setTimeout(cancel, 900);
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, []);
}

/* ============================================================
   Top nav with scroll-aware state
   ============================================================ */
const NAV_LINKS = [
  ['approach', 'Approach'],
  ['services', 'Services'],
  ['lifecycle', 'Lifecycle'],
  ['why', 'Why M+A'],
  ['insights', 'Insights'],
  ['contact', 'Contact'],
];
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [onLight, setOnLight] = useState(false);
  const [active, setActive] = useState('hero');
  useEffect(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 40);
      // Detect if a light section is in the top portion of viewport
      const lightSections = document.querySelectorAll('[data-bg="light"]');
      let inLight = false;
      lightSections.forEach(s => {
        const r = s.getBoundingClientRect();
        if (r.top < 80 && r.bottom > 80) inLight = true;
      });
      setOnLight(inLight);
      // Active section = the last one whose top has passed the mid-viewport line
      let current = 'hero';
      document.querySelectorAll('[data-section]').forEach(s => {
        if (s.getBoundingClientRect().top < window.innerHeight * 0.5) current = s.dataset.section;
      });
      setActive(current);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'is-scrolled' : ''} ${onLight ? 'on-light' : ''}`}>
      <a href="#" className="nav__logo" aria-label="M+A Risk Management home">
        <img className="nav__logo-img nav__logo-img--dark" src="ma-lockup-onDark.png" alt="M+A Risk Management" />
        <img className="nav__logo-img nav__logo-img--light" src="ma-lockup-onLight.png" alt="" aria-hidden="true" />
      </a>
      <div className="nav__links">
        {NAV_LINKS.map(([id, label]) => (
          <a key={id} href={`#${id}`} className={active === id ? 'is-active' : ''}>{label}</a>
        ))}
      </div>
      <a href="#contact" className="nav__cta">
        <span className="dot"></span>
        Schedule a Consultation
      </a>
    </nav>
  );
}

/* ============================================================
   Sticky floating CTA — label morphs by section
   ============================================================ */
const CTA_LABELS = {
  hero: 'Schedule a Consultation',
  approach: 'See Our Approach',
  services: 'Review Your Coverage',
  lifecycle: 'Map Your Stage',
  why: 'Meet the Team',
  insights: 'Read Our Notes',
  testimonials: 'Read Their Story',
  faq: 'Ask Us Directly',
  contact: 'Talk to an Advisor',
};
function FloatCTA() {
  const [section, setSection] = useState('hero');
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const onScroll = () => {
      setVisible(window.scrollY > window.innerHeight * 0.5);
      const sections = document.querySelectorAll('[data-section]');
      let active = 'hero';
      sections.forEach(s => {
        const r = s.getBoundingClientRect();
        if (r.top < window.innerHeight * 0.5) active = s.dataset.section;
      });
      setSection(active);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  // hide when on contact (already there)
  const hideOnContact = section === 'contact';
  return (
    <a href="#contact" className={`float-cta ${visible && !hideOnContact ? 'is-visible' : ''}`}>
      <span className="float-cta__label" key={section}>{CTA_LABELS[section] || CTA_LABELS.hero}</span>
      <span className="float-cta__arrow">→</span>
    </a>
  );
}

/* ============================================================
   Scroll progress bar
   ============================================================ */
function ScrollProgress() {
  const ref = useRef(null);
  useEffect(() => {
    const onScroll = () => {
      const max = document.documentElement.scrollHeight - window.innerHeight;
      const p = max > 0 ? window.scrollY / max : 0;
      if (ref.current) ref.current.style.width = `${p * 100}%`;
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return <div className="scroll-progress" ref={ref}></div>;
}

/* ============================================================
   Annotation toggle
   ============================================================ */
function AnnoToggle({ on, onToggle }) {
  useEffect(() => {
    document.body.dataset.anno = on ? 'on' : 'off';
  }, [on]);
  return (
    <button className="anno-toggle" onClick={onToggle}>
      <span className="dot"></span>
      <span>{on ? 'Hide spec notes' : 'Show spec notes'}</span>
    </button>
  );
}

/* ============================================================
   Intro / page-load
   ============================================================ */
function Intro() {
  const [leaving, setLeaving] = useState(false);
  const [hidden, setHidden] = useState(false);
  useEffect(() => {
    const t1 = setTimeout(() => setLeaving(true), 1000);
    const t2 = setTimeout(() => setHidden(true), 1800);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);
  if (hidden) return null;
  return (
    <div className={`intro ${leaving ? 'is-leaving' : ''}`}>
      <svg className="intro__mark" viewBox="0 0 64 64" fill="none">
        <path d="M6 12 L32 6 L58 12 L58 32 Q58 52 32 60 Q6 52 6 32 Z"
          stroke="var(--bone)" strokeWidth="1.2"
          strokeDasharray="180" strokeDashoffset="180"
          style={{ animation: 'draw 1s var(--ease-out) 0.1s forwards' }}
        />
        <path d="M18 30 L28 38 L46 22"
          stroke="var(--accent)" strokeWidth="1.6"
          strokeDasharray="60" strokeDashoffset="60"
          style={{ animation: 'draw 0.6s var(--ease-out) 0.6s forwards' }}
        />
        <style>{`@keyframes draw { to { stroke-dashoffset: 0; } }`}</style>
      </svg>
      <div className="intro__label">M+A · Risk Management</div>
    </div>
  );
}

/* ============================================================
   Root App
   ============================================================ */
function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply palette
  useEffect(() => {
    document.documentElement.dataset.palette = tweaks.palette;
  }, [tweaks.palette]);

  // Apply type pairing
  useEffect(() => {
    const pair = tweaks.typePairing;
    const root = document.documentElement.style;
    if (pair === 'instrument-geist') {
      root.setProperty('--serif', "'Instrument Serif', serif");
      root.setProperty('--sans', "'Inter Tight', sans-serif");
    } else if (pair === 'eb-plex') {
      root.setProperty('--serif', "'EB Garamond', serif");
      root.setProperty('--sans', "'IBM Plex Sans', sans-serif");
    } else if (pair === 'newsreader-tight') {
      root.setProperty('--serif', "'Newsreader', serif");
      root.setProperty('--sans', "'Inter Tight', sans-serif");
    } else {
      root.setProperty('--serif', "'Fraunces', serif");
      root.setProperty('--sans', "'Inter', sans-serif");
    }
  }, [tweaks.typePairing]);

  useSmoothScroll(tweaks.smoothScroll);
  useAnchorScroll();

  return (
    <>
      <Intro />
      <CustomCursor enabled={tweaks.cursor} />
      <ScrollProgress />
      <Nav />
      <FloatCTA />

      <main>
        <Hero variant={tweaks.heroVariant} />
        <BeyondPolicies />
        <Services />
        <Timeline />
        <WhyUs />
        <Insights />
        <FAQ />
        <Contact />
      </main>

      <TweaksPanel>
        <TweakSection label="Palette" />
        <TweakSelect
          label="Anchor"
          value={tweaks.palette}
          onChange={(v) => setTweak('palette', v)}
          options={[
            { value: 'navy', label: 'Navy' },
            { value: 'charcoal', label: 'Charcoal + Steel Blue' },
            { value: 'charcoal-bone', label: 'Charcoal + Bone' },
            { value: 'forest', label: 'Forest' },
          ]}
        />
        <TweakSection label="Hero animation" />
        <TweakRadio
          label="Variant"
          value={tweaks.heroVariant}
          onChange={(v) => setTweak('heroVariant', v)}
          options={[
            { value: 'topo', label: 'Topo' },
            { value: 'particles', label: 'Shield' },
            { value: 'geometry', label: 'Arches' },
          ]}
        />
        <TweakSection label="Typography" />
        <TweakSelect
          label="Pairing"
          value={tweaks.typePairing}
          onChange={(v) => setTweak('typePairing', v)}
          options={[
            { value: 'fraunces-inter', label: 'Fraunces + Inter' },
            { value: 'instrument-geist', label: 'Instrument Serif + Inter Tight' },
            { value: 'eb-plex', label: 'EB Garamond + IBM Plex' },
            { value: 'newsreader-tight', label: 'Newsreader + Inter Tight' },
          ]}
        />
        <TweakSection label="Interactions" />
        <TweakToggle
          label="Custom cursor"
          value={tweaks.cursor}
          onChange={(v) => setTweak('cursor', v)}
        />
        <TweakToggle
          label="Smooth scroll"
          value={tweaks.smoothScroll}
          onChange={(v) => setTweak('smoothScroll', v)}
        />
        <TweakToggle
          label="Spec annotations"
          value={tweaks.annotations}
          onChange={(v) => setTweak('annotations', v)}
        />
      </TweaksPanel>
    </>
  );
}

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