// App root + cursor + interactions + tweaks
const { useState: useSA, useEffect: useEA } = React;

function App() {
  const [lang, setLang] = useSA(() => localStorage.getItem('lm-lang') || 'pt');
  const [theme, setTheme] = useSA(() => {
    const stored = localStorage.getItem('lm-theme');
    if (stored) return stored;
    return window.TWEAK_DEFAULTS?.theme || 'light';
  });
  const [heroVariant, setHeroVariant] = useSA(() => {
    return localStorage.getItem('lm-hero') || window.TWEAK_DEFAULTS?.heroVariant || 'mesh';
  });
  const [showTweaks, setShowTweaks] = useSA(false);
  const [scrolled, setScrolled] = useSA(false);
  const [activeSection, setActiveSection] = useSA('home');

  const t = window.I18N[lang];

  // persist
  useEA(() => { localStorage.setItem('lm-lang', lang); }, [lang]);
  useEA(() => {
    localStorage.setItem('lm-theme', theme);
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);
  useEA(() => {
    localStorage.setItem('lm-hero', heroVariant);
    document.documentElement.setAttribute('data-hero', heroVariant);
  }, [heroVariant]);

  // Nav scroll state + active section
  useEA(() => {
    function onScroll() {
      setScrolled(window.scrollY > 40);
      const sections = ['home', 'services', 'about', 'process', 'contact'];
      for (const id of sections.reverse()) {
        const el = document.getElementById(id);
        if (el) {
          const rect = el.getBoundingClientRect();
          if (rect.top <= 120) { setActiveSection(id); break; }
        }
      }
    }
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Reveal observer
  useEA(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) e.target.classList.add('in');
      });
    }, { threshold: 0.1, rootMargin: '0px 0px -60px 0px' });
    const watch = () => document.querySelectorAll('.reveal:not(.in)').forEach(el => obs.observe(el));
    watch();
    const mo = new MutationObserver(watch);
    mo.observe(document.body, { childList: true, subtree: true });
    return () => { obs.disconnect(); mo.disconnect(); };
  }, [lang]);

  // Custom cursor
  useEA(() => {
    if (window.innerWidth <= 900) return;
    const dot = document.createElement('div');
    dot.className = 'cursor-dot';
    const ring = document.createElement('div');
    ring.className = 'cursor-ring';
    document.body.appendChild(dot);
    document.body.appendChild(ring);
    let mx = 0, my = 0, rx = 0, ry = 0;
    function move(e) {
      mx = e.clientX; my = e.clientY;
      dot.style.transform = `translate(${mx}px, ${my}px) translate(-50%,-50%)`;
    }
    function loop() {
      rx += (mx - rx) * 0.18;
      ry += (my - ry) * 0.18;
      ring.style.transform = `translate(${rx}px, ${ry}px) translate(-50%,-50%)`;
      requestAnimationFrame(loop);
    }
    window.addEventListener('mousemove', move);
    loop();

    function hoverIn() { document.body.classList.add('cursor-hover'); }
    function hoverOut() { document.body.classList.remove('cursor-hover'); }
    function attach() {
      document.querySelectorAll('a, button, [data-magnetic], .project, .service, .faq-q, .stack-item').forEach(el => {
        el.addEventListener('mouseenter', hoverIn);
        el.addEventListener('mouseleave', hoverOut);
      });
    }
    attach();
    const mo = new MutationObserver(attach);
    mo.observe(document.body, { childList: true, subtree: true });

    return () => {
      window.removeEventListener('mousemove', move);
      dot.remove(); ring.remove(); mo.disconnect();
    };
  }, [lang]);

  // Magnetic buttons
  useEA(() => {
    const els = document.querySelectorAll('[data-magnetic]');
    const handlers = [];
    els.forEach(el => {
      function move(e) {
        const rect = el.getBoundingClientRect();
        const x = e.clientX - (rect.left + rect.width / 2);
        const y = e.clientY - (rect.top + rect.height / 2);
        el.style.transform = `translate(${x * 0.25}px, ${y * 0.25}px)`;
      }
      function leave() { el.style.transform = ''; }
      el.addEventListener('mousemove', move);
      el.addEventListener('mouseleave', leave);
      handlers.push([el, move, leave]);
    });
    return () => handlers.forEach(([el, m, l]) => {
      el.removeEventListener('mousemove', m);
      el.removeEventListener('mouseleave', l);
    });
  }, [lang]);

  // Tweaks listener
  useEA(() => {
    function onMsg(e) {
      if (e.data?.type === '__activate_edit_mode') setShowTweaks(true);
      else if (e.data?.type === '__deactivate_edit_mode') setShowTweaks(false);
    }
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  function updateTweak(key, value) {
    if (key === 'theme') setTheme(value);
    if (key === 'heroVariant') setHeroVariant(value);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: value } }, '*');
  }

  const navItems = [
    { id: 'services', label: t.nav.services },
    { id: 'about', label: t.nav.about },
    { id: 'process', label: t.nav.process },
    // { id: 'projects', label: t.nav.work },  // Temporarily hidden until cases are ready
    { id: 'contact', label: t.nav.contact },
  ];

  return (
    <>
      {/* NAV */}
      <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
        <div className="container nav-inner">
          <a href="#home" className="nav-logo magnetic" data-magnetic>
            <span className="nav-logo-mark">
              <img src="assets/portrait.jpg" alt="Luís Mendes" />
            </span>
            <span className="nav-logo-name">
              <strong>Luís Mendes</strong>
              <small>Web Designer</small>
            </span>
          </a>
          <div className="nav-links">
            {navItems.map(n => (
              <a key={n.id} href={`#${n.id}`} className={`nav-link ${activeSection === n.id ? 'active' : ''}`}>
                {n.label}
              </a>
            ))}
          </div>
          <div className="nav-right">
            <div className="nav-toggle">
              <button className={lang === 'pt' ? 'on' : ''} onClick={() => setLang('pt')}>PT</button>
              <button className={lang === 'en' ? 'on' : ''} onClick={() => setLang('en')}>EN</button>
            </div>
            <button className="theme-btn" onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')} title="Theme">
              {theme === 'light' ? (
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M10.5 8a4.5 4.5 0 01-5.5-5.5A5 5 0 1012 7.5c-.5.3-1 .5-1.5.5z" fill="currentColor"/></svg>
              ) : (
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="7" cy="7" r="2.5"/><path d="M7 1v2M7 11v2M1 7h2M11 7h2M2.8 2.8l1.4 1.4M9.8 9.8l1.4 1.4M2.8 11.2l1.4-1.4M9.8 4.2l1.4-1.4"/></svg>
              )}
            </button>
            <a href="#contact" className="nav-cta magnetic" data-magnetic>
              <span className="nav-cta-dot"></span>
              <span>{t.nav.cta}</span>
            </a>
          </div>
        </div>
      </nav>

      {/* CONTENT */}
      <main>
        <Hero t={t} variant={heroVariant} />
        <Marquee items={t.marquee} />
        <Services t={t} />
        <About t={t} />
        <Process t={t} />
        {/* <Projects t={t} /> — Temporarily hidden until cases are ready */}
        <Stack t={t} />
        <Testimonials t={t} />
        <FAQ t={t} />
        <CTA t={t} />
      </main>
      <Footer t={t} />

      {/* Floating WhatsApp button — pulses to draw attention, opens WA with
          a prefilled message in the current language. */}
      <a
        href={`https://wa.me/${t.cta.whatsapp_raw}?text=${encodeURIComponent(t.cta.whatsapp_message)}`}
        target="_blank"
        rel="noopener noreferrer"
        className="btn-whatsapp-float"
        aria-label="WhatsApp"
      >
        <svg viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
          <path d="M16.003 0C7.2 0 .1 7.1.1 15.9c0 2.8.7 5.5 2.1 7.9L0 32l8.4-2.2c2.3 1.3 4.9 2 7.6 2h.01c8.8 0 15.9-7.1 15.9-15.9 0-4.2-1.7-8.2-4.7-11.2C24.2 1.7 20.2 0 16.003 0zm0 29.1c-2.5 0-4.9-.7-7-1.9l-.5-.3-5 1.3 1.3-4.8-.3-.5c-1.4-2.2-2.1-4.7-2.1-7.3 0-7.4 6-13.2 13.2-13.2 3.5 0 6.8 1.4 9.3 3.9 2.5 2.5 3.9 5.8 3.9 9.3 0 7.3-5.9 13.5-12.7 13.5zm7.3-10c-.4-.2-2.3-1.1-2.7-1.3-.4-.1-.6-.2-.9.2-.3.4-1.1 1.3-1.3 1.6-.2.2-.5.3-.9.1-.4-.2-1.7-.6-3.2-2-1.2-1.1-2-2.4-2.2-2.8-.2-.4 0-.6.2-.8.2-.2.4-.5.6-.7.2-.2.3-.4.4-.7.1-.3 0-.5-.1-.7-.1-.2-.9-2.1-1.2-2.9-.3-.8-.7-.6-.9-.7h-.8c-.3 0-.7.1-1.1.5-.4.4-1.4 1.4-1.4 3.4 0 2 1.5 3.9 1.7 4.2.2.3 2.9 4.4 7 6.2.9.4 1.7.7 2.3.9.9.3 1.8.3 2.4.2.7-.1 2.3-.9 2.6-1.9.3-1 .3-1.8.2-1.9-.1-.2-.3-.3-.7-.5z"/>
        </svg>
      </a>

      {/* TWEAKS */}
      {showTweaks && (
        <div className="tweaks-panel show">
          <div className="tweaks-title">
            <span>✦ {t.tweaks.title}</span>
            <button className="tweaks-close" onClick={() => {
              setShowTweaks(false);
              window.parent.postMessage({ type: '__edit_mode_deactivate_request' }, '*');
            }}>×</button>
          </div>
          <div className="tweak-group">
            <label className="tweak-label">{t.tweaks.hero}</label>
            <div className="tweak-options">
              {[['mesh', t.tweaks.mesh], ['grid', t.tweaks.grid], ['aurora', t.tweaks.aurora]].map(([k, label]) => (
                <button key={k} className={`tweak-opt ${heroVariant === k ? 'active' : ''}`} onClick={() => updateTweak('heroVariant', k)}>{label}</button>
              ))}
            </div>
          </div>
          <div className="tweak-group">
            <label className="tweak-label">{t.tweaks.theme}</label>
            <div className="tweak-options" style={{ gridTemplateColumns: 'repeat(2, 1fr)' }}>
              <button className={`tweak-opt ${theme === 'light' ? 'active' : ''}`} onClick={() => updateTweak('theme', 'light')}>{t.tweaks.light}</button>
              <button className={`tweak-opt ${theme === 'dark' ? 'active' : ''}`} onClick={() => updateTweak('theme', 'dark')}>{t.tweaks.dark}</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

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