/* APP — orchestrator, tweaks, variant switcher */

const DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#ff3d00",
  "typeScale": "archivo",
  "animIntensity": "max"
}/*EDITMODE-END*/;

const ACCENTS_MONOLITH = [
  { name:'Orange', v:'#ff3d00' },
  { name:'Lime', v:'#d4ff3a' },
  { name:'Cyan', v:'#06d4ff' },
  { name:'Pink', v:'#ff3a8a' },
  { name:'Yellow', v:'#fde047' },
  { name:'White', v:'#ffffff' },
];

function GlobalStyles() {
  return (
    <style>{`
      @keyframes kern-marquee { from { transform: translateX(0) } to { transform: translateX(-50%) } }
      @keyframes kern-pulse { 0%,100% { opacity: 1; transform: scale(1) } 50% { opacity: .5; transform: scale(1.4) } }
      @keyframes kern-bar-pulse { 0%,100% { opacity: 1 } 50% { opacity: .6 } }
      @keyframes kern-scroll-hint { 0% { transform: translateX(-100%) } 100% { transform: translateX(100%) } }
      @keyframes kern-fade-up { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
      @keyframes kern-gradient { 0%,100% { background-position: 0% 50% } 50% { background-position: 100% 50% } }
      /* Hidden by default, shown only on mobile via media query in index.html */
      .mobile-br{display:none}
      html { scroll-behavior: smooth }
      /* scrollbar */
      ::-webkit-scrollbar { width: 10px; height: 10px }
      ::-webkit-scrollbar-track { background: #0a0a0a }
      ::-webkit-scrollbar-thumb { background: rgba(255,255,255,.15); border-radius: 10px }
      ::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,.3) }
    `}</style>
  );
}

function ScrollProgress({ color }) {
  const { y } = useScroll();
  const [p, setP] = useState(0);
  useEffect(() => {
    const total = document.body.scrollHeight - window.innerHeight;
    setP(total > 0 ? y/total : 0);
  }, [y]);
  return (
    <div style={{position:'fixed',top:0,left:0,right:0,height:2,background:'rgba(255,255,255,.05)',zIndex:9998,pointerEvents:'none'}}>
      <div style={{height:'100%',background:color,width:`${p*100}%`,transition:'width .1s linear',boxShadow:`0 0 10px ${color}`}}/>
    </div>
  );
}

function Nav({ variant, setVariant }) {
  const { y, dir } = useScroll();
  const hidden = y > 200 && dir === 'down';
  return (
    <nav style={{
      position:'fixed',top:0,left:0,right:0,zIndex:9997,
      padding:'24px 40px',display:'flex',justifyContent:'space-between',alignItems:'center',
      transform: hidden ? 'translateY(-100%)' : 'translateY(0)',
      transition:'transform .35s cubic-bezier(.2,.8,.2,1)',
      background: y > 40 ? 'rgba(10,10,10,.6)' : 'transparent',
      backdropFilter: y > 40 ? 'blur(20px)' : 'none',
      borderBottom: y > 40 ? '1px solid rgba(255,255,255,.06)' : '1px solid transparent',
    }}>
      <div style={{fontFamily: variant==='monolith' ? 'Archivo,sans-serif' : 'Space Grotesk,sans-serif',fontWeight:900,fontSize:22,letterSpacing:'-.02em'}}>
        {variant === 'monolith' ? 'KERN' : 'kern.'}
      </div>
      <div style={{display:'flex',gap:8,fontFamily:'JetBrains Mono,monospace',fontSize:11,letterSpacing:'.15em',textTransform:'uppercase'}}>
        {[['Servicios','servicios'],['Sistema','sistema'],['Requisitos','requisitos'],['Inversión','precios'],['Casos','casos'],['FAQ','faq']].map(([label, id])=>(
          <a key={label} href={'#'+id} className="nav-link" style={{padding:'10px 14px',color:'rgba(255,255,255,.65)',transition:'color .2s'}} onMouseEnter={e=>e.currentTarget.style.color='#fff'} onMouseLeave={e=>e.currentTarget.style.color='rgba(255,255,255,.65)'}>{label}</a>
        ))}
        <a href={CONTENT.callLink} style={{padding:'10px 16px',marginLeft:12,background:'#fff',color:'#0a0a0a',fontWeight:700}}>Escríbenos por WhatsApp →</a>
      </div>
    </nav>
  );
}

function App() {
  const [accent, setAccent] = usePersisted('kern.accent.v2', DEFAULTS.accent);
  const setVariant = () => {};
  const [typeScale, setTypeScale] = usePersisted('kern.type.v2', DEFAULTS.typeScale);
  const [animIntensity, setAnimIntensity] = usePersisted('kern.anim', DEFAULTS.animIntensity);
  const [tweaksOpen, setTweaksOpen] = useState(false);

  // Tweaks protocol
  useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', onMsg);
    try { window.parent.postMessage({ type: '__edit_mode_available' }, '*'); } catch {}
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const persist = useCallback((edits) => {
    try { window.parent.postMessage({ type:'__edit_mode_set_keys', edits }, '*'); } catch {}
  }, []);

  const accentColors = ACCENTS_MONOLITH;

  // type families
  const bodyFont = typeScale === 'archivo' ? 'Inter,system-ui,sans-serif' :
                   typeScale === 'space' ? 'Space Grotesk,sans-serif' :
                   'Inter,system-ui,sans-serif';
  useEffect(() => { document.body.style.fontFamily = bodyFont; }, [bodyFont]);

  return (
    <>
      <GlobalStyles/>
      <CustomCursor accent={accent} mode="monolith"/>
      <ScrollProgress color={accent}/>
      <Nav variant="monolith" setVariant={setVariant}/>

      <MonolithVariant accent={accent} animIntensity={animIntensity}/>

      {/* Tweaks panel */}
      <div className={'tweaks-panel' + (tweaksOpen ? ' open' : '')}>
        <button className="close-x" onClick={()=>setTweaksOpen(false)}>✕</button>
        <h4>⚙ Tweaks</h4>

        <div className="tweak-group">
          <div style={{fontSize:10,letterSpacing:'.15em',textTransform:'uppercase',color:'rgba(255,255,255,.5)',marginBottom:8}}>Color acento</div>
          <div className="swatch-row">
            {accentColors.map(c => (
              <button key={c.v} className={'swatch' + (accent===c.v?' active':'')} style={{background:c.v}} onClick={()=>{setAccent(c.v);persist({accent:c.v});}} title={c.name}/>
            ))}
          </div>
        </div>

        <div className="tweak-group">
          <div style={{fontSize:10,letterSpacing:'.15em',textTransform:'uppercase',color:'rgba(255,255,255,.5)',marginBottom:8}}>Tipografía</div>
          <select value={typeScale} onChange={e=>{setTypeScale(e.target.value);persist({typeScale:e.target.value});}}>
            <option value="archivo">Archivo + Inter (editorial)</option>
            <option value="space">Space Grotesk (moderna)</option>
          </select>
        </div>

        <div className="tweak-group">
          <div style={{fontSize:10,letterSpacing:'.15em',textTransform:'uppercase',color:'rgba(255,255,255,.5)',marginBottom:8}}>Intensidad animación</div>
          <select value={animIntensity} onChange={e=>{setAnimIntensity(e.target.value);persist({animIntensity:e.target.value});}}>
            <option value="subtle">Sutil</option>
            <option value="medium">Media</option>
            <option value="max">Máxima</option>
          </select>
        </div>

        <div style={{marginTop:16,paddingTop:14,borderTop:'1px solid rgba(255,255,255,.08)',fontSize:10,color:'rgba(255,255,255,.4)',lineHeight:1.5}}>
          Kern Agency · v1
        </div>
      </div>
    </>
  );
}

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