// IdeaSection.jsx — chrome WebGL background + VideoPlayer with lang support

const VERT_SRC = `
  attribute vec2 a_pos;
  void main(){ gl_Position=vec4(a_pos,0.0,1.0); }
`;
const FRAG_SRC = `
  precision highp float;
  uniform vec2  u_res, u_mouse;
  uniform float u_time;
  uniform vec2  u_clicks[8];
  uniform float u_clickTimes[8];
  uniform int   u_clickCount;
  #define TAU 6.28318530718
  float hash(vec2 p){ return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453); }
  float noise(vec2 p){
    vec2 i=floor(p),f=fract(p); f=f*f*(3.0-2.0*f);
    float a=hash(i),b=hash(i+vec2(1,0)),c=hash(i+vec2(0,1)),d=hash(i+vec2(1,1));
    return mix(mix(a,b,f.x),mix(c,d,f.x),f.y);
  }
  float fbm(vec2 p){
    float v=0.0,a=0.5;
    for(int i=0;i<6;i++){v+=a*noise(p);p=p*2.1+vec2(1.3,2.7);a*=0.5;}
    return v;
  }
  vec3 chrome(float t){
    vec3 a=vec3(0.80,0.82,0.88),b=vec3(0.20,0.20,0.22),c=vec3(0.92,0.94,1.00),d=vec3(0.08,0.10,0.14);
    return clamp(a+b*cos(TAU*(c*t+d)),0.0,1.0);
  }
  void main(){
    vec2 uv=gl_FragCoord.xy/u_res; float ar=u_res.x/u_res.y;
    vec2 st=uv*vec2(ar,1.0), ms=(u_mouse/u_res)*vec2(ar,1.0);
    float mdist=length(st-ms);
    float mwave=sin(mdist*20.0-u_time*2.8)*0.07/(mdist*5.0+0.6);
    vec2 q=st+vec2(u_time*0.06,u_time*0.04);
    float f=fbm(q+mwave);
    vec2 r=vec2(fbm(q+f+vec2(1.7,9.2)+u_time*0.08),fbm(q+f+vec2(8.3,2.8)-u_time*0.05));
    float base=fbm(st+1.9*r+mwave*0.8);
    float ripple=0.0;
    for(int i=0;i<8;i++){
      if(i>=u_clickCount) break;
      float age=u_time-u_clickTimes[i];
      if(age<0.0||age>4.0) continue;
      vec2 cp=(u_clicks[i]/u_res)*vec2(ar,1.0);
      float d=length(st-cp);
      ripple+=sin(d*34.0-age*9.0)*exp(-d*2.5)*exp(-age*1.0)*0.22;
    }
    float t=base+ripple;
    vec3 col=chrome(t*1.3+u_time*0.035);
    float vig=1.0-smoothstep(0.25,1.3,length(uv-0.5)*1.5);
    col=mix(col*0.65,col,vig);
    gl_FragColor=vec4(col,1.0);
  }
`;

// ── VideoPlayer ───────────────────────────────────────────────────────────────
const VideoPlayer = ({ videos, t }) => {
  const _t = t || ((k)=>k);
  const [idx,    setIdx]   = React.useState(0);
  const [muted,  setMuted] = React.useState(true);
  const [hover,  setHover] = React.useState(false);
  const [isFull, setIsFull]= React.useState(false);
  const wrapRef  = React.useRef(null);
  const videoRef = React.useRef(null);

  // isMobile 감지
  const [isMobileVP, setIsMobileVP] = React.useState(window.innerWidth < 768);
  React.useEffect(()=>{
    const h=()=>setIsMobileVP(window.innerWidth<768);
    window.addEventListener("resize",h,{passive:true});
    return()=>window.removeEventListener("resize",h);
  },[]);

  // React muted 버그 우회: useLayoutEffect로 DOM 직접 제어 (브라우저 paint 전 동기 실행)
  React.useLayoutEffect(()=>{
    if(!videoRef.current) return;
    videoRef.current.muted = muted;
  },[muted]);

  // src 변경 시 video를 프로그래매틱하게 로드/재생
  // ★ muted 상태 유지: 사운드 ON 상태에서 다음 영상으로 넘어가도 소리 유지
  const mutedRef = React.useRef(muted);
  mutedRef.current = muted; // 항상 최신 값 참조 (useEffect 클로저 캡처 문제 방지)

  React.useEffect(()=>{
    const v = videoRef.current;
    if(!v) return;
    const wasMuted = mutedRef.current; // 전환 직전의 음소거 상태 읽기
    v.muted = wasMuted;               // 이전 상태 그대로 적용 (true로 강제 안 함)
    v.volume = wasMuted ? 0 : 1.0;
    v.src = videos[idx].src;
    v.load();
    const p = v.play();
    if(p) p.catch(()=>{
      // 자동재생 정책으로 소리 있는 재생 실패 시 → 음소거로 폴백
      v.muted = true;
      setMuted(true); // UI 동기화
      v.play().catch(()=>{});
    });
  },[idx]);

  // iOS fullscreen 종료 후 body scroll 복구
  React.useEffect(()=>{
    const v = videoRef.current; if(!v) return;
    const restore = () => {
      document.body.style.removeProperty('overflow');
      document.documentElement.style.removeProperty('overflow');
    };
    v.addEventListener('webkitendfullscreen', restore);
    document.addEventListener('fullscreenchange', restore);
    return () => {
      v.removeEventListener('webkitendfullscreen', restore);
      document.removeEventListener('fullscreenchange', restore);
    };
  }, []);

  const next       = (e)=>{ e.stopPropagation(); setIdx(i=>(i+1)%videos.length); };
  const toggleMute = (e)=>{
    e.stopPropagation();
    setMuted(m=>{
      const next=!m;
      if(videoRef.current){
        videoRef.current.muted = next;
        if(!next) videoRef.current.volume = 1.0;
      }
      return next;
    });
  };

  const toggleFull = (e) => {
    e.stopPropagation();
    const el = wrapRef.current;
    const v  = videoRef.current;
    const isFs = !!(document.fullscreenElement || document.webkitFullscreenElement
                    || (v && v.webkitDisplayingFullscreen));
    if (!isFs) {
      // 동기적으로 능력 체크 (typeof) → iOS gesture context 만료 방지
      const canDivFs = typeof el?.requestFullscreen === 'function'
                    || typeof el?.webkitRequestFullscreen === 'function'
                    || typeof el?.mozRequestFullScreen === 'function';
      const canVideoFs = typeof v?.webkitEnterFullscreen === 'function';

      if (canVideoFs && !canDivFs) {
        // iOS Safari: div fullscreen 불가 → video 직접 전체화면 (동기)
        v.webkitEnterFullscreen();
      } else if (canDivFs) {
        // Android/Chrome: div 전체화면
        const fs = el.requestFullscreen || el.webkitRequestFullscreen || el.mozRequestFullScreen;
        fs.call(el).catch(() => {
          // div fullscreen 실패 시 video 폴백 (지원 여부 이미 동기 확인됨)
          if (canVideoFs) v.webkitEnterFullscreen();
        });
      }
    } else {
      (document.exitFullscreen || document.webkitExitFullscreen)?.call(document);
      v?.webkitExitFullscreen?.();
    }
  };

  React.useEffect(()=>{
    const onChange=()=>{
      const v = videoRef.current;
      setIsFull(!!(document.fullscreenElement || document.webkitFullscreenElement
                   || (v && v.webkitDisplayingFullscreen)));
    };
    document.addEventListener("fullscreenchange",onChange);
    document.addEventListener("webkitfullscreenchange",onChange);
    // iOS: video 요소의 fullscreen 이벤트
    const v = videoRef.current;
    if(v) {
      v.addEventListener("webkitbeginfullscreen", ()=>setIsFull(true));
      v.addEventListener("webkitendfullscreen",   ()=>{ setIsFull(false); document.body.style.removeProperty('overflow'); });
    }
    return()=>{
      document.removeEventListener("fullscreenchange",onChange);
      document.removeEventListener("webkitfullscreenchange",onChange);
    };
  },[]);

  // 스크롤 재생/일시정지 제어
  // rootMargin "20% 0px 300% 0px":
  //   top 20%  → 아이디어 섹션이 뷰포트 위로 20% 벗어나면(≒ 뉴스 섹션 도달 전) 일시정지
  //   bottom 300% → 게임 섹션(3 뷰포트 아래)까지 재생 유지
  React.useEffect(()=>{
    const container = wrapRef.current;
    if(!container) return;
    const obs = new IntersectionObserver(([entry]) => {
      const v = videoRef.current;
      if(!v) return;
      if(entry.isIntersecting) {
        // 화면에 들어옴 → 재생
        if(v.paused) {
          const p = v.play();
          if(p) p.catch(()=>{ v.muted=true; setMuted(true); v.play().catch(()=>{}); });
        }
      } else {
        // 화면 밖으로 나감 → 일시정지 (readyState 2 이상일 때만 — 검정 화면 방지)
        if(!v.paused && v.readyState >= 2) v.pause();
      }
    }, {
      threshold: 0,
      rootMargin: "20% 0px 300% 0px",
    });
    obs.observe(container);
    return () => obs.disconnect();
  },[]);

  // 전체화면: contain (영상 비율 그대로 — 시너 잘림 방지)
  // 일반 뷰: cover (기존 디자인 유지)
  const fit = isFull ? "contain" : "cover";

  const dot=(label,action,active)=>(
    <button onClick={action} style={{
      background:"none",border:"none",
      color:active?"#FFF":"rgba(255,255,255,0.45)",
      fontSize:11,letterSpacing:"0.15em",textTransform:"uppercase",
      fontWeight:500,cursor:"pointer",padding:"4px 0",transition:"color 200ms",
    }}
    onMouseEnter={e=>e.currentTarget.style.color="#FFF"}
    onMouseLeave={e=>e.currentTarget.style.color=active?"#FFF":"rgba(255,255,255,0.45)"}
    >{label}</button>
  );

  const labelKey = videos[idx].labelKey || (idx===0?"filmLabel1":"filmLabel2");

  return (
    <div ref={wrapRef}
      style={{ position:"absolute",inset:0,background:"#0A0A0A" }}
      onMouseEnter={()=>setHover(true)}
      onMouseLeave={()=>setHover(false)}
    >
      {/* onClick 제거 — 모바일에서 버튼 클릭을 전체화면으로 납치하는 문제 수정 */}
      <video ref={videoRef}
        src={videos[0].src}
        autoPlay loop muted playsInline preload="auto"
        style={{ position:"absolute",inset:0,width:"100%",height:"100%",objectFit:fit,display:"block" }}/>

      {/* top bar */}
      <div style={{
        position:"absolute",top:0,left:0,right:0,padding:"16px 20px",
        display:"flex",justifyContent:"space-between",
        background:"linear-gradient(to bottom,rgba(0,0,0,0.5),transparent)",
        opacity:(hover||isMobileVP)?1:0,transition:"opacity 250ms",
        pointerEvents:(hover||isMobileVP)?"auto":"none",
      }}>
        <span style={{ fontSize:10,letterSpacing:"0.2em",textTransform:"uppercase",fontWeight:500,color:"rgba(255,255,255,0.9)" }}>
          {_t(labelKey)}
        </span>
        <span style={{ fontSize:10,letterSpacing:"0.15em",textTransform:"uppercase",fontWeight:500,color:"rgba(255,255,255,0.4)" }}>
          {idx+1} / {videos.length}
        </span>
      </div>

      {/* bottom bar */}
      <div style={{
        position:"absolute",bottom:0,left:0,right:0,padding:"16px 20px",
        display:"flex",justifyContent:"space-between",alignItems:"center",
        background:"linear-gradient(to top,rgba(0,0,0,0.55),transparent)",
        opacity:(hover||isMobileVP)?1:0,transition:"opacity 250ms",
        pointerEvents:(hover||isMobileVP)?"auto":"none",
      }}>
        <div style={{ display:"flex",gap:20 }}>
          {dot(muted?_t("soundOff"):_t("soundOn"),toggleMute,!muted)}
          {videos.length>1&&dot(_t("nextFilm"),next,false)}
        </div>
        <span onClick={toggleFull}
          style={{ fontSize:10,letterSpacing:"0.15em",textTransform:"uppercase",fontWeight:500,color:"rgba(255,255,255,0.35)",cursor:"pointer" }}>
          {isFull?_t("exitFullscreen"):_t("fullscreen")}
        </span>
      </div>
    </div>
  );
};

// ── ChromeCanvas ──────────────────────────────────────────────────────────────
const ChromeCanvas = ({ sectionRef }) => {
  const canvasRef = React.useRef(null);
  const S = React.useRef({ mouse:[0,0],clicks:[],animId:null,start:0 });

  React.useEffect(()=>{
    const canvas=canvasRef.current;
    const gl=canvas.getContext("webgl"); if(!gl) return;
    const mkShader=(type,src)=>{ const s=gl.createShader(type); gl.shaderSource(s,src); gl.compileShader(s); return s; };
    const prog=gl.createProgram();
    gl.attachShader(prog,mkShader(gl.VERTEX_SHADER,VERT_SRC));
    gl.attachShader(prog,mkShader(gl.FRAGMENT_SHADER,FRAG_SRC));
    gl.linkProgram(prog); gl.useProgram(prog);
    const buf=gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER,buf);
    gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);
    const aPos=gl.getAttribLocation(prog,"a_pos");
    gl.enableVertexAttribArray(aPos); gl.vertexAttribPointer(aPos,2,gl.FLOAT,false,0,0);
    const U={
      res:gl.getUniformLocation(prog,"u_res"),mouse:gl.getUniformLocation(prog,"u_mouse"),
      time:gl.getUniformLocation(prog,"u_time"),clicks:gl.getUniformLocation(prog,"u_clicks"),
      clickTimes:gl.getUniformLocation(prog,"u_clickTimes"),clickCount:gl.getUniformLocation(prog,"u_clickCount"),
    };
    S.current.start=performance.now();
    const resize=()=>{ const p=canvas.parentElement; canvas.width=p.offsetWidth; canvas.height=p.offsetHeight; gl.viewport(0,0,canvas.width,canvas.height); };
    resize(); window.addEventListener("resize",resize);
    const frame=()=>{
      const t=(performance.now()-S.current.start)/1000,s=S.current,MAX=8;
      const cxy=[],ct=[];
      for(let i=0;i<MAX;i++){ const c=s.clicks[i]||{x:0,y:0,t:-99}; cxy.push(c.x,canvas.height-c.y); ct.push(c.t); }
      gl.useProgram(prog);
      gl.uniform2f(U.res,canvas.width,canvas.height);
      gl.uniform2f(U.mouse,s.mouse[0],canvas.height-s.mouse[1]);
      gl.uniform1f(U.time,t);
      gl.uniform2fv(U.clicks,cxy); gl.uniform1fv(U.clickTimes,ct);
      gl.uniform1i(U.clickCount,Math.min(s.clicks.length,MAX));
      gl.drawArrays(gl.TRIANGLE_STRIP,0,4);
      s.animId=requestAnimationFrame(frame);
    };
    frame();
    return()=>{ window.removeEventListener("resize",resize); cancelAnimationFrame(S.current.animId); };
  },[]);

  React.useEffect(()=>{
    const sec=sectionRef?.current; if(!sec) return;
    const onMove=(e)=>{ const r=sec.getBoundingClientRect(); S.current.mouse=[e.clientX-r.left,e.clientY-r.top]; };
    const onClick=(e)=>{ const r=sec.getBoundingClientRect(); const t=(performance.now()-S.current.start)/1000; S.current.clicks.unshift({x:e.clientX-r.left,y:e.clientY-r.top,t}); if(S.current.clicks.length>8)S.current.clicks.length=8; };
    sec.addEventListener("mousemove",onMove); sec.addEventListener("click",onClick);
    return()=>{ sec.removeEventListener("mousemove",onMove); sec.removeEventListener("click",onClick); };
  },[sectionRef]);

  return <canvas ref={canvasRef} style={{ position:"absolute",inset:0,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"pan-y" }}/>;
};

// ── IdeaSection ───────────────────────────────────────────────────────────────
const IdeaSection = ({ t, noCanvas }) => {
  const _t = t || ((k)=>k);
  const sectionRef = React.useRef(null);
  const [w, setW] = React.useState(window.innerWidth);
  React.useEffect(()=>{
    const h = ()=>setW(window.innerWidth);
    window.addEventListener("resize",h,{passive:true});
    return ()=>window.removeEventListener("resize",h);
  },[]);
  const isMobile = w < 768;

  return (
    <section ref={sectionRef} style={{
      position:"relative",
      padding: isMobile ? "72px 24px" : "128px 40px",
      overflow:"hidden",
      minHeight: isMobile ? "auto" : 640,
      background: noCanvas ? "transparent" : "#C8CACC",
      cursor:"crosshair",
    }}>
      {!noCanvas && <ChromeCanvas sectionRef={sectionRef}/>}
      <div style={{
        position:"relative", zIndex:2, maxWidth:1400, margin:"0 auto",
        display:"grid",
        gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr",
        gap: isMobile ? 40 : 64,
        alignItems:"center",
      }}>
        {/* 모바일: 영상 먼저, 텍스트 아래 */}
        {isMobile && (
          <div style={{ aspectRatio:"4/3", position:"relative", overflow:"hidden", background:"#1A1A1A" }}>
            <VideoPlayer t={_t} videos={[
              { src:"assets/videos/sinner-3.mp4",          labelKey:"filmLabel2" },
              { src:"assets/videos/idea-steel-desert.mp4", labelKey:"filmLabel1" },
            ]}/>
          </div>
        )}
        <div>
          <div style={{ fontSize:10, letterSpacing:"0.2em", textTransform:"uppercase", fontWeight:500, color:"rgba(0,0,0,0.45)", marginBottom:20 }}>
            {_t("ideaLabel")}
          </div>
          <h2 style={{
            fontFamily:"Georgia,serif",
            fontSize: isMobile ? 22 : 44,
            fontWeight:400, lineHeight:1.45, letterSpacing:"-0.01em",
            color:"#0A0A0A", margin:0, mixBlendMode:"multiply",
          }}>
            {_t("ideaQuote")}
          </h2>
          <div style={{ fontSize:10, letterSpacing:"0.2em", textTransform:"uppercase", fontWeight:500, color:"#1A1A1A", marginTop:32, mixBlendMode:"multiply" }}>
            {_t("ideaTagline")}
          </div>
        </div>
        {/* 데스크탑: 영상 오른쪽 */}
        {!isMobile && (
          <div style={{ aspectRatio:"4/5", position:"relative", overflow:"hidden", background:"#1A1A1A" }}>
            <VideoPlayer t={_t} videos={[
              { src:"assets/videos/sinner-3.mp4",          labelKey:"filmLabel2" },
              { src:"assets/videos/idea-steel-desert.mp4", labelKey:"filmLabel1" },
            ]}/>
          </div>
        )}
      </div>
    </section>
  );
};

window.ChromeCanvas = ChromeCanvas;
window.IdeaSection = IdeaSection;
