/* global React, ReactDOM, useTweaks, TweaksPanel, TweakSection, TweakSlider, TweakToggle, TweakRadio */
const { useState, useEffect, useRef, useCallback } = React;

/* ----------------------------------------------------------------
   i18n — language fixed at load; toggle reloads with ?lang=
---------------------------------------------------------------- */
const LANG = (window.FPA_LANG === 'es') ? 'es' : 'en';
const t = (en, es) => (LANG === 'es' && es != null) ? es : en;

/* ----------------------------------------------------------------
   DATA
---------------------------------------------------------------- */
const IMGS = {
  breach:   'assets/nv-breach-square.jpg',
  portrait: 'assets/nv-operator-portrait.jpg',
  aiming:   'assets/nv-convoy-wide.jpg',
  convoy:   'assets/nv-aiming-wide.jpg',
  detain:   'assets/nv-detain-square.jpg',
};
const HERO_SLIDES = [IMGS.aiming, IMGS.convoy, IMGS.breach, IMGS.detain];

const CAPS = window.FPA_CAPS;

const OPS = [
  { n:'01', k:'RECON',  cmd:'./recon',  h:t('Map the threat','Mapear la amenaza'),
    p:t('Intelligence-led assessment of the people, places and patterns around the principal.',
        'Evaluaci\u00F3n basada en inteligencia de las personas, lugares y patrones alrededor del cliente.') },
  { n:'02', k:'PLAN',   cmd:'./plan',   h:t('Build the detail','Dise\u00F1ar el servicio'),
    p:t('A custom protection plan with contingencies, comms and clear rules of engagement.',
        'Un plan de protecci\u00F3n a la medida con contingencias, comunicaciones y reglas de actuaci\u00F3n claras.') },
  { n:'03', k:'DEPLOY', cmd:'./deploy', h:t('Boots on ground','Operadores en terreno'),
    p:t('Vetted operators inserted with secure communications and live command oversight.',
        'Operadores verificados desplegados con comunicaciones seguras y supervisi\u00F3n de mando en vivo.') },
  { n:'04', k:'SECURE', cmd:'./secure', h:t('Maintain & adapt','Mantener y adaptar'),
    p:t('Continuous coverage with real-time reporting and a full after-action review.',
        'Cobertura continua con reportes en tiempo real y un informe final completo.') },
];

const METRICS = [
  { num:'1,200+', lab:t('Details completed','Servicios completados'), pct:0.96 },
  { num:'98%',    lab:t('Client retention','Retenci\u00F3n de clientes'),  pct:0.98 },
  { num:'<15m',   lab:t('Avg response time','Tiempo de respuesta prom.'), pct:0.88 },
  { num:'24/7',   lab:t('Global readiness','Disponibilidad global'),  pct:1.0  },
];

const LOCS = [
  { nm:'MEXICO CITY', co:'CDMX', st:'ACTIVE' },
  { nm:'MONTERREY',   co:'NLE',  st:'ACTIVE' },
  { nm:'GUADALAJARA', co:'JAL',  st:'ACTIVE' },
  { nm:'CANC\u00DAN', co:'ROO',  st:'ACTIVE' },
  { nm:'TIJUANA',     co:'BCN',  st:'STANDBY' },
  { nm:'LOS ANGELES', co:'USA',  st:'STANDBY' },
];
const stLabel = (s) => s === 'ACTIVE' ? t('ACTIVE','ACTIVO') : t('STANDBY','EN ESPERA');

/* ----------------------------------------------------------------
   HELPERS
---------------------------------------------------------------- */
function asciiBar(pct, len = 22) {
  const f = Math.round(pct * len);
  return { fill: '\u2588'.repeat(f), empty: '\u2591'.repeat(len - f) };
}
function Bar({ pct, len }) {
  const b = asciiBar(pct, len);
  return <span className="bar"><span className="fill">{b.fill}</span><span className="empty">{b.empty}</span></span>;
}

function LangToggle() {
  return (
    <span className="langtog">
      <a className={LANG === 'en' ? 'on' : ''} href={window.fpaLangHref('en')}>EN</a>
      <span className="sep">|</span>
      <a className={LANG === 'es' ? 'on' : ''} href={window.fpaLangHref('es')}>ES</a>
    </span>
  );
}

function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver((es) => {
      es.forEach(e => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
    }, { threshold: 0.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
}

/* ----------------------------------------------------------------
   SECTIONS
---------------------------------------------------------------- */
function Nav({ onNav }) {
  const [stuck, setStuck] = useState(false);
  useEffect(() => {
    const f = () => setStuck(window.scrollY > 30);
    f(); window.addEventListener('scroll', f, { passive: true });
    return () => window.removeEventListener('scroll', f);
  }, []);
  const go = (e, sel) => { e.preventDefault(); onNav(sel); };
  return (
    <header className={'nav' + (stuck ? ' stuck' : '')}>
      <div className="wrap">
        <a className="brand" href="#top" onClick={(e)=>go(e,'#top')}>
          <img src="assets/fpa-shield.png" alt="FPA" />
          <span className="tw"><b>FULL_PROTECTION</b><small>AGENCY // FPA</small></span>
        </a>
        <nav>
          <div className="navdd">
            <a href="#capabilities" onClick={(e)=>go(e,'#capabilities')} className="navdd-trig">{t('capabilities','capacidades')}<span className="caret">▾</span></a>
            <div className="dd-menu">
              <div className="dd-head">{t('// service lines','// líneas de servicio')}</div>
              {CAPS.map(c => (
                <a key={c.slug} href={c.href || `capability.html?id=${c.slug}`} className="dd-item">
                  <span className="dd-ix">{c.ix}</span>
                  <span className="dd-tt">{c.tt}</span>
                </a>
              ))}
            </div>
          </div>
          <a href="#operators" onClick={(e)=>go(e,'#operators')}>{t('operators','operadores')}</a>
          <a href="#operations" onClick={(e)=>go(e,'#operations')}>{t('operations','operaciones')}</a>
          <a href="#deployment" onClick={(e)=>go(e,'#deployment')}>{t('deployment','despliegue')}</a>
          <a href="#about" onClick={(e)=>go(e,'#about')}>{t('about','nosotros')}</a>
          <a href="#legal" onClick={(e)=>go(e,'#legal')}>{t('legal','legal')}</a>
          <a href="#contact" onClick={(e)=>go(e,'#contact')}>{t('contact','contacto')}</a>
        </nav>
        <div className="navcta">
          <LangToggle />
          <span className="statuspill"><span className="sq" />{t('SECURE','SEGURO')}</span>
          <button className="btn" onClick={() => window.FPAContact && window.FPAContact.open()}>{t('Request a detail','Solicitar servicio')}</button>
        </div>
        <button className="burger" onClick={() => window.FPAContact && window.FPAContact.open()} aria-label="contact">▤</button>
      </div>
    </header>
  );
}

function Hero({ onNav }) {
  return (
    <section className="hero" id="top">
      <div className="hero-bg">
        <div className="slide on" style={{ backgroundImage: `url(${IMGS.aiming})` }} />
        <div className="grade" />
      </div>
      <div className="wrap">
        <div className="hero-inner">
          <h1 className="reveal">{t('Elite Security','Soluciones de')}<br />{t('Solutions','Seguridad de Élite')}</h1>
          <p className="sub reveal">{t('Specialized protection by retired Mexican special forces for executives, government, and high-value assets.','Protección especializada a cargo de exmilitares de fuerzas especiales mexicanas para ejecutivos, gobierno y activos de alto valor.')}</p>
          <div className="cta reveal">
            <button className="btn" onClick={() => window.FPAContact && window.FPAContact.open()}>{t('[ Request Protection ]','[ Solicitar protección ]')}</button>
            <button className="btn btn-ghost" onClick={() => onNav('#about')}>{t('About FPA','Sobre FPA')}</button>
          </div>
        </div>
      </div>
      <div className="hero-tag">{t("Mexico's Premier Security",'Seguridad líder en México')}</div>
    </section>
  );
}

function MetricsBand() {
  return (
    <section className="band">
      <div className="wrap">
        <div className="metrics">
          {METRICS.map((m, i) => (
            <div className="m reveal" key={i} style={{transitionDelay:`${i*60}ms`}}>
              <div className="num">{m.num}</div>
              <div className="lab">{m.lab}</div>
              <div className="bar"><Bar pct={m.pct} len={14} /></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function SectionHead({ idx, title, lead, id }) {
  return (
    <div className="shead" id={id}>
      <div>
        <div className="idx reveal">{idx}</div>
        <h2 className="reveal">{title}</h2>
      </div>
      {lead && <p className="lead reveal">{lead}</p>}
    </div>
  );
}

function Capabilities() {
  return (
    <section className="section" id="capabilities">
      <div className="wrap">
        <SectionHead idx={t('// 01 — CAPABILITIES','// 01 — CAPACIDADES')} title={t('What we provide','Lo que ofrecemos')} lead={t('Six core service lines. Run them standalone or combined into a single managed protection package.','Seis líneas de servicio principales. Úsalas por separado o combínalas en un solo paquete de protección gestionado.')} />
        <div className="caps">
          {CAPS.map((c, i) => (
            <article className="cap reveal" key={c.ix} style={{transitionDelay:`${(i%3)*70}ms`}}>
              <div className="ch"><span className="ix">{c.ix}</span><span className="tt">{c.tt}</span></div>
              <div className="cb">
                <div className="cmd"><span className="p">fpa@secure:~$</span> {c.cmd}</div>
                <p className="desc">{c.desc}</p>
                <ul>{c.li.map((l, j) => <li key={j}>{l}</li>)}</ul>
                <a className="more" href={c.href || `capability.html?id=${c.slug}`}>{t('> read more _','> ver más _')}</a>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function OurOperators() {
  const vref = useRef(null);
  useEffect(() => {
    const v = vref.current;
    if (!v) return;
    v.muted = true;
    const p = v.play();
    if (p && p.catch) p.catch(() => {});
  }, []);
  return (
    <section className="section" id="operators">
      <div className="wrap">
        <SectionHead idx={t('// 02 — OPERATORS','// 02 — OPERADORES')} title={t('Our operators','Nuestros operadores')} lead={t('The people behind every detail — drawn from elite military and law-enforcement units.','Las personas detrás de cada servicio — provenientes de unidades militares y policiales de élite.')} />
        <div className="win reveal">
          <div className="win-bar"><span className="dots"><i className="on" /><i /><i /></span><span className="win-title">operators_feed.mp4 // FPA</span><span>{t('LIVE','EN VIVO')}</span></div>
          <div className="opvid">
            <video ref={vref} autoPlay muted loop playsInline preload="auto" poster={IMGS.breach}>
              <source src="assets/operators-feed.mp4" type="video/mp4" />
            </video>
            <div className="grade"></div>
            <div className="scan"></div>
            <span className="corner tl"></span>
            <span className="corner br"></span>
            <div className="hud"><span className="d"></span>REC</div>
            <div className="ov">
              <div className="k">{t('// personnel dossier — class A','// expediente de personal — clase A')}</div>
              <h3>{t('Forged in special forces.','Forjados en fuerzas especiales.')}</h3>
              <p>{t("Every FPA operator is drawn from elite military, special-forces and law-enforcement units. Each one clears a multi-stage vetting process — background, psychological and tactical evaluation — before earning the badge. Continuously trained in close protection, defensive driving and emergency medical response, they hold to a single standard: total protection, zero compromise.",'Cada operador de FPA proviene de unidades militares de élite, fuerzas especiales y cuerpos policiales. Todos superan un proceso de selección de varias etapas — antecedentes, evaluación psicológica y táctica — antes de portar la insignia. Entrenados de forma continua en protección cercana, conducción defensiva y respuesta médica de emergencia, se rigen por un único estándar: protección total, cero concesiones.')}</p>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Operations() {
  return (
    <section className="section" id="operations" style={{background:'var(--bg-2)',borderTop:'1px solid var(--border)',borderBottom:'1px solid var(--border)'}}>
      <div className="wrap">
        <SectionHead idx={t('// 03 — OPERATIONS','// 03 — OPERACIONES')} title={t('How a detail runs','Cómo se ejecuta un servicio')} lead={t('Every engagement follows the same disciplined sequence — from first brief to after-action.','Cada misión sigue la misma secuencia disciplinada — desde el primer briefing hasta el informe final.')} />
        <div className="ops">
          {OPS.map((o, i) => (
            <div className="op reveal" key={o.n} style={{transitionDelay:`${i*70}ms`}}>
              <div className="step">{t('STEP','PASO')} {o.n}</div>
              <div className="ic">{o.k}</div>
              <div className="cmd dimtx" style={{fontSize:12,marginBottom:12}}>$ {o.cmd}</div>
              <h3>{o.h}</h3>
              <p>{o.p}</p>
              {i < OPS.length - 1 && <span className="arrow">&gt;&gt;</span>}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Deployment() {
  return (
    <section className="section" id="deployment">
      <div className="wrap">
        <SectionHead idx={t('// 04 — DEPLOYMENT','// 04 — DESPLIEGUE')} title={t('Standing presence','Presencia permanente')} lead={t('Operators on call across Mexico and the border region, ready to mobilize on short notice.','Operadores disponibles en todo México y la región fronteriza, listos para movilizarse en poco tiempo.')} />
        <div className="deploy">
          <div className="scan-img reveal" style={{minHeight:360}}>
            <img src={IMGS.breach} alt="field deployment" style={{width:'100%',height:'100%',objectFit:'cover',minHeight:360}} />
            <div className="cap"><span>SITREP // BREACH TEAM</span><span>GRID 19.43N</span></div>
          </div>
          <div className="win reveal">
            <div className="win-bar"><span className="win-title">deployment_status.log</span><span className="tag live" style={{border:'none',padding:0}}><span className="dot" /></span></div>
            <div className="win-body">
              <div className="locs">
                {LOCS.map((l, i) => (
                  <div className="loc" key={i}>
                    <span className="st"><span className="d" style={{background:l.st==='ACTIVE'?'var(--phos)':'var(--amber)'}} /></span>
                    <span className="nm">{l.nm}</span>
                    <span className="co">{l.co}</span>
                    <span className="st" style={{color:l.st==='ACTIVE'?'var(--dim)':'var(--amber)'}}>{stLabel(l.st)}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function About() {
  return (
    <section className="section about" id="about" style={{background:'var(--bg-2)',borderTop:'1px solid var(--border)',borderBottom:'1px solid var(--border)'}}>
      <div className="wrap">
        <SectionHead idx={t('// 05 — ABOUT','// 05 — NOSOTROS')} title={t('The agency','La agencia')} lead={null} />
        <div className="about-grid">
          <div className="win reveal">
            <div className="win-bar"><span className="dots"><i className="on" /><i /><i /></span><span className="win-title">cat /etc/fpa/about.txt</span></div>
            <div className="win-body">
              <p>{t('','')}<b>Full Protection Agency</b>{t(' is a private security firm built by former military, law-enforcement and intelligence professionals.',' es una firma de seguridad privada creada por exprofesionales del ámbito militar, policial y de inteligencia.')}</p>
              <p>{t('We exist for the moments when ordinary security is not enough — when exposure carries real consequences and the margin for error is zero. Our model is simple: ','Existimos para los momentos en que la seguridad común no basta — cuando la exposición tiene consecuencias reales y el margen de error es cero. Nuestro modelo es simple: ')}<b>{t('intelligence first, presence second, force last.','inteligencia primero, presencia después, fuerza al final.')}</b></p>
              <p>{t('Every operator is background-vetted, mission-trained and held to a single standard — total protection, zero compromise.','Cada operador está verificado, entrenado para la misión y se rige por un único estándar — protección total, cero concesiones.')}</p>
              <div className="creds">
                <div className="c"><div className="k">{t('Founded','Fundada')}</div><div className="v">2009</div></div>
                <div className="c"><div className="k">{t('Licensed in','Con licencia en')}</div><div className="v">{t('14 regions','14 regiones')}</div></div>
                <div className="c"><div className="k">{t('Operators','Operadores')}</div><div className="v">{t('120+ vetted','120+ verificados')}</div></div>
                <div className="c"><div className="k">{t('Clearance','Acreditación')}</div><div className="v">TS / SCI</div></div>
              </div>
            </div>
          </div>
          <div className="about-img reveal">
            <div className="ph" style={{ backgroundImage:`url(${IMGS.portrait})` }} />
            <div className="rechud"><span className="d" />REC ●</div>
            <div className="cap"><span>FIELD OPS // OVERWATCH</span><span>ISO-3200 // NV</span></div>
          </div>
        </div>
      </div>
    </section>
  );
}

function LegalEntity({ onNav }) {
  return (
    <section className="section" id="legal">
      <div className="wrap">
        <SectionHead
          idx={t('// 06 — LEGAL & COMPLIANCE','// 06 — LEGAL Y CUMPLIMIENTO')}
          title={t('Sign in the US. Protected in Mexico.','Firma en EE. UU. Protegido en México.')}
          lead={t('US clients contract with our US-registered LLC under US law — then our licensed teams deliver on the ground in Mexico. One agreement, zero foreign-entity friction.','Los clientes en EE. UU. contratan con nuestra LLC registrada en EE. UU. bajo ley estadounidense — y nuestros equipos con licencia ejecutan en territorio mexicano. Un solo contrato, cero fricción de entidad extranjera.')}
        />
        <div className="legal">
          <div className="lpanel win reveal">
            <div className="win-bar"><span className="dots"><i className="on" /><i /><i /></span><span className="win-title">us-llc / contract.sig</span><span className="lflag">US</span></div>
            <div className="win-body">
              <div className="lphead">
                <span className="lpix">01</span>
                <div>
                  <div className="lpk">{t('CONTRACTING ENTITY // US','ENTIDAD CONTRATANTE // EE. UU.')}</div>
                  <h3>{t('Contract under US law','Contrato bajo ley de EE. UU.')}</h3>
                </div>
              </div>
              <p>{t('You sign with Full Protection Agency, LLC — our US-registered entity. Master agreements, SOWs, NDAs and invoicing are governed by US law and billed through a US bank, so your legal and procurement teams onboard us like any domestic vendor.','Firmas con Full Protection Agency, LLC — nuestra entidad registrada en EE. UU. Los contratos marco, SOW, NDA y la facturación se rigen por ley estadounidense y se cobran mediante un banco en EE. UU., para que tus equipos legales y de compras nos den de alta como a cualquier proveedor nacional.')}</p>
              <ul className="lp-list">
                <li>{t('US-governed MSA / SOW / NDA','MSA / SOW / NDA bajo ley de EE. UU.')}</li>
                <li>{t('Invoiced in USD via a US bank','Facturado en USD vía banco de EE. UU.')}</li>
                <li>{t('Expedited signing — days, not months','Firma expedita — días, no meses')}</li>
              </ul>
            </div>
          </div>

          <div className="lbridge reveal" aria-hidden="true">
            <span className="lbridge-line"></span>
            <span className="lbridge-node">⇄</span>
          </div>

          <div className="lpanel win reveal">
            <div className="win-bar"><span className="dots"><i className="on" /><i /><i /></span><span className="win-title">mx-ops / deploy.run</span><span className="lflag">MX</span></div>
            <div className="win-body">
              <div className="lphead">
                <span className="lpix">02</span>
                <div>
                  <div className="lpk">{t('SERVICE DELIVERY // MX','EJECUCIÓN DEL SERVICIO // MX')}</div>
                  <h3>{t('Protected on the ground in Mexico','Protegido en territorio mexicano')}</h3>
                </div>
              </div>
              <p>{t('That same US agreement authorizes and expedites our fully licensed Mexican operation. FPA operators mobilize across Mexico and the border region under one contract — you hold a single US-law relationship while we carry every in-country licensing, permitting and compliance requirement.','Ese mismo contrato en EE. UU. autoriza y agiliza nuestra operación mexicana con licencia plena. Los operadores de FPA se movilizan en todo México y la región fronteriza bajo un solo contrato — tú mantienes una única relación bajo ley estadounidense mientras nosotros asumimos cada licencia, permiso y requisito de cumplimiento en el país.')}</p>
              <ul className="lp-list">
                <li>{t('Fully licensed Mexican security operation','Operación de seguridad con licencia en México')}</li>
                <li>{t('Rapid cross-border mobilization','Movilización transfronteriza rápida')}</li>
                <li>{t('One contract, one point of accountability','Un contrato, un solo punto de responsabilidad')}</li>
              </ul>
            </div>
          </div>
        </div>

        <div className="lassure reveal">
          <span className="tag">{t('USMCA-ALIGNED','ALINEADO AL T-MEC')}</span>
          <span className="tag">{t('US-LAW CONTRACTING','CONTRATACIÓN BAJO LEY EE. UU.')}</span>
          <span className="tag">{t('MX-LICENSED DELIVERY','EJECUCIÓN CON LICENCIA MX')}</span>
          <button className="btn" onClick={() => window.FPAContact && window.FPAContact.open(t('US contracting','Contratación EE. UU.'))}>{t('[ Start a US contract ]','[ Iniciar contrato en EE. UU. ]')}</button>
        </div>
      </div>
    </section>
  );
}

function Contact({ onNav }) {
  const [sent, setSent] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const submit = (e) => {
    e.preventDefault();
    const f = e.target;
    const data = {
      name: f.elements.name.value.trim(),
      contact: f.elements.contact.value.trim(),
      service: f.elements.service.value,
      brief: f.elements.brief.value.trim(),
      botcheck: f.elements.botcheck.checked ? 'on' : ''
    };
    if (!window.FPAContact) { setErr(t('Form unavailable. Please email contact@fprotection.com.mx','Formulario no disponible. Escribe a contact@fprotection.com.mx')); return; }
    setErr(''); setBusy(true);
    window.FPAContact.send(data)
      .then(() => { setSent(true); })
      .catch((ex) => {
        setErr(ex && ex.message === 'NO_KEY'
          ? t('Form not configured yet. Email contact@fprotection.com.mx','El formulario aún no está configurado. Escribe a contact@fprotection.com.mx')
          : t('Transmission failed. Please try again or email contact@fprotection.com.mx','La transmisión falló. Intenta de nuevo o escribe a contact@fprotection.com.mx'));
      })
      .then(() => setBusy(false));
  };
  return (
    <section className="section" id="contact">
      <div className="wrap">
        <SectionHead idx={t('// 07 — CONTACT','// 07 — CONTACTO')} title={t('Request a protection detail','Solicita un servicio de protección')} lead={t('Encrypted intake. A duty officer responds within one hour — faster for active threats.','Recepción cifrada. Un oficial de guardia responde en menos de una hora — más rápido ante amenazas activas.')} />
        <div className="contact-grid">
          <form className="form win" onSubmit={submit}>
            <div className="win-bar"><span className="dots"><i className="on" /><i /><i /></span><span className="win-title">secure_intake --encrypt</span></div>
            <div className="win-body">
              {sent ? (
                <div className="sent">
                  <div>{t('> transmission encrypted ............ [OK]','> transmisión cifrada ............ [OK]')}</div>
                  <div>{t('> routed to duty officer ........... [OK]','> enviado al oficial de guardia ... [OK]')}</div>
                  <div style={{marginTop:10}} className="amber">{t('[ MESSAGE RECEIVED ] — Stand by. A duty officer will make contact within the hour.','[ MENSAJE RECIBIDO ] — En espera. Un oficial de guardia te contactará en menos de una hora.')}<span className="cursor" /></div>
                </div>
              ) : (
                <React.Fragment>
                  <div className="fld">
                    <label><span className="p">{t('name','nombre')}</span> {t('--required','--requerido')}</label>
                    <div className="ipt"><span className="pmt">$</span><input name="name" required autoComplete="name" placeholder={t('full name','nombre completo')} /></div>
                  </div>
                  <div className="fld">
                    <label><span className="p">{t('contact','contacto')}</span> {t('--encrypted','--cifrado')}</label>
                    <div className="ipt"><span className="pmt">$</span><input name="contact" required placeholder={t('email or secure number','correo o número seguro')} /></div>
                  </div>
                  <input type="checkbox" name="botcheck" className="cm-hp" tabIndex={-1} autoComplete="off" />
                  <div className="fld">
                    <label><span className="p">{t('service','servicio')}</span></label>
                    <div className="ipt"><span className="pmt">&gt;</span>
                      <select name="service" defaultValue="">
                        <option value="" disabled>{t('select detail type…','selecciona el tipo de servicio…')}</option>
                        {CAPS.map(c => <option key={c.ix}>{c.tt}</option>)}
                        <option>{t('Other / not sure','Otro / no estoy seguro')}</option>
                      </select>
                    </div>
                  </div>
                  <div className="fld">
                    <label><span className="p">{t('brief','resumen')}</span></label>
                    <div className="ipt"><span className="pmt">$</span><textarea placeholder={t('describe the situation, location and timeframe…','describe la situación, ubicación y tiempos…')} /></div>
                  </div>
                  <div className="submit">
                    <button className="btn" type="submit" disabled={busy}>{busy ? t('[ Transmitting… ]','[ Transmitiendo… ]') : t('[ Transmit secure ]','[ Transmitir seguro ]')}</button>
                    <span className="note">{t('Encrypted · never shared','Cifrado · nunca se comparte')}</span>
                  </div>
                  {err && <div className="cm-err" style={{marginTop:14}}>{err}</div>}
                </React.Fragment>
              )}
            </div>
          </form>

          <div className="contact-info">
            <div className="win">
              <div className="win-bar"><span className="win-title">channels.cfg</span></div>
              <div className="win-body">
                <div className="line"><span className="k">SECURE_EMAIL</span><span className="v">contact@fprotection.com.mx</span></div>
                <div className="line"><span className="k">HQ</span><span className="v">{t('Mexico City · Monterrey · Guadalajara','Ciudad de México · Monterrey · Guadalajara')}</span></div>
                <div className="line"><span className="k">{t('HOURS','HORARIO')}</span><span className="v">24 / 7 / 365</span></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="foot">
      <div className="wrap">
        <div className="foot-top">
          <div>
            <div className="fbrand"><img src="assets/fpa-shield.png" alt="FPA" /><b>FULL PROTECTION AGENCY</b></div>
            <p className="blurb">{t('Intelligence first. Presence second. Force last. Total protection, zero compromise.','Inteligencia primero. Presencia después. Fuerza al final. Protección total, cero concesiones.')}</p>
            <div className="ascii-rule" style={{marginTop:18}}>{t('└─[ secure ]──[ vetted ]──[ 24/7 ]──┘','└─[ seguro ]──[ verificado ]──[ 24/7 ]──┘')}</div>
          </div>
          <div>
            <h4>{t('Capabilities','Capacidades')}</h4>
            <ul>{CAPS.slice(0,5).map(c => <li key={c.ix}><a href="#capabilities">{c.tt}</a></li>)}</ul>
          </div>
          <div>
            <h4>{t('Agency','Agencia')}</h4>
            <ul>
              <li><a href="#about">{t('About','Nosotros')}</a></li>
              <li><a href="#operations">{t('Operations','Operaciones')}</a></li>
              <li><a href="#deployment">{t('Deployment','Despliegue')}</a></li>
              <li><a href="#legal">{t('US contracting','Contratación EE. UU.')}</a></li>
              <li><a href="#contact">{t('Contact','Contacto')}</a></li>
              <li><a href="#contact">{t('Careers','Empleos')}</a></li>
            </ul>
          </div>
          <div>
            <h4>{t('Contact','Contacto')}</h4>
            <ul>
              <li><a href="mailto:contact@fprotection.com.mx">contact@fprotection.com.mx</a></li>
              <li><a href="#contact">{t('Mexico City · Monterrey · Guadalajara','Ciudad de México · Monterrey · Guadalajara')}</a></li>
            </ul>
          </div>
        </div>
        <div className="foot-bot">
          <span>{t(`© ${new Date().getFullYear()} FULL PROTECTION AGENCY, LLC. ALL RIGHTS RESERVED.`,`© ${new Date().getFullYear()} FULL PROTECTION AGENCY, LLC. TODOS LOS DERECHOS RESERVADOS.`)}</span>
          <span>fpa@secure:~$ logout<span className="cursor" /></span>
        </div>
      </div>
    </footer>
  );
}

/* ----------------------------------------------------------------
   TWEAKS
---------------------------------------------------------------- */
const PHOS = {
  green: { phos:'#2fe04e', rgb:'47,224,78',  bright:'#5cff7a', dim:'#1f9a33', muted:'#176029', faint:'#0e3a18', border:'#1b5e2a', img:'none' },
  amber: { phos:'#ffb000', rgb:'255,176,0', bright:'#ffd27a', dim:'#a86f0c', muted:'#5a3d08', faint:'#3a2705', border:'#5a3d08', img:'sepia(.6) saturate(2.4) hue-rotate(-72deg) brightness(1.05)' },
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "phosphor": "green",
  "scanlines": 12,
  "glow": 50,
  "effects": true
}/*EDITMODE-END*/;

function App() {
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useReveal();

  useEffect(() => {
    const r = document.documentElement.style;
    const p = PHOS[tw.phosphor] || PHOS.green;
    r.setProperty('--phos', p.phos);
    r.setProperty('--phos-rgb', p.rgb);
    r.setProperty('--phos-bright', p.bright);
    r.setProperty('--dim', p.dim);
    r.setProperty('--muted', p.muted);
    r.setProperty('--faint', p.faint);
    r.setProperty('--border', p.border);
    r.setProperty('--img-filter', p.img);
    r.setProperty('--scan-a', (tw.scanlines / 100 * 0.5).toFixed(3));
    r.setProperty('--glow-a', (tw.glow / 100 * 0.9).toFixed(3));
    document.body.classList.toggle('fx-off', !tw.effects);
  }, [tw]);

  const onNav = useCallback((sel) => {
    const el = document.querySelector(sel);
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 50, behavior: 'smooth' });
  }, []);

  return (
    <React.Fragment>
      <Nav onNav={onNav} />
      <main>
        <Hero onNav={onNav} />
        <MetricsBand />
        <Capabilities />
        <OurOperators />
        <Operations />
        <Deployment />
        <About />
        <LegalEntity onNav={onNav} />
        <Contact onNav={onNav} />
      </main>
      <Footer />

      <TweaksPanel>
        <TweakSection label={t('Phosphor','Fósforo')} />
        <TweakRadio label={t('Color','Color')} value={tw.phosphor} options={['green','amber']} onChange={(v)=>setTweak('phosphor', v)} />
        <TweakSection label="CRT" />
        <TweakSlider label={t('Scanlines','Líneas')} value={tw.scanlines} min={0} max={100} unit="%" onChange={(v)=>setTweak('scanlines', v)} />
        <TweakSlider label={t('Glow','Brillo')} value={tw.glow} min={0} max={100} unit="%" onChange={(v)=>setTweak('glow', v)} />
        <TweakToggle label={t('Animations','Animaciones')} value={tw.effects} onChange={(v)=>setTweak('effects', v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

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