// sections-top.jsx — Navbar, Hero, Capabilities marquee, Servizi, Portfolio
// All copy in Italian. Companion to styles.css design system v2.

// ── NAVBAR ──────────────────────────────────────────────────────────────────
function Navbar({ onDemoClick, palette }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const on = () => setScrolled(window.scrollY > 12);
    on();
    window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);

  const here = typeof location !== 'undefined' ? location.pathname.split('/').pop() : '';
  const isHome = !here || here === 'index.html';

  const links = [
    ['Servizi',        'servizi.html',   ['servizi.html']],
    ['Portfolio',      'portfolio.html', ['portfolio.html']],
    ['Processo',       'processo.html',  ['processo.html']],
    ['Prodotti',       'prodotti.html',  ['prodotti.html','domusflow.html','lexai.html','metaagent.html']],
    ['Stack',          'stack.html',     ['stack.html']],
    ['Tool',           'tools.html',     ['tools.html']],
  ];

  const go = (href) => (e) => {
    if (href.startsWith('#')) {
      e.preventDefault();
      const el = document.querySelector(href);
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
    setOpen(false);
  };

  return (
    <header className={'nav ' + (scrolled ? 'is-scrolled' : '')}>
      <div className="nav-inner">
        <a href={isHome ? '#top' : 'index.html'} className="brand"
           onClick={isHome ? go('#top') : undefined} aria-label="MetaWeb Studio  home">
          <Logo />
          <span className="brand-name">MetaWeb Studio</span>
        </a>
        <nav className="nav-links" aria-label="primary">
          {links.map(([label, href, match]) => (
            <a key={label} href={href}
               className={match && match.includes(here) ? 'is-active' : ''}
               onClick={go(href)}>{label}</a>
          ))}
        </nav>
        <div className="nav-cta">
          <ThemeToggle palette={palette}/>
          <a className="btn btn-grad btn-sm" href="contatti.html">
            Prenota demo
            <Icon name="arrow" size={14}/>
          </a>
          <button className="nav-burger" aria-label="Menu" onClick={() => setOpen(o => !o)}>
            <Icon name={open ? 'x' : 'menu'} size={20}/>
          </button>
        </div>
      </div>
      {open && (
        <div className="nav-mobile-open">
          {links.map(([label, href]) => (
            <a key={label} href={href} onClick={go(href)}>{label}</a>
          ))}
          <a className="btn btn-grad" href="contatti.html">Prenota demo</a>
        </div>
      )}
    </header>
  );
}

// Logo mark using the official PNG asset
function Logo({ size = 32 }) {
  return (
    <span className="logo-mark" style={{
      width: size, height: size, display: 'inline-block', flexShrink: 0,
    }}>
      <img src="logo-mark.png" alt="MetaWeb Studio"
           width={size} height={size}
           style={{ width: '100%', height: '100%', display: 'block', objectFit: 'contain' }}/>
    </span>
  );
}

// ── HERO ────────────────────────────────────────────────────────────────────
function Hero({ onDemoClick }) {
  return (
    <section id="top" className="hero">
      <div className="hero-bg" aria-hidden></div>
      <div className="hero-grid" aria-hidden></div>
      <ParticleField count={48} opacity={0.45}/>

      <div className="container hero-inner">
        <div className="hero-mark">
          <span className="dot-live"></span>
          Software studio · Napoli, Italia
        </div>

        <h1 className="hero-name">
          <span className="row-1">
            <WordReveal step={80}>MetaWeb</WordReveal>
          </span>
          <span className="row-2">
            <WordReveal step={80} baseDelay={420}>
              <em>Studio</em>
            </WordReveal>
          </span>
        </h1>

        <p className="hero-sub mo-reveal is-in" style={{ '--mo-delay': '900ms' }}>
          Progettiamo e costruiamo SaaS AI-native, siti web premium e
          automazioni intelligenti per aziende e professionisti.
        </p>

        <div className="hero-cta mo-reveal is-in" style={{ '--mo-delay': '1050ms' }}>
          <Magnetic strength={0.15}>
            <a href="contatti.html" className="btn btn-grad btn-lg">
              Inizia un progetto <Icon name="arrow" size={16}/>
            </a>
          </Magnetic>
          <Magnetic strength={0.12}>
            <a href="portfolio.html" className="btn btn-outline btn-lg">
              Vedi il portfolio
            </a>
          </Magnetic>
        </div>

        <div className="hero-foot mo-reveal is-in" style={{ '--mo-delay': '1200ms' }}>
          <span><Icon name="check" size={14}/> SaaS in produzione</span>
          <span><Icon name="check" size={14}/> Stack moderno</span>
          <span><Icon name="check" size={14}/> Approccio AI-first</span>
          <span><Icon name="check" size={14}/> Hosting EU · GDPR</span>
        </div>
      </div>

      <div className="scroll-cue" aria-hidden>Scroll</div>
    </section>
  );
}

// ── CAPABILITIES MARQUEE ────────────────────────────────────────────────────
function Capabilities() {
  // Mixed styling: solid + outlined + italic gradient, separated by stars.
  const items = [
    { text: 'SaaS', kind: 'solid' },
    { text: 'AI native', kind: 'outline' },
    { text: 'web design', kind: 'italic' },
    { text: 'automation', kind: 'solid' },
    { text: 'CRM', kind: 'outline' },
    { text: 'voice AI', kind: 'italic' },
    { text: 'agents', kind: 'solid' },
    { text: 'product', kind: 'outline' },
  ];
  const renderItem = (it, key) => {
    const cls = 'cap-item ' + (
      it.kind === 'outline' ? 'cap-item-outline' :
      it.kind === 'italic'  ? 'cap-item-accent' : ''
    );
    return (
      <span key={key} className={cls}>
        <span>{it.text}</span>
        <span className="cap-star">✦</span>
      </span>
    );
  };
  return (
    <section className="capabilities" aria-label="Cosa facciamo">
      <Marquee speed={60}>
        {items.map((it, i) => renderItem(it, i))}
      </Marquee>
    </section>
  );
}

// ── SERVIZI (homepage) ──────────────────────────────────────────────────────
function Servizi() {
  const items = [
    {
      icon: 'cube',
      title: 'Sviluppo SaaS',
      body: "Piattaforme web multi-tenant, autenticazione, pagamenti, dashboard. Architetture solide pronte per scalare.",
      tags: ['Next.js', 'Supabase', 'Stripe'],
    },
    {
      icon: 'globe',
      title: 'Siti web premium',
      body: "Marketing site, landing alta conversione, vetrine aziendali. Performance Lighthouse al primo deploy.",
      tags: ['Marketing', 'CMS', 'SEO'],
    },
    {
      icon: 'sparkle',
      title: 'AI & Agenti',
      body: "Assistenti, agenti vocali, RAG, tool calling. AI integrata dove crea valore reale.",
      tags: ['LLM', 'RAG', 'Voice'],
    },
    {
      icon: 'bolt',
      title: 'Automazioni',
      body: "Workflow automatizzati per email, lead, report, processi ripetitivi. Risparmi ore, riduci errori.",
      tags: ['n8n', 'Make', 'Custom'],
    },
    {
      icon: 'layers',
      title: 'CRM su misura',
      body: "Pipeline, contatti, automazioni commerciali. Integrazione email e WhatsApp Business.",
      tags: ['Pipeline', 'Email', 'WhatsApp'],
    },
    {
      icon: 'compass',
      title: 'Consulenza & MVP',
      body: "Dall'idea al prototipo funzionante in tempi record. Validi sul mercato prima di investire mesi.",
      tags: ['MVP', 'Discovery', 'Sprint'],
    },
  ];
  return (
    <section id="servizi" className="section">
      <div className="container">
        <header className="sh">
          <div className="sh-l">
            <span className="eyebrow">Servizi</span>
            <h2 className="display-m">
              Cosa <em style={{ fontStyle: 'normal', background: 'var(--gradient)', WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent' }}>costruiamo</em> per te.
            </h2>
          </div>
          <div className="sh-r">
            <p className="lead">
              Dal SaaS al CRM verticale, dalle automazioni al sito vetrina premium:
              sei modi in cui possiamo lavorare insieme.
            </p>
            <a href="servizi.html" className="link-arrow" style={{ marginTop: 20 }}>
              Tutti i servizi <Icon name="arrow" size={14}/>
            </a>
          </div>
        </header>

        <div className="services-grid">
          {items.map((it, i) => (
            <article key={it.title} className="service">
              <span className="service-icon"><Icon name={it.icon} size={32}/></span>
              <div className="service-num">{String(i + 1).padStart(2, '0')}</div>
              <h3 className="service-title">{it.title}</h3>
              <p className="service-body">{it.body}</p>
              <div className="service-foot">
                {it.tags.map(t => <span key={t} className="chip">{t}</span>)}
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function SectionHeader({ eyebrow, title, sub, align = 'left' }) {
  return (
    <header className={'sh sh-' + align} style={align === 'center' ? { gridTemplateColumns: '1fr', textAlign: 'center', justifyItems: 'center' } : null}>
      <div className="sh-l">
        {eyebrow && <span className="eyebrow">{eyebrow}</span>}
        <h2 className="display-m" style={{ margin: 0 }}>{title}</h2>
      </div>
      {sub && (
        <div className="sh-r">
          <p className="lead">{sub}</p>
        </div>
      )}
    </header>
  );
}

// ── PORTFOLIO  big stacked previews ────────────────────────────────────────
const REAL_PROJECTS = [
  {
    id: 'lexai',
    name: 'LexAI',
    tagline: 'Legal tech per studi legali italiani.',
    desc: "Assistente AI verticale che redige documenti, calcola scadenze processuali e cita la normativa con motore RAG addestrato sul corpus italiano.",
    sector: 'Legal Tech',
    tags: ['SaaS', 'AI', 'RAG'],
    url: 'https://www.legale-ai.it',
    internalPage: 'lexai.html',
  },
  {
    id: 'domusflow',
    name: 'DomusFlow AI',
    tagline: 'Gestione condominiale intelligente.',
    desc: "Piattaforma SaaS per amministratori di condominio: verbali AI, smistamento segnalazioni, riconciliazione, solleciti morosi.",
    sector: 'PropTech',
    tags: ['SaaS', 'AI', 'PropTech'],
    url: 'https://www.domusflow.it',
    internalPage: 'domusflow.html',
  },
  {
    id: 'voxflow',
    name: 'VoxFlow AI',
    tagline: 'Agente vocale AI per il business.',
    desc: "Assistente vocale che risponde al telefono, prenota, gestisce conversazioni in linguaggio naturale, integrato con i gestionali.",
    sector: 'AI Voice',
    tags: ['Voice AI', 'Realtime', 'SaaS'],
    url: 'https://www.voxflowai.it',
  },
  {
    id: 'esteticairis',
    name: 'Estetica Iris',
    tagline: 'Sito vetrina premium per centro estetico.',
    desc: "Marketing site con prenotazione online, gallery trattamenti, schede operatrici e SEO locale curata nel dettaglio.",
    sector: 'Beauty · Local',
    tags: ['Marketing Site', 'CMS', 'SEO'],
    url: 'https://www.esteticairis.it',
  },
  {
    id: 'savintex',
    name: 'Savintex',
    tagline: 'Sito corporate per progetto residenziale.',
    desc: "Sito presentazione del progetto immobiliare con planimetrie, schede immobili e form di richiesta informazioni qualificato.",
    sector: 'Real Estate',
    tags: ['Marketing Site', 'Real Estate', 'CMS'],
    url: 'https://www.savintex.it',
  },
  {
    id: 'mollalo',
    name: 'Mollalo',
    tagline: 'Dona ciò che non usi, trova ciò che ti serve.',
    desc: "Piattaforma gratuita di sharing economy locale: connette donatori e riceventi nella stessa città. Zero intermediari, zero costi, impatto ambientale reale.",
    sector: 'SaaS · Sharing Economy',
    tags: ['SaaS', 'Community', 'Sostenibilità'],
    url: 'https://www.mollalo.com',
  },
  {
    id: 'vinciasmel',
    name: 'VinciASMEL',
    tagline: 'Preparazione AI ai concorsi per enti locali.',
    desc: "Piattaforma AI-native che accompagna i candidati nella preparazione agli esami ASMEL per posizioni amministrative pubbliche, con percorsi personalizzati e simulazioni.",
    sector: 'SaaS · EdTech',
    tags: ['SaaS', 'AI', 'EdTech'],
    url: 'https://www.vinciasmel.online',
  },
  {
    id: 'fratellidipizza',
    name: 'Fratelli di Pizza',
    tagline: 'Pizzeria napoletana tradizionale dal 1958.',
    desc: "Sito vetrina per una storica pizzeria napoletana. Identità digitale curata, menu digitale, storia del locale e SEO locale ottimizzata per il territorio.",
    sector: 'Marketing Site · Food',
    tags: ['Marketing Site', 'Ristorazione', 'SEO'],
    url: 'https://www.fratellidipizza.online',
  },
  {
    id: 'preventivogenny',
    name: 'Preventivo Genny',
    tagline: 'Preventivi edilizi professionali in pochi minuti.',
    desc: "Tool digitale che automatizza la creazione di preventivi strutturati per professionisti delle costruzioni. Dalla selezione lavorazioni alla proposta economica pronta in pochi click.",
    sector: 'Tool · Edilizia',
    tags: ['Tool', 'Edilizia', 'No-code'],
    url: 'https://www.preventivogenny.shop',
  },
];

// Live preview using WordPress mshots (real screenshot of the live site).
function SitePreview({ url, label }) {
  const [loaded, setLoaded] = React.useState(false);
  const [error, setError] = React.useState(false);
  const proxied = `https://s.wordpress.com/mshots/v1/${encodeURIComponent(url)}?w=1280&h=800`;
  let domain = url;
  try { domain = new URL(url).hostname.replace(/^www\./, ''); } catch {}
  return (
    <a href={url} target="_blank" rel="noopener noreferrer"
       className="site-preview" aria-label={`Apri ${label} in una nuova scheda`}>
      <div className="sp-chrome">
        <i></i><i></i><i></i>
        <span className="sp-url">
          <span className="sp-url-lock">🔒</span>{domain}
        </span>
        <span className="sp-ext"><Icon name="external" size={12}/></span>
      </div>
      <div className="sp-img-wrap">
        {!error && (
          <img src={proxied} alt={label} loading="lazy"
               className={loaded ? 'sp-img is-loaded' : 'sp-img'}
               onLoad={(e) => {
                 if (e.target.naturalWidth < 50) {
                   setTimeout(() => { e.target.src = proxied + '&r=' + Date.now(); }, 2000);
                 } else {
                   setLoaded(true);
                 }
               }}
               onError={() => setError(true)}/>
        )}
        {!loaded && !error && <div className="sp-skeleton" aria-hidden/>}
        {error && <div className="sp-fallback" aria-hidden>{label}</div>}
      </div>
    </a>
  );
}

function Portfolio() {
  return (
    <section id="portfolio" className="section section-alt">
      <div className="container">
        <header className="sh">
          <div className="sh-l">
            <span className="eyebrow">Portfolio</span>
            <h2 className="display-m">
              Lavori <em style={{ fontStyle: 'normal', background: 'var(--gradient)', WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent' }}>recenti</em>.
            </h2>
          </div>
          <div className="sh-r">
            <p className="lead">
              Una selezione di prodotti SaaS, agenti AI e siti premium che abbiamo
              costruito. Tutti live, con utenti reali.
            </p>
            <a href="portfolio.html" className="link-arrow" style={{ marginTop: 20 }}>
              Tutti i lavori <Icon name="arrow" size={14}/>
            </a>
          </div>
        </header>

        <div className="portfolio-list">
          {REAL_PROJECTS.map((p, i) => (
            <article key={p.id} className={'work mo-reveal ' + (i % 2 === 1 ? 'work-reverse' : '')}
                     style={{ '--mo-delay': `${i * 60}ms` }}>
              <div className="work-info">
                <span className="work-num">
                  ({String(i + 1).padStart(2, '0')})  {p.sector}
                </span>
                <h3 className="work-name">{p.name}</h3>
                <p className="work-tagline">{p.tagline}</p>
                <div className="work-tags chips">
                  {p.tags.map(t => <span key={t} className="chip">{t}</span>)}
                </div>
                <div className="work-cta">
                  <a href={p.url} target="_blank" rel="noopener noreferrer" className="link-arrow">
                    Visita il sito <Icon name="external" size={14}/>
                  </a>
                  {p.internalPage && (
                    <a href={p.internalPage} className="link-muted">Scopri di più</a>
                  )}
                </div>
              </div>
              <div>
                <SitePreview url={p.url} label={p.name}/>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  Navbar, Logo, Hero, Capabilities, Servizi, SectionHeader,
  Portfolio, SitePreview, REAL_PROJECTS,
});
