// Blast Events — Home page sections
const { useEffect, useRef, useState } = React;
const { TR, Counter, Star, PulseLine, Nav, MobileMenu, Footer,
        useCursor, useReveal, useNavScroll, useHeroReveal, submitContactForm } = window;

function Hero() {
  const videoRef = React.useRef(null);

  // Force-mute the video. Some browsers ignore the JSX `muted` prop the first
  // time around; this also re-mutes if anything (extension, user) un-mutes it.
  React.useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    const lock = () => { v.muted = true; v.volume = 0; try { v.defaultMuted = true; } catch(e){} v.setAttribute('muted', ''); };
    lock();
    // Strip the audio track entirely if the browser exposes it
    try {
      if (v.audioTracks) {
        for (let i = 0; i < v.audioTracks.length; i++) v.audioTracks[i].enabled = false;
      }
    } catch (e) {}
    v.addEventListener('volumechange', lock);
    v.addEventListener('play', lock);
    v.addEventListener('loadedmetadata', lock);
    // Attempt to play (autoplay-muted is allowed)
    const tryPlay = () => { lock(); v.play().catch(() => {}); };
    tryPlay();
    return () => {
      v.removeEventListener('volumechange', lock);
      v.removeEventListener('play', lock);
      v.removeEventListener('loadedmetadata', lock);
    };
  }, []);

  return (
    <section className="hero" id="top">
      <div className="videowrap">
        {/* Desktop: foto reale dell'evento. Mobile: video verticale (loro). */}
        <picture className="hero-photo">
          <source media="(min-width: 769px)" srcSet="assets/hero-desktop.webp" type="image/webp" />
          <source media="(min-width: 769px)" srcSet="assets/hero-desktop.jpg" type="image/jpeg" />
          <img src="assets/hero-mobile-poster.jpg" alt="Evento live a Belluno prodotto da Blast Events: palco, luci e schermi LED" fetchpriority="high" decoding="async" />
        </picture>
        <video
          className="hero-video"
          ref={videoRef}
          poster="assets/hero-mobile-poster.jpg"
          autoPlay muted loop playsInline
          preload="metadata"
          disablePictureInPicture
          disableRemotePlayback
          controls={false}
          aria-hidden="true"
          tabIndex={-1}
        >
          <source src="assets/hero-mobile.mp4" media="(max-width: 768px)" type="video/mp4" />
        </video>
      </div>

      <div className="top-row">
        <div className="mono live">SHOWREEL · 2024 / 2025</div>
        <div className="mono">BL · BELLUNO · IT</div>
        <div className="mono">EST. 2019</div>
      </div>

      <div className="lockup reveal-children">
        <h1>
          <span className="h1-line"><span className="h1-word acc">BLAST</span></span>
          <span className="h1-line events-line"><span className="h1-word events">events · belluno</span></span>
        </h1>
        <div className="actions h1-fade">
          <a href="#portfolio" className="btn primary"><span className="dot" /> Guarda i lavori</a>
          <a href="#contact" className="btn">Contattaci</a>
        </div>
      </div>

      <div className="bottom-row">
        <div className="scroll">
          <span className="arr" />
          <span className="loc">Belluno · IT</span>
        </div>
        <div></div>
        <div className="mono" style={{ textAlign: 'right' }}>N 46.14° · E 12.21°</div>
      </div>
    </section>
  );
}

// ============ Marquee ============
function Marquee() {
  const words = ['LIVE SHOWS', 'CORPORATE', 'PRIVATE EVENTS', 'STAGE DESIGN', 'AUDIO ENGINEERING', 'LIGHTING', 'FESTIVAL', 'TOUR SUPPORT'];
  const row = [...words, ...words];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {row.map((w, i) => (
          <div key={i} className="marquee-item">
            <span>{w}</span>
            <Star />
          </div>
        ))}
      </div>
    </div>
  );
}

// ============ About ============
function About() {
  return (
    <section id="about" className="about wrap">
      <div className="grid">
        <div className="reveal has-title">
          <div className="section-kicker">(01) Chi siamo</div>
          <h2>
            <TR>Dal <span className="ita">2019</span></TR>
            <TR>dietro il palco.</TR>
          </h2>
          <div style={{ marginTop: 32 }}><PulseLine /></div>
        </div>
        <div className="reveal">
          <p>Blast Events nasce nel <strong>2019</strong> con un'idea precisa. Un nuovo format di eventi che unisca intrattenimento, qualità e attenzione ai dettagli. Esperienze coinvolgenti, costruite su misura per il territorio e per il pubblico, curando ogni aspetto organizzativo e creativo.</p>
          <p>Negli anni abbiamo evoluto le nostre competenze ampliando il raggio d'azione, fino a specializzarci nel <strong>service audio e luci</strong>, diventando parte integrante di ciò che sta dietro ogni evento. La struttura tecnica, l'atmosfera, la resa scenica.</p>
          <p>Oggi offriamo un servizio completo, dall'ideazione alla realizzazione, inclusa la progettazione di palchi completamente personalizzati. La nostra filosofia. <em>Passione, affidabilità, innovazione</em>.</p>
        </div>
      </div>
    </section>
  );
}

// ============ Services ============
const SERVICES = [
  { n: '01', t: 'Service Audio', d: 'Sistemi line array, mixing FOH e monitor, sound design tarato sull\'acustica del luogo.' },
  { n: '02', t: 'Service Luci', d: 'Light design, motion fixture, gestione DMX/Art-Net, programmazione su grandMA / Avolites.' },
  { n: '03', t: 'Palchi Custom', d: 'Progettazione strutturale e scenografica, americane, truss, copertura, sicurezza inclusa.' },
  { n: '04', t: 'Event Production', d: 'Ideazione, regia, coordinamento tecnico-artistico, gestione fornitori e timing operativo.' },
  { n: '05', t: 'Video & LED Wall', d: 'Schermi LED indoor/outdoor, regia video, content design sincronizzato con il light show.' },
  { n: '06', t: 'Eventi Privati', d: 'Matrimoni, compleanni, anniversari e celebrazioni. Il rigore del live, l\'eleganza del private.' },
];

function Services() {
  return (
    <section id="services" className="services wrap">
      <div className="section-head reveal has-title">
        <div>
          <div className="section-kicker">(02) Cosa facciamo</div>
          <h2>
            <TR>Quello che</TR>
            <TR>facciamo.</TR>
          </h2>
        </div>
      </div>
      <div className="svc-list">
        {SERVICES.map((s) => (
          <div key={s.n} className="svc reveal">
            <div className="svc-num">[{s.n}]</div>
            <div className="svc-title">{s.t}</div>
            <div className="svc-desc">{s.d}</div>
            <div className="svc-arrow">→</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============ Numbers ============
function Numbers() {
  const items = [
    { v: '6',  s: '+', l: 'Anni in attività' },
    { v: '90', s: '+', l: 'Eventi prodotti' },
    { v: '70', tail: 'k', s: '+', l: 'Spettatori totali' },
    { v: '100', s: '%', l: 'Palchi custom' },
  ];
  return (
    <section className="nums wrap reveal">
      <div className="nums-grid">
        {items.map((i) => (
          <div key={i.l} className="num">
            <div className="v">
              <Counter to={parseInt(i.v, 10)} />
              {i.tail || ''}
              <span className="acc">{i.s}</span>
            </div>
            <div className="l">{i.l}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============ Portfolio ============
const PROJECTS = [
  { name: 'Live Shows',     year: '2024', tag: 'LIVE',     img: 'event-04', w: 'w-6' },
  { name: 'Festival',       year: '2024', tag: 'FESTIVAL', img: 'event-02', w: 'w-6' },
  { name: 'Stage Design',   year: '2025', tag: 'STAGE',    img: 'event-01', w: 'w-4' },
  { name: 'Lighting',       year: '2024', tag: 'LIGHTING', img: 'event-03', w: 'w-4' },
  { name: 'Private Events', year: '2025', tag: 'PRIVATE',  img: 'event-06', w: 'w-4' },
  { name: 'Audio Engineering', year: '2024', tag: 'AUDIO', img: 'event-05', w: 'w-6' },
];

function Portfolio({ onOpen }) {
  return (
    <section id="portfolio" className="portfolio wrap">
      <div className="section-head reveal has-title">
        <div>
          <div className="section-kicker">(03) Portfolio</div>
          <h2>
            <TR>Selezione</TR>
            <TR>lavori.</TR>
          </h2>
        </div>
      </div>
      <div className="pf-grid">
        {PROJECTS.map((p, i) => (
          <div key={i} className={`pf-item reveal ${p.w}`} onClick={() => onOpen(`assets/${p.img}.webp`)}>
            <div className="frame">
              <picture>
                <source srcSet={`assets/${p.img}-thumb.webp`} type="image/webp" />
                <img src={`assets/${p.img}-thumb.jpg`} alt={`${p.name} · evento Blast Events a Belluno`} loading="lazy" decoding="async" />
              </picture>
              <div className="badge">{p.tag}</div>
            </div>
            <div className="meta">
              <div className="name">{p.name}</div>
              <div className="year">{p.year}</div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============ Contact ============
function Contact() {
  const [sent, setSent] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(false);
  return (
    <section id="contact" className="contact wrap">
      <div className="reveal has-title">
        <div className="section-kicker">(04) Contatti</div>
        <h2 className="bigword">
          <span className="title-reveal"><span className="tr-inner">Contattaci<span className="acc">.</span></span></span>
        </h2>
      </div>

      <div className="contact-grid">
        <div className="reveal">
          <form onSubmit={async (e) => {
            e.preventDefault();
            if (e.target.elements.website && e.target.elements.website.value) return;
            setErr(false); setBusy(true);
            try {
              const ok = await submitContactForm(e.target);
              if (ok) { setSent(true); e.target.reset(); } else { setErr(true); }
            } catch (_) { setErr(true); }
            setBusy(false);
          }}>
            <div style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, overflow: 'hidden' }} aria-hidden="true">
              <label htmlFor="hf-website">Sito web</label>
              <input type="text" id="hf-website" name="website" tabIndex={-1} autoComplete="off" />
            </div>
            <div className="field">
              <label htmlFor="hf-name">Nome e cognome <span className="req">*</span></label>
              <input type="text" id="hf-name" name="name" autoComplete="name" placeholder="Mario Rossi" required />
            </div>
            <div className="field-row">
              <div className="field">
                <label htmlFor="hf-email">Email <span className="req">*</span></label>
                <input type="email" id="hf-email" name="email" autoComplete="email" placeholder="mario@email.it" required />
              </div>
              <div className="field">
                <label htmlFor="hf-phone">Telefono</label>
                <input type="tel" id="hf-phone" name="phone" autoComplete="tel" placeholder="+39 333 0000000" />
              </div>
            </div>
            <div className="field">
              <label htmlFor="hf-type">Tipo evento</label>
              <input type="text" id="hf-type" name="event_type" placeholder="Live, matrimonio, festival, aziendale..." />
            </div>
            <div className="field">
              <label htmlFor="hf-msg">Descrizione <span className="req">*</span></label>
              <textarea id="hf-msg" name="message" placeholder="Tipo di evento, location, data prevista, esigenze tecniche..." required minLength={20}></textarea>
            </div>
            <div className="field consent">
              <label htmlFor="hf-privacy" style={{ display: 'flex', alignItems: 'flex-start', gap: 10, fontSize: 13, lineHeight: 1.45, cursor: 'pointer' }}>
                <input type="checkbox" id="hf-privacy" name="privacy" required style={{ marginTop: 3, accentColor: 'var(--accent)' }} />
                <span>Ho letto l'<a href="https://www.iubenda.com/privacy-policy/59618259" target="_blank" rel="noopener noreferrer">informativa privacy</a> e acconsento al trattamento dei dati per rispondere alla mia richiesta. <span className="req">*</span></span>
              </label>
            </div>
            <button className="btn primary" type="submit" disabled={busy || sent}>
              <span className="dot" /> {sent ? 'Messaggio inviato' : (busy ? 'Invio...' : 'Invia richiesta')}
            </button>
            {err && <p style={{ marginTop: 14, fontSize: 13, color: 'var(--accent)' }}>Invio non riuscito. Riprova o scrivici a info@blasteventservice.com.</p>}
            <p style={{ marginTop: 18, fontSize: 12, color: 'var(--fg-dim)', fontFamily: 'var(--mono)', letterSpacing: '.06em' }}>RISPONDIAMO ENTRO 24H · LUN–VEN</p>
          </form>
        </div>
      </div>
    </section>
  );
}


// ============ Lightbox ============
function Lightbox({ src, onClose }) {
  useEffect(() => {
    const k = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', k);
    return () => window.removeEventListener('keydown', k);
  }, [onClose]);
  return (
    <div className={`lightbox ${src ? 'open' : ''}`} onClick={onClose}>
      <button className="close" onClick={onClose} aria-label="Chiudi">×</button>
      {src && <img src={src} alt="" onClick={(e) => e.stopPropagation()} />}
    </div>
  );
}

// ============ Root App ============
function App({ tweaks }) {
  useCursor();
  useReveal();
  useNavScroll();
  useHeroReveal();
  const [menu, setMenu] = useState(false);
  const [lightbox, setLightbox] = useState(null);

  // Apply tweaks
  useEffect(() => {
    const r = document.documentElement.style;
    r.setProperty('--accent', tweaks.accent);
    r.setProperty('--display', tweaks.display);
    r.setProperty('--density', tweaks.density);
    if (tweaks.theme === 'light') {
      r.setProperty('--bg', '#f4f1ea');
      r.setProperty('--bg-2', '#ebe7dd');
      r.setProperty('--fg', '#0a0a0a');
      r.setProperty('--fg-dim', '#666');
      r.setProperty('--line', '#dcd6c8');
      r.setProperty('--line-2', '#c8c1b0');
      r.setProperty('--accent-ink', '#f4f1ea');
    } else {
      r.setProperty('--bg', '#000');
      r.setProperty('--bg-2', '#0a0a0a');
      r.setProperty('--fg', '#ffffff');
      r.setProperty('--fg-dim', '#8a8a8a');
      r.setProperty('--line', '#1a1a1a');
      r.setProperty('--line-2', '#2a2a2a');
      r.setProperty('--accent-ink', '#000');
    }
  }, [tweaks]);

  return (
    <>
      <Nav onMenu={() => setMenu(true)} />
      <MobileMenu open={menu} onClose={() => setMenu(false)} />
      <Hero />
      <Marquee />
      <About />
      <Numbers />
      <Services />
      <Portfolio onOpen={setLightbox} />
      <Contact />
      <Footer />
      <Lightbox src={lightbox} onClose={() => setLightbox(null)} />
    </>
  );
}

window.App = App;
