const { useState, useEffect, useRef, useLayoutEffect } = React;
const C = window.SANS_COPY;
const L = window.SANS_LINKS;

/* ---------- state-driven reveal (survives re-renders) ---------- */
function useInView(opts){
  opts=opts||{};
  const ref=useRef(null);
  const [seen,setSeen]=useState(false);
  useEffect(()=>{
    const el=ref.current; if(!el) return;
    if(window.matchMedia("(prefers-reduced-motion: reduce)").matches){ setSeen(true); return; }
    let done=false;
    const check=()=>{
      if(done) return;
      const r=el.getBoundingClientRect();
      const vh=window.innerHeight||document.documentElement.clientHeight;
      const trigger=opts.early? vh+280 : vh*0.9;
      if(r.top<trigger && r.bottom>-40){ done=true; setSeen(true); cleanup(); }
    };
    const cleanup=()=>{
      window.removeEventListener("scroll",check);
      window.removeEventListener("resize",check);
    };
    window.addEventListener("scroll",check,{passive:true});
    window.addEventListener("resize",check);
    check();
    const t1=setTimeout(check,80);
    const t2=setTimeout(check,360);
    return ()=>{cleanup();clearTimeout(t1);clearTimeout(t2);};
  },[]);
  return [ref,seen];
}
function Reveal({as="div",className="",delay=0,children,...rest}){
  const Tag=as;
  const [ref,seen]=useInView();
  const [done,setDone]=useState(false);
  useEffect(()=>{ if(!seen) return; const t=setTimeout(()=>setDone(true),1100+delay); return ()=>clearTimeout(t); },[seen]);
  return <Tag ref={ref} className={className+" reveal"+(seen?" in":"")+(done?" done":"")}
    style={{animationDelay:delay+"ms",...(rest.style||{})}} {...(()=>{const{style,...r}=rest;return r;})()}>{children}</Tag>;
}
/* headline with line masks, state-driven */
function HeadLines({items,accentIndex,className=""}){
  const [ref,seen]=useInView();
  const [done,setDone]=useState(false);
  useEffect(()=>{ if(!seen) return; const t=setTimeout(()=>setDone(true),1500); return ()=>clearTimeout(t); },[seen]);
  return (
    <span ref={ref} className={"lines"+(seen?" in":"")+(done?" done":"")+(className?" "+className:"")}>
      {items.map((t,i)=>(
        <span className="ln" key={i}><span className={i===accentIndex?"accent":""}>{t}</span></span>
      ))}
    </span>
  );
}

/* ---------- icons ---------- */
const IcYT=()=>(<svg viewBox="0 0 24 24" fill="currentColor"><path d="M23.5 6.2a3 3 0 0 0-2.1-2.1C19.5 3.5 12 3.5 12 3.5s-7.5 0-9.4.6A3 3 0 0 0 .5 6.2 31 31 0 0 0 0 12a31 31 0 0 0 .5 5.8 3 3 0 0 0 2.1 2.1c1.9.6 9.4.6 9.4.6s7.5 0 9.4-.6a3 3 0 0 0 2.1-2.1A31 31 0 0 0 24 12a31 31 0 0 0-.5-5.8zM9.6 15.6V8.4l6.3 3.6-6.3 3.6z"/></svg>);
const IcIG=()=>(<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.3" cy="6.7" r="1.2" fill="currentColor" stroke="none"/></svg>);
const IcWA=()=>(<svg viewBox="0 0 24 24" fill="currentColor"><path d="M.5 23.5l1.6-5.8a11.1 11.1 0 1 1 4.2 4.1L.5 23.5zM6.6 20l.4.2a9.2 9.2 0 1 0-3.2-3.2l.2.4-1 3.5 3.6-.9zM17.5 14.4c-.2-.1-1.5-.7-1.7-.8s-.4-.1-.5.1-.6.8-.8 1-.3.2-.5.1a7.4 7.4 0 0 1-2.2-1.3 8.2 8.2 0 0 1-1.5-1.9c-.2-.3 0-.4.1-.5l.4-.4.2-.4a.4.4 0 0 0 0-.4l-.8-1.9c-.2-.5-.4-.4-.5-.5h-.5a.9.9 0 0 0-.7.3 2.8 2.8 0 0 0-.9 2.1A4.9 4.9 0 0 0 8.5 12a11 11 0 0 0 4.2 3.7c.6.2 1 .4 1.4.5a3.4 3.4 0 0 0 1.5.1c.5-.1 1.5-.6 1.7-1.2s.2-1.1.1-1.2-.2-.1-.4-.2z"/></svg>);
const IcMail=()=>(<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2.5" y="4.5" width="19" height="15" rx="2.5"/><path d="M3 6.5l9 6 9-6"/></svg>);

/* ---------- live cinematic background ---------- */
function LiveBg({img}){
  return (
    <div className="livebg" aria-hidden="true">
      <div className="img" style={{backgroundImage:`url(img/${img})`}}></div>
      <div className="blob b1"></div>
      <div className="blob b2"></div>
      <div className="vig"></div>
    </div>
  );
}

/* ---------- TOP BAR ---------- */
function TopBar({t,lang,setLang}){
  const [s,setS]=useState(false);
  useEffect(()=>{
    const on=()=>setS(window.scrollY>40);
    on(); window.addEventListener("scroll",on,{passive:true});
    return ()=>window.removeEventListener("scroll",on);
  },[]);
  return (
    <header className={"topbar"+(s?" scrolled":"")}>
      <a className="brand" href="#top" aria-label="Sans Filmes"><img src="img/logo-white.png" alt="Grupo Sans"/></a>
      <div className="right">
        <span className="status"><span className="dot"></span>{t.nav_status}</span>
        <button className="langbtn" onClick={()=>setLang(lang==="pt"?"en":"pt")}>{t.nav_lang}</button>
      </div>
    </header>
  );
}

/* ---------- HERO ---------- */
function Hero({t,bg}){
  return (
    <section className="hero" id="top">
      <LiveBg img={bg}/>
      <div className="hero-scrim" aria-hidden="true"></div>
      <span className="sidelabel">{t.side}</span>
      <div className="wrap">
        <Reveal className="hero-kicker"><span className="kicker">{t.hero_kicker}</span></Reveal>
        <h1><HeadLines items={t.hero_head} accentIndex={2}/></h1>
        <Reveal as="p" className="hero-sub" delay={140}>{t.hero_sub}</Reveal>
        <div className="hero-foot">
          <Reveal as="a" className="scrollcue" delay={240} href="#manifesto"><span className="bar"></span>{t.hero_scroll}</Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---------- SEAL / CREDENTIAL ---------- */
const CRED_LOGOS=["img/org-ebc.png","img/org-fsa.png","img/org-tvbrasil.png"];
function Seal({t}){
  return (
    <section className="seal" id="reconhecimento">
      <div className="glowline"></div>
      <div className="wrap seal-grid">
        <div>
          <Reveal as="span" className="kicker">{t.seal_kicker}</Reveal>
          <Reveal as="h2" className="seal-title" delay={80}>{t.seal_title_pre}<span className="accent">{t.seal_title_em}</span>{t.seal_title_post}</Reveal>
          <Reveal as="p" className="seal-note" delay={160}>{t.seal_note}</Reveal>
        </div>
        <div className="orgs-wrap">
          <Reveal as="span" className="orgs-label">{t.seal_orgs_label}</Reveal>
          <Reveal className="orgs">
            {t.seal_orgs.map((o,i)=>(
              <div className="org" key={i}>
                <img className="org-logo" src={CRED_LOGOS[i]} alt={o}/>
              </div>
            ))}
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---------- MANIFESTO ---------- */
function Manifesto({t}){
  const words=t.man_lead.split(" ");
  const last=words.pop();
  const close=t.man_close.replace(/Sans Filmes\.?$/,"");
  return (
    <section className="man" id="manifesto">
      <div className="bgword" aria-hidden="true">SANS</div>
      <div className="wrap inner">
        <Reveal as="span" className="kicker">{t.man_kicker}</Reveal>
        <h2 className="man-lead"><HeadLines items={[words.join(" ")]} accentIndex={-1}/><em style={{display:"block"}}>{last}</em></h2>
        <div className="man-body">
          {t.man_paras.map((p,i)=>(<Reveal as="p" key={i} delay={i*90}>{p}</Reveal>))}
        </div>
        <Reveal as="p" className="man-close" delay={120}>{close}<span className="accent">Sans Filmes.</span></Reveal>
      </div>
    </section>
  );
}

/* ---------- REEL ---------- */
function Reel({t}){
  const [ref,seen]=useInView({early:true});
  return (
    <section className="reel" id="reel">
      <div className="wrap">
        <div className="reel-head">
          <div>
            <Reveal as="span" className="kicker">{t.reel_kicker}</Reveal>
            <Reveal as="h2" delay={80}>{t.reel_title}</Reveal>
            <Reveal as="p" className="sub" delay={150}>{t.reel_sub}</Reveal>
          </div>
          <Reveal as="a" className="ytlink" delay={120} href={L.youtube} target="_blank" rel="noopener"><IcYT/>{t.reel_cta}</Reveal>
        </div>
        <Reveal className="player">
          <span className="frame-tag"><span style={{width:7,height:7,borderRadius:"50%",background:"var(--red)",display:"inline-block"}}></span>REC · Sans Filmes</span>
          <span ref={ref}></span>
          {seen && <iframe src={L.uploads} title="Sans Filmes · YouTube" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen></iframe>}
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- WHERE ---------- */
function Where({t}){
  const items=[...t.where_states,...t.where_states];
  return (
    <section className="where" id="onde">
      <div className="wrap where-top">
        <Reveal as="span" className="kicker">{t.where_kicker}</Reveal>
        <Reveal as="span" className="where-hq" delay={80}>{t.where_hq}</Reveal>
      </div>
      <div className="marquee">
        <div className="track">
          {items.map((s,i)=>(<span className={"it"+(i%2?" ghost":"")} key={i}>{s}</span>))}
        </div>
      </div>
    </section>
  );
}

/* ---------- CTA ---------- */
function CTA({t}){
  const [email,setEmail]=useState("");
  const [state,setState]=useState("idle");
  const submit=(e)=>{
    e.preventDefault();
    const ok=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
    if(!ok){setState("err");return;}
    try{
      const list=JSON.parse(localStorage.getItem("sans_waitlist")||"[]");
      list.push({email:email.trim(),at:Date.now()});
      localStorage.setItem("sans_waitlist",JSON.stringify(list));
    }catch(err){}
    setState("ok");
  };
  return (
    <section className="cta" id="cta">
      <LiveBg img="bg-03.jpg"/>
      <div className="wrap">
        <Reveal as="span" className="kicker">{t.cta_kicker}</Reveal>
        <Reveal as="h2" delay={70}>{t.cta_title}</Reveal>
        <Reveal as="p" className="sub" delay={130}>{t.cta_sub}</Reveal>
        <Reveal as="form" className="signup" delay={190} onSubmit={submit} noValidate>
          {state==="ok" ? (
            <div className="submitted">{t.cta_ok}</div>
          ):(<>
            <label className="field">
              <input type="email" placeholder={t.cta_ph} value={email}
                onChange={e=>{setEmail(e.target.value);if(state==="err")setState("idle");}} aria-label="email"/>
            </label>
            <button type="submit" className="btn-red">{t.cta_btn}</button>
            {state==="err" && <span className="err">{t.cta_err}</span>}
          </>)}
        </Reveal>
        <Reveal className="cta-or" delay={120}>{t.cta_or}</Reveal>
        <Reveal className="actions" delay={160}>
          <a className="chip wpp" href={L.whatsapp} target="_blank" rel="noopener"><IcWA/>{t.cta_wpp}</a>
          <a className="chip ig" href={L.instagram} target="_blank" rel="noopener"><IcIG/>Instagram</a>
          <a className="chip yt" href={L.youtube} target="_blank" rel="noopener"><IcYT/>YouTube</a>
          <a className="chip mail" href={"mailto:"+L.email}><IcMail/>{L.email}</a>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- FOOTER ---------- */
function Footer({t}){
  const yr=new Date().getFullYear();
  return (
    <footer className="foot">
      <div className="wrap">
        <div className="row">
          <div>
            <img src="img/logo-white.png" alt="Grupo Sans" style={{height:38}}/>
            <p className="tag" style={{marginTop:22}}>{t.foot_tag}</p>
          </div>
          <div className="meta">
            <a href={L.whatsapp} target="_blank" rel="noopener">{L.whatsapp_label}</a>
            <a href={"mailto:"+L.email}>{L.email}</a>
            <span>Rio Branco · Acre · Brasil</span>
          </div>
        </div>
        <div className="rights">
          <span>© {yr} {t.foot_rights}</span>
          <span>{t.nav_status}</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------- TWEAKS ---------- */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#c40606",
  "heroBg": "bg-03.jpg",
  "motion": "marcante",
  "grain": true
}/*EDITMODE-END*/;

function Tweaks({t,setT,lang,setLang}){
  return (
    <TweaksPanel>
      <TweakSection label={lang==="pt"?"Marca":"Brand"} />
      <TweakColor label={lang==="pt"?"Vermelho":"Red"} value={t.accent}
        options={["#c40606","#ff1e1e","#e10600","#a30000"]}
        onChange={v=>setT("accent",v)} />
      <TweakRadio label={lang==="pt"?"Idioma":"Language"} value={lang}
        options={["pt","en"]} onChange={v=>setLang(v)} />
      <TweakSection label={lang==="pt"?"Atmosfera":"Atmosphere"} />
      <TweakSelect label="Background" value={t.heroBg}
        options={[{value:"bg-03.jpg",label:"Fumaça / Smoke"},{value:"bg-01.jpg",label:"Arco / Arch"}]}
        onChange={v=>setT("heroBg",v)} />
      <TweakRadio label={lang==="pt"?"Movimento":"Motion"} value={t.motion}
        options={["sutil","marcante"]} onChange={v=>setT("motion",v)} />
      <TweakToggle label={lang==="pt"?"Granulado de filme":"Film grain"} value={t.grain}
        onChange={v=>setT("grain",v)} />
    </TweaksPanel>
  );
}

/* ---------- MOTION (motion.dev) enhancements — additive, gated ---------- */
function setupMotion(opts){
  const M=window.Motion; if(!M) return ()=>{};
  if(opts&&opts.reduce) return ()=>{};
  if(window.matchMedia("(prefers-reduced-motion: reduce)").matches) return ()=>{};
  const {scroll,animate}=M;
  const cleanups=[];
  const reg=(c)=>{ if(typeof c==="function") cleanups.push(c); };
  const spring={type:"spring",stiffness:320,damping:20};

  // scroll progress bar
  const bar=document.querySelector(".scrollbar");
  if(bar) reg(scroll((p)=>{ bar.style.transform="scaleX("+p+")"; }));

  // hero depth parallax
  const hero=document.querySelector(".hero");
  const img=document.querySelector(".hero .livebg .img");
  const content=document.querySelector(".hero .wrap");
  if(hero&&img) reg(scroll(animate(img,{y:["0px","150px"],scale:[1.08,1.22]},{ease:"linear"}),{target:hero,offset:["start start","end start"]}));
  if(hero&&content) reg(scroll(animate(content,{y:["0px","-80px"],opacity:[1,0.15]},{ease:"linear"}),{target:hero,offset:["start start","end start"]}));

  // manifesto watermark drift
  const man=document.querySelector(".man");
  const bw=document.querySelector(".man .bgword");
  if(man&&bw) reg(scroll(animate(bw,{x:["7%","-13%"]},{ease:"linear"}),{target:man,offset:["start end","end start"]}));

  // cta glow parallax
  const cta=document.querySelector(".cta");
  const cimg=document.querySelector(".cta .livebg .img");
  if(cta&&cimg) reg(scroll(animate(cimg,{y:["-60px","60px"]},{ease:"linear"}),{target:cta,offset:["start end","end start"]}));

  // marquee skew by scroll velocity
  const marquee=document.querySelector(".marquee");
  if(marquee){
    let last=window.scrollY,vel=0,raf;
    const onScroll=()=>{ const y=window.scrollY; vel=Math.max(-16,Math.min(16,(y-last)*0.35)); last=y; };
    window.addEventListener("scroll",onScroll,{passive:true});
    const tick=()=>{ vel*=0.85; marquee.style.transform="skewX("+vel.toFixed(2)+"deg)"; raf=requestAnimationFrame(tick); };
    tick();
    reg(()=>{ window.removeEventListener("scroll",onScroll); cancelAnimationFrame(raf); marquee.style.transform=""; });
  }

  // magnetic primary button
  const mag=document.querySelector(".btn-red");
  if(mag){
    const move=(e)=>{ const r=mag.getBoundingClientRect(); const mx=e.clientX-(r.left+r.width/2), my=e.clientY-(r.top+r.height/2); animate(mag,{x:mx*0.3,y:my*0.45},{type:"spring",stiffness:300,damping:18}); };
    const leave=()=>animate(mag,{x:0,y:0},{type:"spring",stiffness:240,damping:16});
    mag.addEventListener("pointermove",move); mag.addEventListener("pointerleave",leave);
    reg(()=>{ mag.removeEventListener("pointermove",move); mag.removeEventListener("pointerleave",leave); });
  }

  // hover spring on cards / chips / links
  document.querySelectorAll(".chip,.ytlink").forEach(el=>{
    const enter=()=>animate(el,{scale:1.035},spring);
    const leave=()=>animate(el,{scale:1},{type:"spring",stiffness:300,damping:22});
    el.addEventListener("pointerenter",enter); el.addEventListener("pointerleave",leave);
    reg(()=>{ el.removeEventListener("pointerenter",enter); el.removeEventListener("pointerleave",leave); });
  });

  window.__motionRan=(window.__motionRan||0)+1;
  return ()=>{ cleanups.forEach(c=>{ try{c()}catch(e){} }); };
}

/* ---------- APP ---------- */
function App(){
  const [lang,setLang]=useState(()=>localStorage.getItem("sans_lang")||"pt");
  const [t,setT]=useTweaks(TWEAK_DEFAULTS);
  const copy=C[lang];

  useEffect(()=>{localStorage.setItem("sans_lang",lang);
    document.documentElement.lang=lang==="pt"?"pt-BR":"en";},[lang]);

  useEffect(()=>{
    const r=document.documentElement.style;
    r.setProperty("--red",t.accent);
    r.setProperty("--red-hot",t.accent==="#c40606"?"#ff1e1e":t.accent);
    r.setProperty("--grain",t.grain?(t.motion==="sutil"?".05":".08"):"0");
    r.setProperty("--glow",t.motion==="sutil"?".55":"1");
    const sys=window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    document.body.toggleAttribute("data-reduce",t.motion==="sutil"||sys);
  },[t]);

  // Motion.dev enhancements — (re)bind after each render of the section tree
  useEffect(()=>{
    let cleanup=()=>{};
    const reduce=t.motion==="sutil";
    const run=()=>{ cleanup(); const id=setTimeout(()=>{ cleanup=setupMotion({reduce})||(()=>{}); },80); cleanup=()=>clearTimeout(id); };
    if(window.__motionReady) run();
    else window.addEventListener("motion-ready",run,{once:true});
    return ()=>{ cleanup(); window.removeEventListener("motion-ready",run); };
  },[lang,t.motion,t.heroBg]);

  return (
    <React.Fragment key={lang}>
      <TopBar t={copy} lang={lang} setLang={setLang}/>
      <main>
        <Hero t={copy} bg={t.heroBg}/>
        <Seal t={copy}/>
        <Manifesto t={copy}/>
        <Reel t={copy}/>
        <Where t={copy}/>
        <CTA t={copy}/>
      </main>
      <Footer t={copy}/>
      <Tweaks t={t} setT={setT} lang={lang} setLang={setLang}/>
    </React.Fragment>
  );
}

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