// Main app: React-driven interactive bits.
// Bilingual: EN / IT

const { useState, useEffect, useRef, useCallback } = React;

/* ============ Translations ============ */
const T = {
  en: {
    langToggle: { label: 'cambia in', flag: '🇮🇹' },
    nav: {
      myself: 'Myself',
      collaboration: 'Collaboration',
      partner: 'Partner',
      faq: 'FAQ',
      help: 'Let me help you',
    },
    hero: {
      eyebrow: 'Freelance · Web design, development and AI',
      h1a: 'Web solutions that integrate ',
      h1accent: 'AI and automation',
      h1b: ' where it matters.',
      ledeStrong: 'Services for companies and agencies.',
      ledeBodyPre: ' I build websites, e-commerce platforms and digital processes, integrating ',
      ledeBodyStrong: 'AI tools where they reduce time and improve the quality',
      ledeBodyPost: ' of the work.',
      ctaPrimary: 'Book your free consultation',
      ctaSecondary: 'Learn more ↓',
      scroll: 'Scroll ↓',
    },
    myself: {
      sectionLabelText: 'Myself',
      eyebrow: 'About',
      titleA: 'Listening first.',
      titleB: 'Shipping',
      titleC: ' second.',
      bio1pre: "I'm ",
      bio1name: 'Fabio Calvosa',
      bio1post: ', a freelance web designer and front-end developer based in Italy. For ',
      bio1strongYears: 'more than two decades',
      bio1mid: " I've helped small teams and companies turn their work into ",
      bio1strongValues: 'concrete, well-built websites and digital projects',
      bio1tail: '.',
      bio2pre: 'My approach starts with a ',
      bio2strong: 'conversation, not a template',
      bio2post: ". Every project gets its own tailored path: from positioning and information architecture to interface, development and hosting.",
      bioParaPre: 'Since 2005 building the web. From the early days of table layouts to AI-powered workflows. ',
      bioParaStrong: 'More than 80 projects',
      bioParaPost: " delivered for clients in Italy and abroad, working with each client's tools, process and goals.",
      skills: [
        ['Sites & e-commerce', 'WordPress · WooCommerce'],
        ['Front-end', 'pixel-accurate'],
        ['AI & automation', 'agents & workflows'],
        ['Consulting & UX', 'digital strategy'],
        ['Hosting', 'w/ Artera'],
      ],
    },
    collab: {
      sectionLabelText: 'Collaboration',
      eyebrow: "Let's work together",
      titleA: 'Start with a ',
      titleAccent: 'brief',
      titleB: ', not a wall of questions.',
      descPre: 'A short, structured conversation in four steps. I read every submission ',
      descStrong1: 'personally',
      descMid: ' and reply ',
      descStrong2: 'within two working days',
      descTail: ' with a honest assessment and next steps.',
      steps: ['Project type', 'Scope & budget', 'About you', 'Privacy'],
      step0title: 'What are you looking for?',
      step0sub: 'Pick the closest match. We can refine later.',
      kinds: ['New website', 'Refresh / redesign', 'Online store', 'Consulting', 'Ongoing partnership', 'AI & Automation'],
      step1title: 'What do you need?',
      step1sub: 'Rough is fine. Nothing is binding.',
      scopeLabel: "What's included",
      scopes: ['Strategy & consulting', 'Design & visual identity', 'Website development', 'CMS / WordPress', 'Hosting & maintenance', 'Copywriting', 'SEO & visibility'],
      budgetLabel: 'Budget range',
      budgets: ['< 5k €', '5 – 15k €', '15 – 35k €', '35k+ €', 'To define'],
      timelineLabel: 'Timeline',
      timelines: ['ASAP', '1 – 3 months', '3 – 6 months', 'Flexible'],
      step2title: 'Tell me who you are.',
      step2sub: 'I reply personally. No automated responses, no middlemen.',
      nameLabel: 'Full name',
      namePlaceholder: 'Jane Doe',
      emailLabel: 'Email',
      emailPlaceholder: 'jane@company.com',
      companyLabel: 'Company (optional)',
      companyPlaceholder: 'Acme Srl',
      messageLabel: 'Anything else?',
      messagePlaceholder: 'Context, references, constraints…',
      step3title: 'Privacy & consent',
      step3sub: 'Required before sending. Please read carefully.',
      privacyBoxTitle: 'Privacy notice (Art. 13 GDPR)',
      privacyText: `Data Controller: Fabio Calvosa, fabio@fabiocalvosa.com

Purpose & legal basis: The data provided (name, email, company, message) will be processed solely to respond to your collaboration request, on the basis of pre-contractual measures (Art. 6(1)(b) GDPR).

Retention: Data will be kept only as long as necessary to handle your request and, if a contractual relationship arises, to comply with applicable legal obligations.

Disclosure: Data will not be shared with or disclosed to third parties.

Your rights: You may at any time exercise your rights of access, rectification, erasure, restriction, portability and objection by writing to fabio@fabiocalvosa.com.

Supervisory Authority: You have the right to lodge a complaint with the Italian Data Protection Authority (www.garanteprivacy.it).`,
      privacyCheckLabel: 'I have read the privacy notice and consent to the processing of my personal data to respond to my request.',
      backBtn: '← Back',
      continueBtn: 'Continue →',
      sendBtn: 'Send brief →',
      sendingBtn: 'Sending…',
      errorMsg: 'Something went wrong. Please try again or write directly to fabio@fabiocalvosa.com.',
    },
    partner: {
      sectionLabelText: 'Partner',
      eyebrow: 'Two directions, one standard',
      titleA: 'A network of ',
      titleAccent: 'partnerships',
      titleB: 'I can offer, and be.',
      card1tag: 'Partner of · Artera',
      card1title: 'Professional hosting for reliable projects.',
      card1p1pre: "I'm a technical partner of ",
      card1p1strong: 'Artera',
      card1p1post: ', a provider of managed hosting and cloud services. For clients this means every website I deliver can land on infrastructure that is fast, monitored, and ',
      card1p1strong2: 'supported in Italian',
      card1p1tail: ', without juggling multiple vendors.',
      card1p2: "With Artera I handle the entire technical stack, from choosing the environment to publishing the project.",
      card1stack: ['Managed hosting', 'Cloud', 'Italian support', 'Performance', 'SLA'],
      card2tag: 'Partner for · Agencies',
      card2title: 'A reliable extension of your team.',
      card2p1pre: 'I also partner with ',
      card2p1strong: 'web and communication agencies',
      card2p1post: ' as an outsourced front-end and WordPress developer. I ship pixel-accurate interfaces from Figma, build custom themes and WooCommerce flows.',
      card2p2strong: 'White-label',
      card2p2post: ' and integrated into your workflow.',
      card2stack: ['Front-end', 'WordPress', 'WooCommerce', 'Figma → code', 'AI & Automation'],
    },
    help: {
      sectionLabelText: 'Let me help you',
      eyebrow: 'Ready when you are',
      copy1: "If you've read this far, ",
      copy2: 'chances are',
      copy3: " we're already thinking in the same language. ",
      copy4: 'Let me help you',
      copy5: ' build the digital side of your work, carefully.',
      ctaBtn: 'Shall we begin?',
      emailBtn: 'fabio@fabiocalvosa.com',
      note: 'Replies within 48h · Based in Italy',
    },
    footer: {
      tag: 'Freelance web designer & front-end developer. Partner of Artera for hosting and cloud. Working with companies and agencies.',
      location: 'Remote',
      col1: 'Contact',
      col2: 'Go to',
      col3: 'Elsewhere',
      col2links: [
        { label: 'Myself',        href: '#myself' },
        { label: 'Collaboration', href: '#collaboration' },
        { label: 'Partner',       href: '#partner' },
        { label: 'Let me help',   href: '#help' },
      ],
      copyright: '© 2026 Fabio Calvosa · P.IVA 02158150033',
      craft: 'Crafted in Italy · Hosted with Artera',
    },
    bio: {
      eyebrow: 'About',
      name: 'Fabio Calvosa',
      role: 'Freelance web designer & front-end developer',
      p1: "I'm a freelance web designer and front-end developer based in Italy. Over 20 years building the web: from early table layouts to AI-powered workflows. I work with companies and agencies in Italy and abroad.",
      p2: 'My work sits between strategy, design and development. I guide projects from the first conversation to launch: positioning, UX, WordPress and WooCommerce builds, AI integrations and ongoing care. Hosting and performance handled with Artera.',
      p3pre: 'I prefer ',
      p3strong: 'long, direct relationships',
      p3post: " over one-off transactions. Every project gets its own path, built around the client's tools, process and goals.",
      metaBasedIn: 'Based in',      metaBasedInVal: 'Italy · clients worldwide',
      metaAvail:   'Available',     metaAvailVal:   'Let\'s talk',
      metaLang:    'Languages',     metaLangVal:    'Italian · English',
      metaFocus:   'Focus',         metaFocusVal:   'WordPress · WooCommerce · AI',
      footerNote: 'fabiocalvosa.com',
      footerCta:  'Shall we begin?',
      notesEyebrow: 'Notes',
      notesText:    'Notes, reflections and field tests',
      notesCta:     'Read the notes →',
    },
    faq: {
      sectionLabelText: 'FAQ',
      eyebrow: 'Common questions',
      title: 'Straight answers.',
      items: [
        {
          q: 'How much does a professional website cost?',
          a: "Every project is different. The right and wisest answer, as always, is 'it depends.' We can discuss it openly during the initial brief by filling out the form above. No surprises.",
        },
        {
          q: 'How long does it take?',
          a: 'It depends on the scope and complexity of the project. More complex builds naturally require more work. Timeline is always agreed upfront.',
        },
        {
          q: 'Do you work with agencies?',
          a: "Yes. I partner with web and communication agencies as an outsourced front-end and WordPress developer: white-label and integrated into your workflow.",
        },
        {
          q: 'Do you work outside Italy?',
          a: 'Absolutely. I work remotely with clients and agencies. Most projects run entirely online, in Italian or English.',
        },
        {
          q: 'Can I hire you for just part of a project?',
          a: "Yes. Whether you need design only, development only, a technical review or ongoing support, I'm flexible. Tell me what you need in the brief.",
        },
      ],
    },
  },
  it: {
    langToggle: { label: 'switch to', flag: '🇬🇧' },
    nav: {
      myself: 'Chi sono',
      collaboration: 'Collaborazione',
      partner: 'Partner',
      faq: 'FAQ',
      help: 'Posso aiutarti',
    },
    hero: {
      eyebrow: 'Freelance · Web design, sviluppo e AI',
      h1a: 'Soluzioni web che integrano ',
      h1accent: 'AI e automazioni',
      h1b: ' dove servono.',
      ledeStrong: 'Servizi per aziende e agenzie.',
      ledeBodyPre: ' Costruisco siti, e-commerce e processi digitali integrando ',
      ledeBodyStrong: 'strumenti AI dove riducono i tempi e migliorano la qualità',
      ledeBodyPost: ' del lavoro.',
      ctaPrimary: 'Prenota la tua consulenza gratuita',
      ctaSecondary: 'Scopri di più ↓',
      scroll: 'Scorri ↓',
    },
    myself: {
      sectionLabelText: 'Chi sono',
      eyebrow: 'About',
      titleA: "Prima l'ascolto.",
      titleB: 'Poi',
      titleC: ' il codice.',
      bio1pre: 'Sono ',
      bio1name: 'Fabio Calvosa',
      bio1post: ", web designer e sviluppatore front-end freelance con base in Italia. Da ",
      bio1strongYears: "oltre vent'anni",
      bio1mid: ' aiuto piccoli team e aziende a trasformare il loro lavoro in ',
      bio1strongValues: 'siti e progetti digitali concreti e curati',
      bio1tail: '.',
      bio2pre: 'Il mio approccio inizia con una ',
      bio2strong: 'conversazione, non con un template',
      bio2post: ". Ogni progetto riceve un percorso su misura: dalla strategia e architettura dell'informazione, all'interfaccia, allo sviluppo e all'hosting.",
      bioParaPre: 'Un percorso iniziato nel 2005: dai layout a tabelle ai flussi con AI. ',
      bioParaStrong: 'Più di 80 progetti',
      bioParaPost: " realizzati per clienti in Italia e all'estero, adattandomi ogni volta agli strumenti, al processo e agli obiettivi del cliente.",
      skills: [
        ['Siti & e-commerce', 'WordPress · WooCommerce'],
        ['Front-end', 'pixel-accurate'],
        ['AI & automazione', 'agenti & workflow'],
        ['Consulenza & UX', 'strategia digitale'],
        ['Hosting', 'con Artera'],
      ],
    },
    collab: {
      sectionLabelText: 'Collaborazione',
      eyebrow: 'Lavoriamo insieme',
      titleA: 'Un ',
      titleAccent: 'brief',
      titleB: ', non un muro di domande.',
      descPre: 'Una conversazione strutturata in quattro passaggi. Inviami la tua richiesta,',
      descStrong1: ' compila il modulo',
      descMid: ' e risponderò ',
      descStrong2: 'entro due giorni lavorativi',
      descTail: ' con una valutazione preliminare.',
      steps: ['Tipo di progetto', 'Scope & budget', 'Chi sei', 'Privacy'],
      step0title: 'Cosa stai cercando?',
      step0sub: "Scegli l'opzione più vicina. Possiamo rifinire dopo.",
      kinds: ['Nuovo sito web', 'Restyling del sito', 'Negozio online', 'Consulenza', 'Collaborazione continuativa', 'AI & Automazione'],
      step1title: 'Di cosa hai bisogno?',
      step1sub: 'Approssimativo va bene. Niente è vincolante.',
      scopeLabel: 'Cosa è incluso',
      scopes: ['Strategia & consulenza', 'Design & identità visiva', 'Sviluppo del sito', 'CMS / WordPress', 'Hosting & manutenzione', 'Copywriting', 'SEO & visibilità'],
      budgetLabel: 'Budget indicativo',
      budgets: ['< 5k €', '5 – 15k €', '15 – 35k €', '35k+ €', 'Da definire'],
      timelineLabel: 'Tempistiche',
      timelines: ['Prima possibile', '1 – 3 mesi', '3 – 6 mesi', 'Flessibile'],
      step2title: 'Dimmi chi sei.',
      step2sub: 'Ti rispondo di persona. Nessun messaggio automatico, nessun intermediario.',
      nameLabel: 'Nome e cognome',
      namePlaceholder: 'Mario Rossi',
      emailLabel: 'Email',
      emailPlaceholder: 'mario@azienda.it',
      companyLabel: 'Azienda (opzionale)',
      companyPlaceholder: 'Acme Srl',
      messageLabel: 'Vuoi aggiungere altro?',
      messagePlaceholder: 'Contesto, riferimenti, vincoli…',
      step3title: 'Privacy & consenso',
      step3sub: "Necessario prima dell'invio. Leggila con cura.",
      privacyBoxTitle: 'Informativa (Art. 13 GDPR)',
      privacyText: `Titolare del trattamento: Fabio Calvosa, fabio@fabiocalvosa.com

Finalità e base giuridica: I dati forniti (nome, e-mail, azienda, messaggio) saranno trattati esclusivamente per rispondere alla tua richiesta di collaborazione, sulla base delle misure precontrattuali (art. 6, par. 1, lett. b GDPR).

Conservazione: I dati saranno conservati per il tempo necessario a gestire la tua richiesta e, in caso di rapporto contrattuale, per gli obblighi di legge applicabili.

Comunicazione: I dati non saranno ceduti a terzi né diffusi.

I tuoi diritti: Puoi esercitare in qualsiasi momento i diritti di accesso, rettifica, cancellazione, limitazione, portabilità e opposizione scrivendo a fabio@fabiocalvosa.com.

Autorità di controllo: Hai il diritto di presentare reclamo al Garante per la protezione dei dati personali (www.garanteprivacy.it).`,
      privacyCheckLabel: "Ho letto l'informativa e acconsento al trattamento dei miei dati personali per rispondere alla mia richiesta.",
      backBtn: '← Indietro',
      continueBtn: 'Continua →',
      sendBtn: 'Invia brief →',
      sendingBtn: 'Invio in corso…',
      errorMsg: 'Qualcosa è andato storto. Riprova o scrivimi direttamente a fabio@fabiocalvosa.com.',
    },
    partner: {
      sectionLabelText: 'Partner',
      eyebrow: 'Due direzioni, un solo standard',
      titleA: 'Una rete di ',
      titleAccent: 'partnership',
      titleB: 'che posso offrire, ed essere.',
      card1tag: 'Partner di · Artera',
      card1title: 'Hosting professionale per progetti affidabili.',
      card1p1pre: 'Sono partner tecnico di ',
      card1p1strong: 'Artera',
      card1p1post: ", provider di hosting gestito e servizi cloud. Per i clienti questo significa che ogni sito che realizzo può appoggiarsi a un'infrastruttura veloce, monitorata e ",
      card1p1strong2: 'supportata in italiano',
      card1p1tail: ', senza gestire più fornitori.',
      card1p2: "Con Artera gestisco l'intero stack tecnico, dalla scelta dell'ambiente alla pubblicazione del progetto.",
      card1stack: ['Hosting gestito', 'Cloud', 'Supporto italiano', 'Performance', 'SLA'],
      card2tag: 'Partner per · Agenzie',
      card2title: "Un'estensione affidabile del tuo team.",
      card2p1pre: 'Collaboro anche con ',
      card2p1strong: 'agenzie web e di comunicazione',
      card2p1post: ' come sviluppatore front-end e WordPress in outsourcing. Realizzo interfacce pixel-accurate da Figma, costruisco temi custom e flussi WooCommerce.',
      card2p2strong: 'White-label',
      card2p2post: ' e integrato nel tuo flusso di lavoro.',
      card2stack: ['Front-end', 'WordPress', 'WooCommerce', 'Figma → code', 'AI & Automazione'],
    },
    help: {
      sectionLabelText: 'Posso aiutarti',
      eyebrow: 'Sono pronto quando lo sei tu',
      copy1: 'Se hai letto fin qui, ',
      copy2: 'è probabile che',
      copy3: ' stiamo già pensando nella stessa lingua. ',
      copy4: 'Lascia che ti aiuti',
      copy5: ' a costruire il lato digitale del tuo lavoro, con cura.',
      ctaBtn: 'Iniziamo?',
      emailBtn: 'fabio@fabiocalvosa.com',
      note: 'Risposte entro 48h',
    },
    footer: {
      tag: 'Web designer e sviluppatore front-end freelance. Partner di Artera per hosting e cloud. Lavoro con aziende e agenzie.',
      col1: 'Contatti',
      col2: 'Vai a',
      col3: 'Altrove',
      col2links: [
        { label: 'Chi sono',       href: '#myself' },
        { label: 'Collaborazione', href: '#collaboration' },
        { label: 'Partner',        href: '#partner' },
        { label: 'Posso aiutarti', href: '#help' },
      ],
      copyright: '© 2026 Fabio Calvosa · P.IVA 02158150033',
      craft: 'Realizzato in Italia · Hosted con Artera',
    },
    bio: {
      eyebrow: 'Chi sono',
      name: 'Fabio Calvosa',
      role: 'Web designer & sviluppatore front-end freelance',
      p1: "Sono un web designer e sviluppatore front-end freelance con base in Italia. Inizio nel 2005: dai layout a tabelle ai flussi con AI. Lavoro con aziende e agenzie in Italia e all'estero.",
      p2: "Il mio lavoro si colloca tra strategia, design e sviluppo. Seguo i progetti dalla prima conversazione al lancio: posizionamento, UX, build WordPress e WooCommerce, integrazioni AI e cura continuativa. Hosting e performance gestiti con Artera.",
      p3pre: 'Preferisco ',
      p3strong: 'relazioni lunghe e dirette',
      p3post: '. Ogni progetto riceve un percorso costruito intorno agli strumenti, al processo e agli obiettivi del cliente.',
      metaBasedIn: 'Sede in',   metaBasedInVal: 'Italia · clienti in tutto il mondo',
      metaAvail:   'Disponibile', metaAvailVal:   'Parliamoci',
      metaLang:    'Lingue',      metaLangVal:    'Italiano · Inglese',
      metaFocus:   'Focus',       metaFocusVal:   'WordPress · WooCommerce · AI',
      footerNote: 'fabiocalvosa.com',
      footerCta:  'Iniziamo?',
      notesEyebrow: 'Notes',
      notesText:    'Appunti, riflessioni e prove di campo',
      notesCta:     'Leggi le note →',
    },
    faq: {
      sectionLabelText: 'FAQ',
      eyebrow: 'Domande frequenti',
      title: 'Risposte dirette.',
      items: [
        {
          q: 'Quanto costa un sito web professionale?',
          a: "Ogni progetto è diverso. La risposta giusta e più saggia è come sempre 'dipende'. Possiamo parlarne apertamente nel brief iniziale, compilando il modulo che trovi sopra. Nessuna sorpresa.",
        },
        {
          q: 'Quanto tempo ci vuole per realizzare un sito web?',
          a: "Dipende dallo scope e dalla complessità del progetto. Le build più complesse richiedono naturalmente più lavoro. Le tempistiche vengono concordate prima di iniziare.",
        },
        {
          q: 'Lavori anche con le agenzie?',
          a: "Sì. Collaboro con agenzie web e di comunicazione come sviluppatore front-end e WordPress in outsourcing: white-label e integrato nel tuo flusso di lavoro.",
        },
        {
          q: 'Lavori solo in Italia?',
          a: "Lavoro anche con clienti all'estero (Finlandia e Australia, per esempio). Lavoro da remoto con clienti e agenzie. La maggior parte dei progetti si svolge interamente online, in italiano o in inglese.",
        },
        {
          q: 'Posso affidarti solo una parte del progetto?',
          a: "Sì. Che tu abbia bisogno solo del design, solo dello sviluppo, di una revisione tecnica o di supporto continuativo, posso adattarmi. Descrivi cosa ti serve nel brief.",
        },
      ],
    },
  },
};

/* ============ Language Switcher ============ */
function LanguageSwitcher({ lang, onToggle }) {
  const t = T[lang].langToggle;
  return (
    <button
      type="button"
      className="lang-switcher"
      onClick={onToggle}
      aria-label={`${t.label} ${t.flag}`}
    >
      <span className="lang-label">{t.label}</span>
      <span className="lang-flag">{t.flag}</span>
    </button>
  );
}

/* ============ FAQ ============ */
function Faq({ lang }) {
  const t = T[lang].faq;
  const [open, setOpen] = useState(null);
  const toggle = (i) => setOpen(open === i ? null : i);
  return (
    <section id="faq" data-section-index="4" data-screen-label="05 FAQ">
      <div className="section-label"><span className="num">04</span> {t.sectionLabelText}</div>
      <div className="container">
        <div className="faq-wrap">
          <div className="faq-intro">
            <div className="eyebrow">{t.eyebrow}</div>
            <h2 className="section-title">{t.title}</h2>
          </div>
          <ul className="faq-list">
            {t.items.map((item, i) => (
              <li key={i} className={`faq-item ${open === i ? 'open' : ''}`}>
                <button
                  type="button"
                  className="faq-question"
                  onClick={() => toggle(i)}
                  aria-expanded={open === i}
                >
                  <span>{item.q}</span>
                  <span className="faq-icon" aria-hidden="true">{open === i ? '−' : '+'}</span>
                </button>
                <div className="faq-answer" aria-hidden={open !== i}>
                  <p>{item.a}</p>
                </div>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
}

/* ============ Preloader: rimuove il preloader statico HTML ============ */
function hideStaticPreloader() {
  const el = document.getElementById('static-preloader');
  if (!el) return;
  el.classList.add('hidden');
  el.addEventListener('transitionend', () => el.remove(), { once: true });
}

/* ============ Bottom Nav ============ */
function BottomNav({ lang }) {
  const t = T[lang].nav;
  const [active, setActive] = useState('hero');
  const navRef = useRef(null);
  useEffect(() => {
    const onScroll = () => {
      const sections = ['hero', 'myself', 'collaboration', 'partner', 'faq', 'help'];
      let current = 'hero';
      for (const id of sections) {
        const el = document.getElementById(id);
        if (!el) continue;
        const r = el.getBoundingClientRect();
        if (r.top <= window.innerHeight * 0.5) current = id;
      }
      setActive(current);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Quando la voce attiva cambia, se la nav ha overflow orizzontale (mobile),
  // ricentro la voce attiva all'interno della pillola. Calcolo manuale
  // dello scrollLeft per agire SOLO sul contenitore interno e non sulla pagina.
  useEffect(() => {
    const nav = navRef.current;
    if (!nav) return;
    if (nav.scrollWidth <= nav.clientWidth) return; // niente overflow → no-op
    const btn = nav.querySelector('.nav-item.active');
    if (!btn) return;
    const navRect = nav.getBoundingClientRect();
    const btnRect = btn.getBoundingClientRect();
    const offset = (btnRect.left - navRect.left) - (navRect.width / 2) + (btnRect.width / 2);
    nav.scrollTo({ left: nav.scrollLeft + offset, behavior: 'smooth' });
  }, [active]);

  const items = [
    { id: 'myself',        label: t.myself },
    { id: 'collaboration', label: t.collaboration },
    { id: 'partner',       label: t.partner },
    { id: 'faq',           label: t.faq },
    { id: 'help',          label: t.help },
  ];
  const jump = (id) => {
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 20, behavior: 'smooth' });
  };
  return (
    <nav className="bottom-nav" aria-label="Primary" ref={navRef}>
      {items.map((it) => (
        <button
          key={it.id}
          className={`nav-item ${active === it.id ? 'active' : ''}`}
          onClick={() => jump(it.id)}
        >
          <span className="dot" />
          {it.label}
        </button>
      ))}
    </nav>
  );
}

/* ============ Hero ============ */
function Hero({ lang, onOpenCalModal }) {
  const t = T[lang].hero;
  const scrollDown = () => {
    const el = document.getElementById('myself');
    if (el) window.scrollTo({ top: el.offsetTop - 20, behavior: 'smooth' });
  };
  return (
    <section id="hero" className="hero" data-section-index="0" data-screen-label="01 Hero">
      <div className="container">
        <div className="reveal in" style={{ maxWidth: 1100 }}>
          <div className="eyebrow">{t.eyebrow}</div>
          <h1>
            {t.h1a}<span className="accent">{t.h1accent}</span>{t.h1b}
          </h1>
          <p className="lede">
            <strong>{t.ledeStrong}</strong>{t.ledeBodyPre}<strong>{t.ledeBodyStrong}</strong>{t.ledeBodyPost}
          </p>
          <div className="hero-ctas">
            <button
              type="button"
              className="cta-primary"
              onClick={onOpenCalModal}
            >
              {t.ctaPrimary}
            </button>
            <button type="button" className="cta-secondary" onClick={scrollDown}>
              {t.ctaSecondary}
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ Myself ============ */
function Myself({ lang }) {
  const t = T[lang].myself;
  return (
    <section id="myself" data-section-index="1" data-screen-label="02 Myself">
      <div className="section-label"><span className="num">01</span> {t.sectionLabelText}</div>
      <div className="container">
        <div className="myself-grid">
          <div>
            <div className="eyebrow">{t.eyebrow}</div>
            <h2 className="section-title">
              {t.titleA}<br />
              <span className="accent">{t.titleB}</span>{t.titleC}
            </h2>
            <div className="myself-bio">
              <p>
                {t.bio1pre}<strong>{t.bio1name}</strong>{t.bio1post}<strong>{t.bio1strongYears}</strong>{t.bio1mid}<strong>{t.bio1strongValues}</strong>{t.bio1tail}
              </p>
              <p>{t.bio2pre}<strong>{t.bio2strong}</strong>{t.bio2post}</p>
            </div>
          </div>
          <div>
            <ul className="skills-list">
              {t.skills.map(([k, v]) => (
                <li key={k}>{k}<span>{v}</span></li>
              ))}
            </ul>
            <p className="myself-bio-para">{t.bioParaPre}<strong>{t.bioParaStrong}</strong>{t.bioParaPost}</p>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ Collaboration: multi-step form ============ */
function Collaboration({ lang }) {
  const t = T[lang].collab;
  const [step, setStep] = useState(0);
  const [form, setForm] = useState({
    kinds: [], scope: [], budget: '', timeline: '',
    name: '', email: '', company: '', message: '',
    privacyAccepted: false,
  });
  const [sending, setSending] = useState(false);
  const [sendError, setSendError] = useState('');
  const [formToken, setFormToken] = useState('');

  // Recupera un token anti-bot all'apertura della pagina.
  useEffect(() => {
    let alive = true;
    fetch('form-token.php')
      .then((r) => r.json())
      .then((d) => { if (alive && d && d.token) setFormToken(d.token); })
      .catch(() => {});
    return () => { alive = false; };
  }, []);

  const steps = t.steps.map((label, i) => ({
    key: ['project', 'scope', 'about', 'privacy'][i],
    label,
  }));

  const toggleKind = (v) => {
    setForm((f) => ({
      ...f,
      kinds: f.kinds.includes(v) ? f.kinds.filter((x) => x !== v) : [...f.kinds, v],
    }));
  };

  const toggleScope = (v) => {
    setForm((f) => ({
      ...f,
      scope: f.scope.includes(v) ? f.scope.filter((x) => x !== v) : [...f.scope, v],
    }));
  };

  const canNext = () => {
    if (step === 0) return form.kinds.length > 0;
    if (step === 1) return form.scope.length > 0 && !!form.budget && !!form.timeline;
    if (step === 2) return !!form.name && /^\S+@\S+\.\S+$/.test(form.email);
    if (step === 3) return form.privacyAccepted && !sending;
    return true;
  };

  const handleNext = async () => {
    if (step < 3) {
      setStep(step + 1);
      return;
    }
    // Step 3: submit
    setSending(true);
    setSendError('');
    try {
      const res = await fetch('send-brief.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          kinds:    form.kinds,
          scope:    form.scope,
          budget:   form.budget,
          timeline: form.timeline,
          name:     form.name,
          email:    form.email,
          company:  form.company,
          message:  form.message,
          lang,
          token:    formToken,
        }),
      });
      const data = await res.json();
      if (data.success) {
        window.location.href = 'thankyou.html?lang=' + lang;
      } else {
        setSendError(t.errorMsg);
        setSending(false);
      }
    } catch (e) {
      setSendError(t.errorMsg);
      setSending(false);
    }
  };

  const progressPct = Math.min(100, (step / (steps.length - 1)) * 100);

  return (
    <section id="collaboration" data-section-index="2" data-screen-label="03 Collaboration">
      <div className="section-label"><span className="num">02</span> {t.sectionLabelText}</div>
      <div className="container">
        <div className="collab-wrap">
          <div className="collab-intro">
            <div className="eyebrow">{t.eyebrow}</div>
            <h2 className="section-title">
              {t.titleA}<span className="accent">{t.titleAccent}</span>{t.titleB}
            </h2>
            <p>{t.descPre}<strong>{t.descStrong1}</strong>{t.descMid}<strong>{t.descStrong2}</strong>{t.descTail}</p>
          </div>

          <div className="collab-form-col">
            <div className="form-card">
              <div style={{
                position: 'absolute', top: 0, left: 0, height: 2,
                width: `${progressPct}%`, background: 'var(--primary)',
                transition: 'width 0.5s cubic-bezier(.2,.7,.2,1)',
              }} />
              <div className="form-header">
                <span>Step {String(step + 1).padStart(2, '0')} / {String(steps.length).padStart(2, '0')}</span>
                <span>{steps[step].label}</span>
              </div>

              {step === 0 && (
                <div>
                  <div className="form-step-title">{t.step0title}</div>
                  <div className="form-step-sub">{t.step0sub}</div>
                  <div className="form-chips" style={{ marginBottom: 8 }}>
                    {t.kinds.map((k) => (
                      <div
                        key={k}
                        className={`chip ${form.kinds.includes(k) ? 'selected' : ''}`}
                        onClick={() => toggleKind(k)}
                      >{k}</div>
                    ))}
                  </div>
                </div>
              )}

              {step === 1 && (
                <div>
                  <div className="form-step-title">{t.step1title}</div>
                  <div className="form-step-sub">{t.step1sub}</div>
                  <div className="form-row">
                    <label className="form-label">{t.scopeLabel}</label>
                    <div className="form-chips">
                      {t.scopes.map((k) => (
                        <div
                          key={k}
                          className={`chip ${form.scope.includes(k) ? 'selected' : ''}`}
                          onClick={() => toggleScope(k)}
                        >{k}</div>
                      ))}
                    </div>
                  </div>
                  <div className="form-row">
                    <label className="form-label">{t.budgetLabel}</label>
                    <div className="form-chips">
                      {t.budgets.map((k) => (
                        <div
                          key={k}
                          className={`chip ${form.budget === k ? 'selected' : ''}`}
                          onClick={() => setForm({ ...form, budget: k })}
                        >{k}</div>
                      ))}
                    </div>
                  </div>
                  <div className="form-row">
                    <label className="form-label">{t.timelineLabel}</label>
                    <div className="form-chips">
                      {t.timelines.map((k) => (
                        <div
                          key={k}
                          className={`chip ${form.timeline === k ? 'selected' : ''}`}
                          onClick={() => setForm({ ...form, timeline: k })}
                        >{k}</div>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {step === 2 && (
                <div>
                  <div className="form-step-title">{t.step2title}</div>
                  <div className="form-step-sub">{t.step2sub}</div>
                  <div className="form-row">
                    <label className="form-label">{t.nameLabel}</label>
                    <input className="form-input" value={form.name}
                           onChange={(e) => setForm({ ...form, name: e.target.value })}
                           placeholder={t.namePlaceholder} />
                  </div>
                  <div className="form-row">
                    <label className="form-label">{t.emailLabel}</label>
                    <input className="form-input" value={form.email}
                           onChange={(e) => setForm({ ...form, email: e.target.value })}
                           placeholder={t.emailPlaceholder} type="email" />
                  </div>
                  <div className="form-row">
                    <label className="form-label">{t.companyLabel}</label>
                    <input className="form-input" value={form.company}
                           onChange={(e) => setForm({ ...form, company: e.target.value })}
                           placeholder={t.companyPlaceholder} />
                  </div>
                  <div className="form-row">
                    <label className="form-label">{t.messageLabel}</label>
                    <textarea className="form-textarea" value={form.message}
                           onChange={(e) => setForm({ ...form, message: e.target.value })}
                           placeholder={t.messagePlaceholder} />
                  </div>
                </div>
              )}

              {step === 3 && (
                <div>
                  <div className="form-step-title">{t.step3title}</div>
                  <div className="form-step-sub">{t.step3sub}</div>
                  <div className="privacy-box">
                    <strong className="privacy-box-title">{t.privacyBoxTitle}</strong>
                    <p style={{ whiteSpace: 'pre-line' }}>{t.privacyText}</p>
                  </div>
                  <label className="privacy-check-label">
                    <input
                      type="checkbox"
                      checked={form.privacyAccepted}
                      onChange={(e) => setForm({ ...form, privacyAccepted: e.target.checked })}
                    />
                    <span>{t.privacyCheckLabel}</span>
                  </label>
                </div>
              )}

              {sendError && (
                <div className="form-error">{sendError}</div>
              )}

              <div className="form-actions">
                <button
                  className="btn btn-ghost"
                  onClick={() => setStep(Math.max(0, step - 1))}
                  disabled={step === 0 || sending}
                >
                  {t.backBtn}
                </button>
                <button
                  className="btn btn-primary"
                  onClick={handleNext}
                  disabled={!canNext()}
                >
                  {step === 3
                    ? (sending ? t.sendingBtn : t.sendBtn)
                    : t.continueBtn}
                </button>
              </div>
            </div>

            <ul className="step-track">
              {steps.map((s, i) => (
                <li
                  key={s.key}
                  className={`step-track-item ${step === i ? 'active' : ''} ${step > i ? 'done' : ''}`}
                >
                  <span className="num">{step > i ? '✓' : String(i + 1).padStart(2, '0')}</span>
                  {s.label}
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ Partner ============ */
function PartnerCard({ tag, title, children, stack }) {
  return (
    <div className="partner-card">
      <span className="partner-tag">{tag}</span>
      <h3>{title}</h3>
      {children}
      <div className="partner-stack">
        {stack.map((s) => <span key={s} className="stack-chip">{s}</span>)}
      </div>
    </div>
  );
}

function Partner({ lang }) {
  const t = T[lang].partner;
  return (
    <section id="partner" data-section-index="3" data-screen-label="04 Partner">
      <div className="section-label"><span className="num">03</span> {t.sectionLabelText}</div>
      <div className="container">
        <div className="eyebrow">{t.eyebrow}</div>
        <h2 className="section-title">
          {t.titleA}<span className="accent">{t.titleAccent}</span><br />
          {t.titleB}
        </h2>
        <div className="partner-split">
          <PartnerCard tag={t.card1tag} title={t.card1title} stack={t.card1stack}>
            <p>
              {t.card1p1pre}<strong>{t.card1p1strong}</strong>{t.card1p1post}<strong>{t.card1p1strong2}</strong>{t.card1p1tail}
            </p>
            <p>{t.card1p2}</p>
          </PartnerCard>

          <PartnerCard tag={t.card2tag} title={t.card2title} stack={t.card2stack}>
            <p>
              {t.card2p1pre}<strong>{t.card2p1strong}</strong>{t.card2p1post}
            </p>
            <p><strong>{t.card2p2strong}</strong>{t.card2p2post}</p>
          </PartnerCard>
        </div>
      </div>
    </section>
  );
}

/* ============ Help / CTA ============ */
function Help({ lang }) {
  const t = T[lang].help;
  return (
    <section id="help" className="help" data-section-index="5" data-screen-label="06 Help">
      <div className="section-label"><span className="num">05</span> {t.sectionLabelText}</div>
      <div className="container">
        <div className="eyebrow" style={{ justifyContent: 'center' }}>{t.eyebrow}</div>
        <p className="help-copy">
          {t.copy1}<span className="mute">{t.copy2}</span>{t.copy3}
          <span className="accent">{t.copy4}</span>
          {' '}<span className="mute">{t.copy5}</span>
        </p>
        <div className="help-cta-row">
          <button className="btn btn-primary help-btn"
                  onClick={() => document.getElementById('collaboration').scrollIntoView({ behavior: 'smooth' })}>
            {t.ctaBtn}
          </button>
          <a href="mailto:fabio@fabiocalvosa.com" className="btn btn-ghost help-btn">
            {t.emailBtn}
          </a>
        </div>
        <div className="help-note">{t.note}</div>
      </div>
    </section>
  );
}

/* ============ Footer ============ */
function Footer({ lang }) {
  const t = T[lang].footer;

  const smoothScroll = (e, href) => {
    const id = href.replace('#', '');
    const el = document.getElementById(id);
    if (el) {
      e.preventDefault();
      window.scrollTo({ top: el.offsetTop - 20, behavior: 'smooth' });
    }
  };

  return (
    <footer className="site-footer">
      <div className="footer-grid">
        <div>
          <div className="footer-brand">
            <img src="assets/logo.png" alt="Fabio Calvosa" />
            <span className="footer-brand-name">Fabio Calvosa</span>
          </div>
          <p className="footer-tag">{t.tag}</p>
        </div>
        <div className="footer-col">
          <h4>{t.col1}</h4>
          <ul>
            <li><a href="mailto:fabio@fabiocalvosa.com">fabio@fabiocalvosa.com</a></li>
            <li><a href="tel:+393471554614">+39 347 155 4614</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h4>{t.col2}</h4>
          <ul>
            {t.col2links.map((l) => (
              <li key={l.href}>
                <a href={l.href} onClick={(e) => smoothScroll(e, l.href)}>{l.label}</a>
              </li>
            ))}
          </ul>
        </div>
        <div className="footer-col">
          <h4>{t.col3}</h4>
          <ul>
            <li><a href="https://www.linkedin.com/in/fabiocalvosa/" target="_blank" rel="noopener noreferrer">LinkedIn ↗</a></li>
            <li><a href="https://wa.me/393471554614" target="_blank" rel="noopener noreferrer">WhatsApp ↗</a></li>
            <li><a href="https://www.instagram.com/fabiocalvosa" target="_blank" rel="noopener noreferrer">Instagram ↗</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>{t.copyright}</span>
        <a
          href="https://admin.artera.net/auth/signup?afid=55985&aftk=XRpBfG8TlPhr0_Cx_SnFUM2HoPF5hNvyBINIckriG_Q"
          target="_blank"
          rel="noopener noreferrer"
          className="artera-badge"
        >
          <img
            src="https://resources.artera.net/brand/artera-partnerbadge-horizontal.svg"
            alt="Artera Partner"
            width="180"
            style={{ filter: 'brightness(0) invert(1)', opacity: 0.6 }}
          />
        </a>
      </div>
    </footer>
  );
}

/* ============ Bio Drawer ============ */
function BioDrawer({ open, onClose, lang }) {
  const t = T[lang].bio;
  return (
    <>
      <div
        className={`drawer-scrim ${open ? 'open' : ''}`}
        onClick={onClose}
        aria-hidden={!open}
      />
      <aside
        className={`bio-drawer ${open ? 'open' : ''}`}
        role="dialog"
        aria-modal="true"
        aria-label={`About ${t.name}`}
      >
        <div className="bio-drawer-inner">
          <button className="drawer-close" type="button" onClick={onClose} aria-label="Close bio">
            ✕
          </button>

          <div className="bio-portrait">
            <img src="assets/pfp.svg" alt={`${t.name} portrait illustration`} />
          </div>

          <div className="bio-eyebrow">{t.eyebrow}</div>
          <h3 className="bio-name">{t.name}</h3>
          <div className="bio-role">{t.role}</div>

          <div className="bio-body">
            <p>{t.p1}</p>
            <p>{t.p2}</p>
            <p>{t.p3pre}<strong>{t.p3strong}</strong>{t.p3post}</p>
          </div>

          <dl className="bio-meta">
            <div><dt>{t.metaBasedIn}</dt><dd>{t.metaBasedInVal}</dd></div>
            <div><dt>{t.metaAvail}</dt><dd>{t.metaAvailVal}</dd></div>
            <div><dt>{t.metaLang}</dt><dd>{t.metaLangVal}</dd></div>
            <div><dt>{t.metaFocus}</dt><dd>{t.metaFocusVal}</dd></div>
          </dl>

          <a className="bio-notes-card" href={`/${lang}/notes/`}>
            <div className="bio-notes-eyebrow">{t.notesEyebrow}</div>
            <div className="bio-notes-text">{t.notesText}</div>
            <div className="bio-notes-cta">{t.notesCta}</div>
          </a>

          <div className="bio-footer">
            <span>{t.footerNote}</span>
            <a href="#collaboration" onClick={onClose}>{t.footerCta}</a>
          </div>
        </div>
      </aside>
    </>
  );
}

/* ============ Cal.com Modal ============ */
function CalModal({ open, onClose, lang }) {
  const calUrl = 'https://cal.com/fabio-calvosa-pkzz0l/30min';
  const iframeSrc = `${calUrl}?embed=true&theme=dark&hideEventTypeDetails=false`;
  const ariaLabel = lang === 'it' ? 'Chiudi prenotazione' : 'Close booking';

  return (
    <>
      <div
        className={`drawer-scrim ${open ? 'open' : ''}`}
        onClick={onClose}
        aria-hidden={!open}
      />
      <aside
        className={`cal-modal ${open ? 'open' : ''}`}
        role="dialog"
        aria-modal="true"
        aria-hidden={!open}
        aria-label="Calendar booking"
      >
        <button
          className="cal-close"
          type="button"
          onClick={onClose}
          aria-label={ariaLabel}
        >
          ×
        </button>
        <div className="cal-iframe-wrap">
          {open && (
            <iframe
              src={iframeSrc}
              title="Cal.com booking"
              frameBorder="0"
              allow="camera; microphone; fullscreen"
              loading="lazy"
            ></iframe>
          )}
        </div>
      </aside>
    </>
  );
}

/* ============ App ============ */
function App() {
  const [lang, setLang] = useState('it');
  const [bioOpen, setBioOpen] = useState(false);
  const [calOpen, setCalOpen] = useState(false);

  const toggleLang = () => setLang((l) => (l === 'en' ? 'it' : 'en'));

  // Rimuove il preloader statico HTML appena React monta e dipinge
  useEffect(() => {
    requestAnimationFrame(() => {
      setTimeout(hideStaticPreloader, 200);
    });
  }, []);

  // Sync <html lang=""> with current language for accessibility and SEO crawlers
  useEffect(() => {
    document.documentElement.lang = lang;
  }, [lang]);

  useEffect(() => {
    requestAnimationFrame(() => {
      if (window.__initScrollFx) window.__initScrollFx();
      // Refresh after a short delay to ensure FAQ section is in the layout
      setTimeout(() => {
        if (window.ScrollTrigger) window.ScrollTrigger.refresh();
      }, 400);
    });
  }, []);

  useEffect(() => {
    document.body.style.overflow = bioOpen ? 'hidden' : '';
    const onKey = (e) => { if (e.key === 'Escape') setBioOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [bioOpen]);

  useEffect(() => {
    // Quando uno dei due overlay è aperto, blocca lo scroll del body
    document.body.style.overflow = (bioOpen || calOpen) ? 'hidden' : '';
    const onKey = (e) => { if (e.key === 'Escape') setCalOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [calOpen, bioOpen]);

  return (
    <>
      <header className="site-header">
        <a href="#hero" aria-label="Fabio Calvosa home">
          <img src="assets/logo.png" alt="Fabio Calvosa logo" className="logo-mark" />
        </a>
        <button
          type="button"
          className={`profile-mark ${bioOpen ? 'active' : 'pulse-ring'}`}
          aria-label="Open Fabio's bio"
          aria-expanded={bioOpen}
          onClick={() => setBioOpen(true)}
        >
          <img src="assets/pfp.svg" alt="Fabio profile illustration" />
        </button>
      </header>

      <BioDrawer open={bioOpen} onClose={() => setBioOpen(false)} lang={lang} />
      <CalModal open={calOpen} onClose={() => setCalOpen(false)} lang={lang} />

      <main>
        <Hero lang={lang} onOpenCalModal={() => setCalOpen(true)} />
        <Myself lang={lang} />
        <Collaboration lang={lang} />
        <Partner lang={lang} />
        <Faq lang={lang} />
        <Help key={lang} lang={lang} />
      </main>

      <Footer lang={lang} />
      <BottomNav lang={lang} />
      <LanguageSwitcher lang={lang} onToggle={toggleLang} />
    </>
  );
}

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