/* Homepage: Hero, Nav, What, Audience, Scale, Proof — clean white v5. Bilingual.
   Reads window.LANG ('en' | 'es'). Logo + LangSwitch come from shell.jsx. */

const HLANG = (typeof window !== 'undefined' && window.LANG) || 'en';

const HOMECONTENT = {
  en: {
    nav: [['What we do', '#what'], ['Problem', '#problem'], ['Proof', '#proof'], ['Pilot', '#pilot']],
    license: 'License', protect: 'Protect',
    live: 'LIVE MONITORING', weekWord: 'WEEK',
    regions: 'EU · US · UK · LATAM',
    clips: <>UNAUTHORIZED CLIPS<br/>THIS WEEK</>,
    heroTitle: <>Stop AI from <em>stealing</em> your talent.</>,
    heroSub: <><b>talicense</b> finds unauthorized AI clones of the actors, musicians and voiceover artists you represent, across every major platform, and gives you the legal evidence to take them down or turn them into licensed revenue.</>,
    freeScan: 'Get a free scan', seeHow: 'See how it works',
    whatTitle: <>Your talent. Your rules.<br/><em>Your revenue.</em></>,
    whatSub: 'Two services. One platform. Both built for the people who own the rights.',
    protectName: 'Protect',
    protectHeading: 'Monitor, detect, and act on every violation. You decide. We execute.',
    protectFeat: [
      'Continuous monitoring across YouTube, TikTok, Instagram and Meta',
      'Court-ready evidence: screenshot, URL, timestamp and on-chain certificate',
      'Instant notification the moment a violation is detected',
      'You choose: takedown, license offer, or legal demand. We execute.',
      'Inbound requests from verified studios managed from one dashboard',
    ],
    protectFor: 'Talent Agencies · Estates · Rights Orgs', protectBtn: 'Protect Now',
    licenseName: 'License',
    licenseHeading: 'Set your terms, approve every deal, and get paid. All from one dashboard.',
    licenseFeat: [
      'Choose which media types you authorize: film, TV, advertising, social media, or any combination',
      'Set terms upfront: territory, duration, exclusivity, and content restrictions',
      'Every request comes to you first. Approve or reject before anything moves',
      'Legally binding contract auto-generated the moment you approve',
      'Payment collected on platform and sent directly to you',
    ],
    licenseFor: 'Talent Agencies · Rights Orgs', licenseBtn: 'Apply for access',
    audLabel: <>Built for the people who <em>own the face.</em></>,
    aud: [
      ['Talent Agencies', 'Protect actors, musicians and voiceover artists on your roster.'],
      ['Estates of Performers', 'Defend the legacy of deceased artists across every platform.'],
      ['Rights Organizations', 'Add likeness enforcement to your IP and royalty operations.'],
      ['Studios & Brands', 'License talent for AI content with full legal clarity.'],
    ],
    problemTitle: <>Not a future problem.<br/><em>Happening today.</em></>,
    rvLabel: 'Real violations, detected and documented',
    rvKeys: ['Subscribers', 'Est. monthly revenue', 'Platform', 'Rights holder notified'],
    rvBadge: 'Monetized · Active',
    cats: [<>Icons <em>resurrected</em> without consent</>, <>Talent <em>cloned</em> mid-career</>, <>Voices <em>sold</em> as AI products</>],
    proofTitle: <>Coverage that <em>actually works.</em></>,
    proofStats: [
      ['6', '+', 'Major platforms under continuous monitoring: YouTube, TikTok, Instagram, Facebook, web ads, streaming.'],
      ['48', 'h', 'Average detection-to-evidence time, from violation flagged to filing-ready package delivered.'],
      ['98', '%', 'Face and voice match accuracy on flagged violations. False positives below industry standard.'],
      ['100', '%', 'Of evidence packages on-chain anchored and admissible across EU, US, UK and LatAm jurisdictions.'],
    ],
    cases: [
      { eyebrow: 'Spain', name: 'Chiquito de la Calzada', meta: '🇪🇸 Comedian · d. 2017', subs: '5,500', revenue: '$180 – $420', platform: 'YouTube', notified: 'No', video: 'videos/case001_chiquito.mp4' },
      { eyebrow: 'USA', name: 'Marilyn Monroe', meta: '🇺🇸 Actress · d. 1962', subs: '12,300', revenue: '$520 – $1,100', platform: 'YouTube', notified: 'No', video: 'videos/case002_marilyn.mp4' },
      { eyebrow: 'India', name: 'Amitabh Bachchan', meta: '🇮🇳 Actor · Living', subs: '28,700', revenue: '$1,200 – $2,800', platform: 'YouTube', notified: 'No', video: 'videos/case003_bachchan.mp4' },
    ],
  },

  es: {
    nav: [['Qué hacemos', '#what'], ['El problema', '#problem'], ['Pruebas', '#proof'], ['Piloto', '#pilot']],
    license: 'Licenciar', protect: 'Proteger',
    live: 'MONITOREO EN VIVO', weekWord: 'SEMANA',
    regions: 'UE · EE.UU. · RU · LATAM',
    clips: <>CLIPS NO AUTORIZADOS<br/>ESTA SEMANA</>,
    heroTitle: <>Evita que la IA <em>robe</em> tu talento.</>,
    heroSub: <><b>talicense</b> encuentra clones de IA no autorizados de los actores, músicos y locutores que representas, en todas las plataformas principales, y te da la prueba legal para retirarlos o convertirlos en ingresos por licencia.</>,
    freeScan: 'Escaneo gratuito', seeHow: 'Cómo funciona',
    whatTitle: <>Tu talento. Tus reglas.<br/><em>Tus ingresos.</em></>,
    whatSub: 'Dos servicios. Una plataforma. Ambos hechos para quienes son dueños de los derechos.',
    protectName: 'Proteger',
    protectHeading: 'Monitorea, detecta y actúa ante cada infracción. Tú decides. Nosotros ejecutamos.',
    protectFeat: [
      'Monitoreo continuo en YouTube, TikTok, Instagram y Meta',
      'Pruebas listas para un tribunal: captura, URL, marca de tiempo y certificado en cadena',
      'Notificación inmediata en cuanto se detecta una infracción',
      'Tú eliges: retirada, oferta de licencia o requerimiento legal. Nosotros ejecutamos.',
      'Solicitudes de estudios verificados gestionadas desde un solo panel',
    ],
    protectFor: 'Agencias de talento · Herederos · Org. de derechos', protectBtn: 'Proteger ahora',
    licenseName: 'Licenciar',
    licenseHeading: 'Define tus condiciones, aprueba cada acuerdo y cobra. Todo desde un panel.',
    licenseFeat: [
      'Elige qué tipos de medios autorizas: cine, TV, publicidad, redes sociales o cualquier combinación',
      'Define las condiciones desde el inicio: territorio, duración, exclusividad y restricciones de contenido',
      'Cada solicitud llega primero a ti. Apruébala o recházala antes de que avance nada',
      'Contrato legalmente vinculante generado en el momento en que apruebas',
      'El pago se cobra en la plataforma y se te envía directamente',
    ],
    licenseFor: 'Agencias de talento · Org. de derechos', licenseBtn: 'Solicitar acceso',
    audLabel: <>Hecho para quienes son <em>dueños de su rostro.</em></>,
    aud: [
      ['Agencias de talento', 'Protege a los actores, músicos y locutores de tu cartera.'],
      ['Herederos de artistas', 'Defiende el legado de artistas fallecidos en todas las plataformas.'],
      ['Organizaciones de derechos', 'Suma la defensa de la imagen a tus operaciones de PI y regalías.'],
      ['Estudios y marcas', 'Licencia talento para contenido con IA con plena claridad legal.'],
    ],
    problemTitle: <>No es un problema del futuro.<br/><em>Está pasando hoy.</em></>,
    rvLabel: 'Infracciones reales, detectadas y documentadas',
    rvKeys: ['Suscriptores', 'Ingresos mensuales est.', 'Plataforma', 'Titular notificado'],
    rvBadge: 'Monetizado · Activo',
    cats: [<>Íconos <em>resucitados</em> sin consentimiento</>, <>Talento <em>clonado</em> en plena carrera</>, <>Voces <em>vendidas</em> como productos de IA</>],
    proofTitle: <>Cobertura que <em>de verdad funciona.</em></>,
    proofStats: [
      ['6', '+', 'Plataformas principales bajo monitoreo continuo: YouTube, TikTok, Instagram, Facebook, anuncios web, streaming.'],
      ['48', 'h', 'Tiempo medio de detección a evidencia, desde la infracción detectada hasta el paquete listo para presentar.'],
      ['98', '%', 'Precisión de coincidencia de rostro y voz en infracciones señaladas. Falsos positivos por debajo del estándar.'],
      ['100', '%', 'De los paquetes de prueba anclados en cadena y admisibles en la UE, EE. UU., Reino Unido y Latinoamérica.'],
    ],
    cases: [
      { eyebrow: 'España', name: 'Chiquito de la Calzada', meta: '🇪🇸 Humorista · f. 2017', subs: '5.500', revenue: '$180 – $420', platform: 'YouTube', notified: 'No', video: 'videos/case001_chiquito.mp4' },
      { eyebrow: 'EE. UU.', name: 'Marilyn Monroe', meta: '🇺🇸 Actriz · f. 1962', subs: '12.300', revenue: '$520 – $1,100', platform: 'YouTube', notified: 'No', video: 'videos/case002_marilyn.mp4' },
      { eyebrow: 'India', name: 'Amitabh Bachchan', meta: '🇮🇳 Actor · En vida', subs: '28.700', revenue: '$1,200 – $2,800', platform: 'YouTube', notified: 'No', video: 'videos/case003_bachchan.mp4' },
    ],
  },
};

const HT = HOMECONTENT[HLANG];

/* Current ISO week number, computed live from the browser clock (auto-updates weekly) */
const isoWeekNow = () => {
  const d = new Date();
  const t = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
  const day = t.getUTCDay() || 7;
  t.setUTCDate(t.getUTCDate() + 4 - day);
  const yearStart = new Date(Date.UTC(t.getUTCFullYear(), 0, 1));
  return { week: Math.ceil((((t - yearStart) / 86400000) + 1) / 7), year: t.getUTCFullYear() };
};
const NOW = isoWeekNow();

const Nav = ({ onProtect, onLicense }) => {
  const [open, setOpen] = React.useState(false);
  const resHref = HLANG === 'es' ? '/es/recursos.html' : '/resources.html';
  const resLabel = HLANG === 'es' ? 'Recursos' : 'Resources';
  return (
    <nav className="nav">
      <div className="nav-inner">
        <div className="nav-bar">
          <Logo />
          <div className="nav-links">
            {HT.nav.map(([label, anchor]) => <a key={anchor} href={anchor}>{label}</a>)}
            <a href={resHref}>{resLabel}</a>
          </div>
          <div className="nav-cta">
            <LangSwitch />
            <button className="btn btn-secondary btn-sm nav-desktop-cta" onClick={onLicense}>{HT.license}</button>
            <button className="btn btn-primary btn-sm" onClick={onProtect}>
              {HT.protect} <span className="arrow">→</span>
            </button>
            <button className="nav-toggle" aria-label="Menu" aria-expanded={open} onClick={() => setOpen(!open)}>
              <span/><span/><span/>
            </button>
          </div>
        </div>
        {open && (
          <div className="nav-menu">
            {HT.nav.map(([label, anchor]) => <a key={anchor} href={anchor} onClick={() => setOpen(false)}>{label}</a>)}
            <a href={resHref} onClick={() => setOpen(false)}>{resLabel}</a>
            <button onClick={() => { setOpen(false); onLicense(); }}>{HT.license}</button>
          </div>
        )}
      </div>
    </nav>
  );
};

const useCounter = (start, perTick) => {
  const [v, setV] = React.useState(start);
  React.useEffect(() => {
    const t = setInterval(() => setV(x => x + perTick), 2200);
    return () => clearInterval(t);
  }, [perTick]);
  return v;
};
const fmt = (n) => n.toLocaleString(HLANG === 'es' ? 'es-ES' : 'en-US');

const Hero = ({ onProtect, onLicense, baseCounter }) => {
  const v = useCounter(baseCounter, 1);
  return (
    <header className="hero">
      <div className="container">
        <div className="hero-meta">
          <span className="live"><span className="dot"></span> {HT.live} · {HT.weekWord} {NOW.week} / {NOW.year}</span>
          <div className="hero-meta-right">
            <span>{HT.regions}</span>
            <div className="hero-counter-chip">
              <div>
                <div className="num">{fmt(v)}<em>+</em></div>
                <div className="label" style={{marginTop: 8}}>{HT.clips}</div>
              </div>
            </div>
          </div>
        </div>

        <h1 className="hero-title">{HT.heroTitle}</h1>

        <div className="hero-bottom">
          <p className="hero-sub">{HT.heroSub}</p>
          <div className="hero-cta-row">
            <button className="btn btn-accent" onClick={onProtect}>
              {HT.freeScan} <span className="arrow">→</span>
            </button>
            <a className="btn btn-secondary" href={HLANG === 'es' ? '/es/protect.html' : '/protect.html'}>{HT.seeHow}</a>
          </div>
        </div>
      </div>
    </header>
  );
};

/* Check icon used in feature lists */
const CheckIcon = ({ color }) => (
  <svg width="18" height="18" viewBox="0 0 18 18" fill="none" style={{flexShrink: 0, marginTop: 1}}>
    <circle cx="9" cy="9" r="9" fill={color} fillOpacity="0.14"/>
    <path d="M5 9L7.5 11.5L13 6" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

/* WHAT WE DO — two service cards on dark */
const WhatSection = ({ onProtect, onLicense }) => (
  <section id="what" className="what-section-v2">
    <div className="container">
      <div className="wsv2-header">
        <h2 className="section-title wsv2-title">{HT.whatTitle}</h2>
        <p className="wsv2-subtitle">{HT.whatSub}</p>
      </div>

      <div className="wsv2-grid">
        <div className="wsv2-card wsv2-protect">
          <div className="wsv2-top">
            <h2 className="wsv2-card-title">{HT.protectName}</h2>
            <p className="wsv2-heading">{HT.protectHeading}</p>
          </div>
          <ul className="wsv2-features">
            {HT.protectFeat.map((f, i) => (
              <li key={i}><CheckIcon color="#E8412B" /><span>{f}</span></li>
            ))}
          </ul>
          <div className="wsv2-bottom">
            <div className="wsv2-for">
              <span className="wsv2-for-label">For</span>
              {HT.protectFor}
            </div>
            <button className="btn wsv2-btn wsv2-btn-protect" onClick={onProtect}>
              {HT.protectBtn} <span className="arrow">→</span>
            </button>
          </div>
        </div>

        <div className="wsv2-card wsv2-license">
          <div className="wsv2-top">
            <h2 className="wsv2-card-title">{HT.licenseName}</h2>
            <p className="wsv2-heading">{HT.licenseHeading}</p>
          </div>
          <ul className="wsv2-features">
            {HT.licenseFeat.map((f, i) => (
              <li key={i}><CheckIcon color="#1E45FF" /><span>{f}</span></li>
            ))}
          </ul>
          <div className="wsv2-bottom">
            <div className="wsv2-for">
              <span className="wsv2-for-label">For</span>
              {HT.licenseFor}
            </div>
            <button className="btn wsv2-btn wsv2-btn-license" onClick={onLicense}>
              {HT.licenseBtn} <span className="arrow">→</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </section>
);

/* AUDIENCE STRIP — "Who we serve" (anchor target #serve) */
const AudienceStrip = () => (
  <section id="serve" className="audience-strip">
    <div className="audience-strip-inner">
      <div className="audience-strip-label">{HT.audLabel}</div>
      {HT.aud.map(([title, desc], i) => (
        <div className="audience-item" key={i}>
          <div className="ai">{title}</div>
          <div className="ad">{desc}</div>
        </div>
      ))}
    </div>
  </section>
);

/* PROBLEM */
const CASES = HT.cases;

const TICKER_NAMES = ['Tom Hanks','Scarlett Johansson','Morgan Freeman','Taylor Swift','Keanu Reeves','Beyoncé','Robert Downey Jr.','Oprah Winfrey','Will Smith','Jennifer Aniston','Elon Musk','Leonardo DiCaprio','Dwayne Johnson','Cristiano Ronaldo','Margot Robbie','Barack Obama','Chris Evans','Angelina Jolie','Jeff Bezos','Zendaya','Brad Pitt','Kim Kardashian','Johnny Depp','Rihanna','Mark Zuckerberg','Meryl Streep','LeBron James','Natalie Portman','Cate Blanchett','Shah Rukh Khan','Shakira','Harrison Ford','Selena Gomez','Denzel Washington'];

const ScaleSection = () => {
  const [caseIdx, setCaseIdx] = React.useState(0);
  const [counter, setCounter] = React.useState(68328);
  const vidRef = React.useRef(null);

  React.useEffect(() => {
    const t = setInterval(() => setCaseIdx(i => (i + 1) % CASES.length), 45000);
    return () => clearInterval(t);
  }, []);

  React.useEffect(() => {
    const t = setInterval(() => setCounter(n => n + Math.floor(Math.random() * 4) + 1), 3500);
    return () => clearInterval(t);
  }, []);

  React.useEffect(() => {
    if (vidRef.current) { vidRef.current.src = CASES[caseIdx].video; vidRef.current.play().catch(() => {}); }
  }, [caseIdx]);

  const c = CASES[caseIdx];

  return (
    <section id="problem" className="problem-section">
      <div className="container">
        <div className="problem-header">
          <div>
            <h2 className="section-title problem-title">{HT.problemTitle}</h2>
          </div>
          <div className="rv-header-inline">
            <span className="rv-dot"></span>
            <span className="rv-label">{HT.rvLabel}</span>
          </div>
        </div>

        <div className="rv-card">
          <div className="rv-video">
            <video ref={vidRef} autoPlay muted loop playsInline src={c.video} />
          </div>
          <div className="rv-info">
            <div className="rv-eyebrow">{c.eyebrow}</div>
            <div className="rv-name">{c.name}</div>
            <div className="rv-meta">{c.meta}</div>
            <div className="rv-stats">
              <div className="rv-row"><span className="rv-key">{HT.rvKeys[0]}</span><span className="rv-val">{c.subs}</span></div>
              <div className="rv-row"><span className="rv-key">{HT.rvKeys[1]}</span><span className="rv-val">{c.revenue}</span></div>
              <div className="rv-row"><span className="rv-key">{HT.rvKeys[2]}</span><span className="rv-val">{c.platform}</span></div>
              <div className="rv-row"><span className="rv-key">{HT.rvKeys[3]}</span><span className="rv-val">{c.notified}</span></div>
            </div>
            <div className="rv-badge">{HT.rvBadge}</div>
            <div className="rv-pips">
              {CASES.map((_, i) => (
                <div key={i} className={'rv-pip' + (i === caseIdx ? ' active' : '')} onClick={() => setCaseIdx(i)} />
              ))}
            </div>
          </div>
        </div>

        <div className="problem-cats">
          {HT.cats.map((cat, i) => (
            <div className="prob-cat" key={i}><span className="prob-cat-num">{'0' + (i + 1)}</span>{cat}</div>
          ))}
        </div>
      </div>

      <div className="rv-ticker-wrap">
        <div className="rv-ticker">
          {[...TICKER_NAMES, ...TICKER_NAMES].map((n, i) => <span key={i}>{n}</span>)}
        </div>
      </div>
    </section>
  );
};

/* PROOF BAND — map bg + stats overlay */
const ProofBand = () => {
  React.useEffect(() => {
    if (window.__mapLoaded600) return;
    window.__mapLoaded600 = true;
    const loadScript = (src) => new Promise(res => {
      const s = document.createElement('script'); s.src = src; s.onload = res; document.head.appendChild(s);
    });
    loadScript('https://d3js.org/d3.v7.min.js').then(() =>
      loadScript('https://cdn.jsdelivr.net/npm/topojson-client@3/dist/topojson-client.min.js')
    ).then(() => {
      const W = 1100, H = 600;
      const svg = window.d3.select('#proof-map-svg');
      if (!svg.node()) return;
      svg.append('rect').attr('width', W).attr('height', H).attr('fill', 'transparent');
      const grid = svg.append('g').attr('stroke', 'rgba(80,130,200,0.07)').attr('stroke-width', '0.6');
      [100,200,300,400,500].forEach(y => grid.append('line').attr('x1',0).attr('y1',y).attr('x2',W).attr('y2',y));
      [183,366,550,733,916].forEach(x => grid.append('line').attr('x1',x).attr('y1',0).attr('x2',x).attr('y2',H));
      const proj = window.d3.geoEquirectangular().scale(W/(2*Math.PI)).translate([W/2, H/2+20]);
      const geoPath = window.d3.geoPath().projection(proj);
      fetch('https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json')
        .then(r => r.json()).then(world => {
          const countries = window.topojson.feature(world, world.objects.countries);
          const borders   = window.topojson.mesh(world, world.objects.countries, (a,b) => a !== b);
          svg.append('g').selectAll('path').data(countries.features).join('path')
            .attr('d', geoPath).attr('fill', 'rgba(22,34,80,0.5)').attr('stroke','none');
          svg.append('path').datum(borders).attr('d', geoPath)
            .attr('fill','none').attr('stroke','#1e3566').attr('stroke-width','0.6');
          svg.append('path').datum(window.topojson.mesh(world, world.objects.countries))
            .attr('d', geoPath).attr('fill','none').attr('stroke','#2a4a80').attr('stroke-width','0.9');
        });
    });
  }, []);

  return (
    <section id="proof" className="proof-band">
      <div className="proof-map-bg">
        <svg id="proof-map-svg" viewBox="0 0 1100 600" style={{display:'block',width:'100%',height:'100%'}} />
        {[
          {cls:'orange', s:'18%', t:'38%', lbl:'YouTube Scan'},
          {cls:'orange', s:'26%', t:'63%', lbl:'Deepfake Flagged'},
          {cls:'orange', s:'43%', t:'30%', lbl:'Voice Clone Detected'},
          {cls:'orange', s:'34%', t:'74%', lbl:'Account Blocked'},
          {cls:'orange', s:'10%', t:'56%', lbl:'DMCA Notice Sent'},
          {cls:'orange', s:'46%', t:'53%', lbl:'Evidence Captured'},
          {cls:'blue',   s:'57%', t:'31%', lbl:'Film Production'},
          {cls:'blue',   s:'68%', t:'56%', lbl:'Smart Contract Signed'},
          {cls:'blue',   s:'78%', t:'39%', lbl:'TV Commercial'},
          {cls:'blue',   s:'88%', t:'66%', lbl:'Revenue Collected'},
          {cls:'blue',   s:'63%', t:'73%', lbl:'Brand Campaign'},
          {cls:'blue',   s:'91%', t:'43%', lbl:'Studio Approved'},
        ].map((d,i) => (
          <div key={i} className={`map-dot ${d.cls}`} style={{left:d.s, top:d.t}}>
            <div className="dot-label">{d.lbl}</div>
            <div className="dot-ring" /><div className="dot-ring" /><div className="dot-ring" />
            <div className="dot-core" />
          </div>
        ))}
      </div>

      <div className="proof-overlay">
        <div className="container">
          <div className="proof-head">
            <h2 className="section-title proof-title">{HT.proofTitle}</h2>
          </div>
          <div className="proof-grid">
            {HT.proofStats.map(([v, unit, label], i) => (
              <div className="proof-stat" key={i}>
                <div className="v">{v}<em>{unit}</em></div>
                <div className="l">{label}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Nav, Hero, WhatSection, AudienceStrip, ScaleSection, ProofBand });
