/* global React, ReactDOM, COPY, Icon, Logo, Mark, Button, Eyebrow,
   Hero, About, StatsBand, Services, Projects, QuoteBand, Contact, CTABand, SiteFooter */
const { useState, useEffect, useRef } = React;

const PAD_X = 'clamp(22px, 5.5vw, 76px)';

// Site settings (language / theme / accent / hero background / motion).
// Edit these defaults to change what loads first; values persist to localStorage
// so a visitor's language + theme choice survives reloads.
const TWEAK_DEFAULTS = {
  "lang": "sr",
  "theme": "dark",
  "accent": "#D4AF37",
  "heroBg": "spotlight",   // 'spotlight' | 'mark' | 'minimal'
  "motion": true
};

const TWEAKS_KEY = 'es-settings';

// localStorage-backed settings store. Keeps the [values, setTweak] interface the
// nav toggles use: setTweak('lang','en') / setTweak('theme','light').
function useTweaks(defaults) {
  const [values, setValues] = useState(() => {
    try { return { ...defaults, ...JSON.parse(localStorage.getItem(TWEAKS_KEY) || '{}') }; }
    catch (_) { return defaults; }
  });
  const setTweak = (keyOrEdits, val) => {
    const edits = (typeof keyOrEdits === 'object' && keyOrEdits !== null) ? keyOrEdits : { [keyOrEdits]: val };
    setValues((prev) => {
      const next = { ...prev, ...edits };
      try { localStorage.setItem(TWEAKS_KEY, JSON.stringify(next)); } catch (_) {}
      return next;
    });
  };
  return [values, setTweak];
}

const SECTIONS = ['home', 'about', 'services', 'projects', 'contact'];

function ScrollProgress() {
  const ref = useRef(null);
  useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const p = h.scrollTop / (h.scrollHeight - h.clientHeight || 1);
      if (ref.current) ref.current.style.transform = `scaleX(${p})`;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return <div style={{ position: 'fixed', top: 0, left: 0, right: 0, height: 2, zIndex: 60, transformOrigin: '0 0', transform: 'scaleX(0)', background: 'var(--accent)' }} ref={ref} />;
}

function Nav({ t, lang, theme, setTweak, active }) {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const go = (id) => { setOpen(false); document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' }); };
  const links = SECTIONS.map(id => [id, t.nav[id]]);

  const veil = theme === 'dark' ? 'rgba(20,21,25,0.72)' : 'rgba(245,245,247,0.78)';

  const LangToggle = ({ size = 'sm' }) => (
    <div style={{ display: 'inline-flex', border: '1px solid var(--hairline-strong)', borderRadius: 'var(--r-pill)', overflow: 'hidden', flex: '0 0 auto' }}>
      {['sr', 'en'].map(l => (
        <button key={l} onClick={() => setTweak('lang', l)} style={{
          fontFamily: 'var(--font-display)', fontWeight: 700, letterSpacing: '0.1em', fontSize: 12,
          padding: size === 'lg' ? '10px 18px' : '7px 13px', border: 'none', cursor: 'pointer',
          textTransform: 'uppercase', transition: 'all var(--dur-fast) var(--ease-out)',
          background: lang === l ? 'var(--accent)' : 'transparent', color: lang === l ? 'var(--accent-contrast)' : 'var(--fg2)',
        }}>{l}</button>
      ))}
    </div>
  );

  const ThemeToggle = () => (
    <button onClick={() => setTweak('theme', theme === 'dark' ? 'light' : 'dark')} aria-label="Toggle theme" style={{
      width: 40, height: 40, borderRadius: 'var(--r-pill)', border: '1px solid var(--hairline-strong)',
      background: 'transparent', color: 'var(--fg1)', cursor: 'pointer', display: 'inline-flex',
      alignItems: 'center', justifyContent: 'center', flex: '0 0 auto', transition: 'all var(--dur-base) var(--ease-out)',
    }} className="theme-toggle">
      <Icon name={theme === 'dark' ? 'sun' : 'moon'} size={19} />
    </button>
  );

  return (
    <>
      <header style={{
        position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50, display: 'flex', alignItems: 'center',
        gap: 24, padding: `${scrolled ? '14px' : '20px'} ${PAD_X}`, background: scrolled ? veil : 'transparent',
        backdropFilter: scrolled ? 'blur(20px)' : 'none', WebkitBackdropFilter: scrolled ? 'blur(20px)' : 'none',
        borderBottom: scrolled ? '1px solid var(--hairline)' : '1px solid transparent',
        transition: 'all var(--dur-base) var(--ease-out)',
      }}>
        <a href="#home" onClick={e => { e.preventDefault(); go('home'); }} style={{ display: 'flex', flex: '0 0 auto' }}>
          <Logo height={30} theme={theme} />
        </a>

        <nav className="nav-links" style={{ display: 'flex', gap: 28, marginLeft: 16, flex: 1 }}>
          {links.map(([id, label]) => (
            <a key={id} href={`#${id}`} onClick={e => { e.preventDefault(); go(id); }} className="ns-link" style={{
              fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 14, textDecoration: 'none', whiteSpace: 'nowrap',
              color: active === id ? 'var(--accent-ink)' : 'var(--fg2)', position: 'relative', paddingBottom: 4,
              transition: 'color var(--dur-fast) var(--ease-out)',
            }}>
              {label}
              <span style={{ position: 'absolute', left: 0, bottom: 0, height: 1.5, width: active === id ? '100%' : 0, background: 'var(--accent)', transition: 'width var(--dur-base) var(--ease-out)' }} />
            </a>
          ))}
        </nav>

        <div className="nav-controls" style={{ display: 'flex', alignItems: 'center', gap: 12, flex: '0 0 auto' }}>
          <LangToggle />
          <ThemeToggle />
          <Button style={{ padding: '11px 20px' }} onClick={() => go('contact')}>{t.cta.access}</Button>
        </div>

        <button className="nav-burger" onClick={() => setOpen(true)} aria-label="Menu" style={{
          display: 'none', width: 44, height: 44, borderRadius: 'var(--r-sm)', border: '1px solid var(--hairline-strong)',
          background: 'transparent', color: 'var(--fg1)', cursor: 'pointer', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto',
        }}>
          <Icon name="menu" size={22} />
        </button>
      </header>

      {/* mobile overlay */}
      <div style={{
        position: 'fixed', inset: 0, zIndex: 70, background: 'var(--bg)', display: 'flex', flexDirection: 'column',
        padding: `${PAD_X}`, transform: open ? 'translateY(0)' : 'translateY(-100%)', opacity: open ? 1 : 0,
        transition: 'transform var(--dur-base) var(--ease-out), opacity var(--dur-base) var(--ease-out)',
        pointerEvents: open ? 'auto' : 'none',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 'clamp(32px,8vw,56px)' }}>
          <Logo height={30} theme={theme} />
          <button onClick={() => setOpen(false)} aria-label="Close" style={{ width: 44, height: 44, borderRadius: 'var(--r-sm)', border: '1px solid var(--hairline-strong)', background: 'transparent', color: 'var(--fg1)', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="x" size={24} />
          </button>
        </div>
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 4, flex: 1 }}>
          {links.map(([id, label], i) => (
            <a key={id} href={`#${id}`} onClick={e => { e.preventDefault(); go(id); }} style={{
              fontFamily: 'var(--font-display)', fontWeight: 800, textTransform: 'uppercase', letterSpacing: '-0.01em',
              fontSize: 'clamp(34px,9vw,52px)', color: active === id ? 'var(--accent)' : 'var(--fg1)', textDecoration: 'none',
              padding: '10px 0', borderBottom: '1px solid var(--hairline)', display: 'flex', alignItems: 'baseline', gap: 14,
            }}>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--accent-ink)', fontWeight: 400 }}>{String(i + 1).padStart(2, '0')}</span>
              {label}
            </a>
          ))}
        </nav>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 28, flexWrap: 'wrap' }}>
          <LangToggle size="lg" />
          <ThemeToggle />
          <Button style={{ flex: 1, padding: '15px', minWidth: 160 }} onClick={() => go('contact')}>{t.cta.access}</Button>
        </div>
      </div>
    </>
  );
}

function App() {
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const lang = tw.lang === 'en' ? 'en' : 'sr';
  const theme = tw.theme === 'light' ? 'light' : 'dark';
  const t = COPY[lang];
  const [active, setActive] = useState('home');

  // keep <html>/body in sync with theme so letterbox + scrollbar match
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    document.documentElement.lang = lang;
  }, [theme, lang]);

  // active section tracking
  useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) setActive(e.target.id); });
    }, { rootMargin: '-45% 0px -50% 0px', threshold: 0 });
    SECTIONS.forEach(id => { const el = document.getElementById(id); if (el) obs.observe(el); });
    return () => obs.disconnect();
  }, [lang]);

  const accentVars = {
    '--accent': tw.accent,
    '--gold': tw.accent,
    '--accent-ink': theme === 'dark' ? tw.accent : shade(tw.accent, -0.28),
  };

  return (
    <div data-theme={theme} style={{ background: 'var(--bg)', color: 'var(--fg1)', minHeight: '100vh', transition: 'background var(--dur-base) var(--ease-out)', ...accentVars }}>
      <ScrollProgress />
      <Nav t={t} lang={lang} theme={theme} setTweak={setTweak} active={active} />
      <main>
        <Hero t={t} motionOn={tw.motion} bg={tw.heroBg} theme={theme} />
        <About t={t} />
        <StatsBand t={t} />
        <Services t={t} />
        <Projects t={t} />
        <QuoteBand t={t} />
        <Contact t={t} lang={lang} />
        <CTABand t={t} />
      </main>
      <SiteFooter t={t} theme={theme} />
    </div>
  );
}

// quick hex shade helper for accent-ink on light theme
function shade(hex, amt) {
  const h = hex.replace('#', '');
  let r = parseInt(h.substring(0, 2), 16), g = parseInt(h.substring(2, 4), 16), b = parseInt(h.substring(4, 6), 16);
  r = Math.max(0, Math.min(255, Math.round(r + amt * 255)));
  g = Math.max(0, Math.min(255, Math.round(g + amt * 255)));
  b = Math.max(0, Math.min(255, Math.round(b + amt * 255)));
  return `#${[r, g, b].map(x => x.toString(16).padStart(2, '0')).join('')}`;
}

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