// Shared layout components: header, footer, ticker, placeholders, lang state
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

// Language context (mock — toggles copy between IT and EN where we bother)
const LangCtx = createContext({ lang: 'it', setLang: () => {} });

function useLang() {
  return useContext(LangCtx);
}

function t(it, en) {
  const { lang } = useLang();
  return lang === 'en' ? en : it;
}

function T({ it, en }) {
  const { lang } = useLang();
  return lang === 'en' ? en : it;
}

function LangProvider({ children }) {
  const [lang, setLang] = useState(() => {
    try { return localStorage.getItem('geek_lang') || 'it'; } catch { return 'it'; }
  });
  useEffect(() => {
    try { localStorage.setItem('geek_lang', lang); } catch {}
    document.documentElement.lang = lang;
  }, [lang]);
  return <LangCtx.Provider value={{ lang, setLang }}>{children}</LangCtx.Provider>;
}

function LangToggle() {
  const { lang, setLang } = useLang();
  return (
    <div className="lang-toggle" role="group" aria-label="Language">
      <button className={lang === 'it' ? 'active' : ''} onClick={() => setLang('it')}>IT</button>
      <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
    </div>
  );
}

function SiteHeader({ current }) {
  const items = [
    { id: 'home', href: 'index.html', it: 'Home', en: 'Home' },
    { id: 'servizi', href: 'servizi.html', it: 'Servizi', en: 'Services' },
    { id: 'progetti', href: 'progetti.html', it: 'Progetti', en: 'Work' },
    { id: 'metodo', href: 'metodo.html', it: 'Metodo', en: 'Method' },
    { id: 'blog', href: 'blog.html', it: 'Blog', en: 'Journal' },
    { id: 'contatti', href: 'contatti.html', it: 'Contatti', en: 'Contact' },
  ];

  const [menuOpen, setMenuOpen] = useState(false);
  const close = () => setMenuOpen(false);

  useEffect(() => {
    if (!menuOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') close(); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener('keydown', onKey);
    };
  }, [menuOpen]);

  return (
    <header className="site-header">
      <div className="site-header-inner">
        <a href="index.html" className="logo-mark" aria-label="Geek Srls">
          <img src="assets/logo_geek.svg" alt="Geek" onError={(e) => { e.target.outerHTML = '<span class="logo-mark-text">GeeK<sup>.srls</sup></span>'; }} />
        </a>
        <nav className="nav">
          {items.map(it => (
            <a key={it.id} href={it.href} className={current === it.id ? 'active' : ''}>
              <T it={it.it} en={it.en} />
            </a>
          ))}
        </nav>
        <div className="header-right">
          <LangToggle />
          <a href="contatti.html" className="btn sm orange header-cta">
            <T it="Video-call 30 min" en="30 min call" />
            <span className="arrow">→</span>
          </a>
          <button
            type="button"
            className={`nav-toggle ${menuOpen ? 'open' : ''}`}
            aria-label={menuOpen ? 'Chiudi menu' : 'Apri menu'}
            aria-expanded={menuOpen}
            aria-controls="mobile-menu"
            onClick={() => setMenuOpen(v => !v)}
          >
            <span /><span /><span />
          </button>
        </div>
      </div>

      <div
        id="mobile-menu"
        className={`mobile-menu ${menuOpen ? 'open' : ''}`}
        role="dialog"
        aria-modal="true"
        aria-hidden={!menuOpen}
      >
        <nav className="mobile-menu-nav">
          {items.map((it, i) => (
            <a
              key={it.id}
              href={it.href}
              className={current === it.id ? 'active' : ''}
              onClick={close}
            >
              <span className="mobile-menu-num">{String(i + 1).padStart(2, '0')}</span>
              <T it={it.it} en={it.en} />
            </a>
          ))}
        </nav>
        <div className="mobile-menu-footer">
          <LangToggle />
          <a href="contatti.html" className="btn sm orange" onClick={close}>
            <T it="Video-call 30 min" en="30 min call" />
            <span className="arrow">→</span>
          </a>
        </div>
      </div>
      {menuOpen && <div className="mobile-menu-backdrop" onClick={close} aria-hidden="true" />}
    </header>
  );
}

function Ticker({ items }) {
  const defaultItems = [
    'SOFTWARE GESTIONALE SU MISURA',
    'WEBSERVICES REST / SOAP',
    'AGENTI AI PER PROCESSI AZIENDALI',
    'INTEGRAZIONE SISTEMI LEGACY',
    'KPI MISURABILI, NON PROMESSE',
    'PMI ITALIANE • 10–80 DIPENDENTI',
  ];
  const it = items || defaultItems;
  const doubled = [...it, ...it];
  return (
    <div className="ticker" aria-hidden="true">
      <div className="ticker-inner">
        {doubled.map((s, i) => (
          <span key={i}><span className="dot" />{s}</span>
        ))}
      </div>
    </div>
  );
}

function SiteFooter() {
  return (
    <footer className="site-footer">
      <div className="site-footer-inner">
        <div>
          <div className="site-footer-claim">
            <T
              it={<>L'innovazione senza sviluppo del business è un mero esercizio <em style={{ fontStyle: 'italic', color: '#E8601C' }}>narcisistico</em>.</>}
              en={<>Innovation without business growth is a mere exercise in <em style={{ fontStyle: 'italic', color: '#E8601C' }}>narcissism</em>.</>}
            />
          </div>
          <div style={{ marginTop: 32, fontFamily: 'var(--mono)', fontSize: 12, color: '#8B8F99', letterSpacing: '0.06em', lineHeight: 1.8 }}>
            GEEK SRLS<br />
            VIALE PAVIA, 16 · 26900 LODI<br />
            P.IVA 12543240969<br />
            INFO@GEEK.SRLS
          </div>
        </div>
        <div>
          <h4><T it="Servizi" en="Services" /></h4>
          <a href="servizi.html#gestionale"><T it="Gestionale su misura" en="Custom ERP" /></a>
          <a href="servizi.html#webservices"><T it="Webservices & API" en="Webservices & API" /></a>
          <a href="servizi.html#ai"><T it="Automazione AI" en="AI automation" /></a>
          <a href="servizi.html#integrazioni"><T it="Integrazione legacy" en="Legacy integration" /></a>
        </div>
        <div>
          <h4><T it="Progetti" en="Work" /></h4>
          <a href="progetti.html#glm">Galardi LM</a>
          <a href="progetti.html#gsm">Galardi SM</a>
          <a href="progetti.html#oracolo">Oracolo FSE</a>
          <a href="progetti.html#cvt">CaboVerdeTrip</a>
          <a href="progetti.html#asset">Asset IT</a>
        </div>
        <div>
          <h4><T it="Geek" en="Geek" /></h4>
          <a href="metodo.html"><T it="Metodo" en="Method" /></a>
          <a href="blog.html">Blog</a>
          <a href="contatti.html"><T it="Prenota una call" en="Book a call" /></a>
          <a href="varianti.html"><T it="Esplorazioni di design" en="Design explorations" /></a>
        </div>
      </div>
      <div className="site-footer-bottom">
        <div>© 2026 GEEK SRLS · ALL RIGHTS RESERVED</div>
        <div><T it="COSTRUITO A LODI, CON METODO" en="BUILT IN LODI, WITH METHOD" /></div>
      </div>
    </footer>
  );
}

const NEWSLETTER_ENDPOINT = 'server/api/newsletter.php';

function NewsletterForm({ source = 'web', compact = false }) {
  const { lang } = useLang();
  const [email, setEmail] = useState('');
  const [website, setWebsite] = useState(''); // honeypot
  const [busy, setBusy] = useState(false);
  const [state, setState] = useState(null); // 'ok' | 'already' | 'error'
  const [errorMsg, setErrorMsg] = useState('');

  const onSubmit = async (e) => {
    e.preventDefault();
    if (busy) return;
    setBusy(true);
    setState(null);
    setErrorMsg('');
    try {
      const res = await fetch(NEWSLETTER_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, lang, source, website }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data && data.ok) {
        setState(data.status === 'already' ? 'already' : 'ok');
        setEmail('');
      } else {
        setState('error');
        setErrorMsg((data && data.error) || (lang === 'en' ? 'Something went wrong.' : 'Qualcosa è andato storto.'));
      }
    } catch (err) {
      setState('error');
      setErrorMsg(lang === 'en' ? 'Network error.' : 'Errore di rete.');
    } finally {
      setBusy(false);
    }
  };

  if (state === 'ok') {
    return (
      <div style={{ border: '1px solid var(--rule)', padding: '12px 14px', fontSize: 13, color: 'var(--ink)', background: 'var(--paper-3)' }}>
        <T it="Iscrizione confermata. Controlla la posta — c'è un'email di benvenuto." en="You're in. Check your inbox for a welcome email." />
      </div>
    );
  }
  if (state === 'already') {
    return (
      <div style={{ border: '1px solid var(--rule)', padding: '12px 14px', fontSize: 13, color: 'var(--ink-2)', background: 'var(--paper-3)' }}>
        <T it="Sei già iscritto. Buona lettura." en="You're already subscribed. Enjoy." />
      </div>
    );
  }

  return (
    <form onSubmit={onSubmit} noValidate style={{ position: 'relative' }}>
      <div style={{ display: 'flex', border: '1px solid var(--rule)' }}>
        <input
          type="email"
          required
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder={lang === 'en' ? 'email@company.com' : 'email@azienda.it'}
          disabled={busy}
          style={{ flex: 1, border: 0, padding: compact ? '10px 12px' : '12px 14px', fontFamily: 'var(--mono)', fontSize: compact ? 12 : 13, background: 'transparent', outline: 'none' }}
        />
        <button
          type="submit"
          disabled={busy}
          style={{ border: 0, background: 'var(--ink)', color: 'var(--paper)', padding: compact ? '0 14px' : '0 18px', fontFamily: 'var(--mono)', fontSize: compact ? 11 : 12, letterSpacing: '0.1em', cursor: busy ? 'wait' : 'pointer', opacity: busy ? 0.6 : 1 }}
        >
          {busy ? '…' : '→'}
        </button>
      </div>
      <input
        type="text"
        tabIndex={-1}
        autoComplete="off"
        value={website}
        onChange={(e) => setWebsite(e.target.value)}
        style={{ position: 'absolute', left: '-10000px', width: 1, height: 1, opacity: 0 }}
        aria-hidden="true"
      />
      {state === 'error' && (
        <div style={{ marginTop: 8, fontFamily: 'var(--mono)', fontSize: 11, color: '#c0392b' }}>
          {errorMsg}
        </div>
      )}
    </form>
  );
}

function Placeholder({ label, aspect = '4/3', style = {}, children }) {
  return (
    <div className="placeholder" style={{ aspectRatio: aspect, ...style }}>
      <div className="placeholder-label">{label}</div>
      {children}
    </div>
  );
}

// Expose globally
Object.assign(window, { LangCtx, LangProvider, LangToggle, SiteHeader, SiteFooter, Ticker, Placeholder, NewsletterForm, useLang, T, t });
