/* =============================================================
   Cight 단초점렌즈 — 시야 시뮬레이터 (Field-of-View)
   렌즈 설계 등급 × 처방(도수)으로 "선명한 시야 폭"을 직접 보여준다.
   - 고객 도수가 있으면 자동 반영, 없으면 슬라이더로 시뮬레이션
   - 효과: 선명 영역 크기 · 주변부 흐림 · 가장자리 스웜 · 색수차 · 왜곡 격자
   window.CMP_FOV 로 노출 (app.jsx에서 사용)
   ============================================================= */
(function(){
  const SCENE = ()=> (window.__resources && window.__resources.fov_scene) || "assets/products/fov_scene.jpg";

  // 설계군 → 광학 등급 g (1=가장 넓고 왜곡 적음 · 0=구면 기본)
  const GRADE_FAM = {
    d_personal:1.0, d_dual:0.85, d_inner:0.70, d_thin:0.58,
    d_value:0.50, d_clearcolor:0.50, d_bluelight:0.55, d_spherical:0.18,
  };
  const GRADE_KEY = { bluelight_sph:0.20, bluelight_asp:0.52, bluv:0.55, bluv_fc:0.55, ator_lite:0.48, chemi:0.50 };
  function gradeOf(key){
    if (GRADE_KEY[key] != null) return GRADE_KEY[key];
    const fam = window.DESIGN_ART && window.DESIGN_ART[key];
    return (fam && GRADE_FAM[fam] != null) ? GRADE_FAM[fam] : 0.5;
  }
  // 비교표 전용 표기 (BRIDGE→HI-VISION)
  const NAME_OVR = { bridge:'HI-VISION' };
  function nameOf(key){ const p=window.PRODUCTS&&window.PRODUCTS[key]; return NAME_OVR[key] || (p&&p.name) || key; }
  function krOf(key, lang){
    const tr = (lang!=='ko' && window.CIGHT_PROD && window.CIGHT_PROD[lang] && window.CIGHT_PROD[lang][key]);
    if (tr && tr.kr) return tr.kr;
    const p = window.PRODUCTS && window.PRODUCTS[key];
    return (key==='bridge') ? ({ko:'구면',en:'Spherical',ja:'球面',zh:'球面'}[lang]||'구면') : (p && p.kr) || '';
  }
  // 1.67 기준 양안 가격
  function priceOf(key){
    const T = window.TABLES || {};
    for (const tier in T){ for (const g of T[tier]){ for (const r of g.rows){ if (r.k===key && r.p) return r.p[1]; } } }
    return null;
  }
  const won = (n)=> (n==null?'':n.toLocaleString('ko-KR'));

  const ALL_KEYS = ()=> Object.keys(window.PRODUCTS||{});

  // 효과 파라미터 계산
  function params(g, power, intensity){
    const k = intensity;                          // 1=정직 · 1.5=강조
    const Pn = Math.min(power, 8) / 8;            // 0~1 도수 비중
    const inv = 1 - g;
    let clearR = 30 + g*38 - Pn*30*(1 - g*0.65);  // 선명 영역 반경(%)
    clearR = Math.max(12, Math.min(70, clearR));
    const edgeR = Math.min(96, clearR + 24);
    const blur  = (2 + inv*15 + Pn*14*inv) * k;
    const ca    = (inv*4.5 + Pn*5*inv) * k;
    const swim  = 1 + (inv*0.045 + Pn*0.05*inv) * k;
    const warp  = (inv*0.55 + Pn*0.65*inv) * k;
    const vig   = Math.min(0.62, 0.14 + inv*0.34 + Pn*0.12*inv);
    const cf    = Math.round((clearR-12)/58*100);  // "선명 시야" 친화 수치
    return { clearR, edgeR, blur, ca, swim, warp, vig, cf };
  }

  // 왜곡 격자 (왜곡 클수록 직선이 바깥으로 휨)
  function GridSVG({ warp }){
    const N = 6, S = 100/N, w = warp;
    const bow = (t)=> { const d = (t-0.5)*2; return d*d*Math.sign(d); }; // -1..1, 가장자리에서 큼
    const lines = [];
    for (let i=1;i<N;i++){
      const p = i*S, t = i/N, off = bow(t)*w*9;
      lines.push(<path key={'v'+i} d={`M ${p} 0 Q ${p+off} 50 ${p} 100`} />);
      lines.push(<path key={'h'+i} d={`M 0 ${p} Q 50 ${p+off} 100 ${p}`} />);
    }
    return (
      <svg className="fov-grid" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
        {lines}
      </svg>
    );
  }

  function Lens({ side, keyId, g, power, intensity, showGrid, lang, L, rec }){
    const P = params(g, power, intensity);
    const mask = `radial-gradient(circle at 50% 50%, rgba(0,0,0,0) 0%, rgba(0,0,0,0) ${P.clearR}%, #000 ${P.edgeR}%)`;
    const vars = {
      '--scene': `url("${SCENE()}")`,
      WebkitMaskImage: mask, maskImage: mask,
    };
    const sceneStyle = { backgroundImage:`url("${SCENE()}")` };
    const cf = P.cf;
    const price = priceOf(keyId);
    return (
      <div className="fov-lens-wrap">
        <div className={"fov-lens"+(side==='r'?" prem":"")}>
          {/* 선명 기본 */}
          <div className="fov-scene base" style={sceneStyle} />
          {/* 주변부 흐림 + 스웜 */}
          <div className="fov-scene blur" style={Object.assign({}, sceneStyle, { filter:`blur(${P.blur}px)`, transform:`scale(${P.swim})`, WebkitMaskImage:mask, maskImage:mask })} />
          {/* 색수차(채널 분리) */}
          <div className="fov-scene ca" style={Object.assign({}, sceneStyle, { filter:`blur(${P.blur}px) url(#fovR)`, transform:`scale(${P.swim}) translateX(${P.ca}px)`, WebkitMaskImage:mask, maskImage:mask })} />
          <div className="fov-scene ca" style={Object.assign({}, sceneStyle, { filter:`blur(${P.blur}px) url(#fovB)`, transform:`scale(${P.swim}) translateX(${-P.ca}px)`, WebkitMaskImage:mask, maskImage:mask })} />
          {showGrid && <GridSVG warp={P.warp} />}
          {/* 비네팅 */}
          <div className="fov-vig" style={{ background:`radial-gradient(circle at 50% 50%, rgba(8,14,18,0) ${P.clearR*0.7}%, rgba(8,14,18,${P.vig}) 100%)` }} />
          {/* 선명 영역 표시 링 */}
          <div className="fov-ring" style={{ width:`${P.clearR*2}%`, height:`${P.clearR*2}%` }} />
          <span className="fov-clearlab" style={{ bottom:`calc(50% + ${P.clearR}% + 6px)` }}>{L.clearZone}</span>
        </div>
        <div className="fov-meta">
          <div className="fov-meta-head">
            <span className="fov-side">{side==='r'? L.sideRec : L.sideBasic}</span>
            <b className="fov-pname">{nameOf(keyId)}</b>
            <em className="fov-pkr">{krOf(keyId, lang)}</em>
          </div>
          <div className="fov-cf">
            <div className="fov-cf-bar"><i style={{ width: Math.max(6, Math.min(100, cf))+'%' }} /></div>
            <span className="fov-cf-num">{cf}<small>%</small></span>
            <span className="fov-cf-lab">{L.clearField}</span>
          </div>
          {price!=null && <div className="fov-price"><span>{L.priceLab}</span><b>{won(price)}<small>{L.won}</small></b></div>}
        </div>
      </div>
    );
  }

  function Select({ value, onChange, lang }){
    return (
      <select className="fov-select" value={value} onChange={e=>onChange(e.target.value)}>
        {ALL_KEYS().map(k=>(<option key={k} value={k}>{nameOf(k)} · {krOf(k,lang)}</option>))}
      </select>
    );
  }

  function CMP_FOV({ rx, lang, setLang, onHome, onBack, LangSwitch }){
    const L = (window.CIGHT_FOV && window.CIGHT_FOV[lang]) || (window.CIGHT_FOV && window.CIGHT_FOV.ko) || {};
    // 기본 추천 산정
    const recAll = (rx && typeof window.CIGHT_recommend==='function') ? window.CIGHT_recommend(rx, new Set(ALL_KEYS())) : null;
    const topPick = recAll ? Object.keys(recAll.picks).find(k=>recAll.picks[k]==='상') : null;

    const hasRx = !!(rx && rx.od && (rx.od.sph!=null || rx.od.cyl!=null));
    const rxSph = hasRx ? Math.abs(rx.od.sph||0) : 3;
    const rxCyl = hasRx ? Math.abs(rx.od.cyl||0) : 1;

    const [leftKey, setLeft]   = React.useState('bridge');
    const [rightKey, setRight] = React.useState(topPick || 'smartlife_ind');
    const [sph, setSph] = React.useState(rxSph);
    const [cyl, setCyl] = React.useState(rxCyl);
    const [useRx, setUseRx] = React.useState(hasRx);
    const [showGrid, setShowGrid] = React.useState(true);
    const [intensity, setIntensity] = React.useState(1.0);  // 정직 기본 (강조 토글 제공)

    const effSph = useRx && hasRx ? rxSph : sph;
    const effCyl = useRx && hasRx ? rxCyl : cyl;
    const power = effSph + effCyl;

    const gL = gradeOf(leftKey), gR = gradeOf(rightKey);

    return (
      <div className="fov-app">
        {/* 색수차 채널 필터 */}
        <svg className="fov-defs" aria-hidden="true" focusable="false">
          <filter id="fovR" x="-20%" y="-20%" width="140%" height="140%">
            <feColorMatrix type="matrix" values="1 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 1 0" />
          </filter>
          <filter id="fovB" x="-20%" y="-20%" width="140%" height="140%">
            <feColorMatrix type="matrix" values="0 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 1 0" />
          </filter>
        </svg>

        <div className="fov-top">
          <div className="fov-brand">
            <img className="fov-logo" src={(window.__resources&&window.__resources.logo_teal)||"assets/cight_logo_teal.png"} alt="Cight" role="button" tabIndex={0} title={L.home} style={{cursor:'pointer'}} onClick={onHome} onKeyDown={(e)=>{ if(e.key==='Enter'||e.key===' '){ e.preventDefault(); onHome&&onHome(); } }} />
            <div>
              <div className="fov-kicker">{L.kicker}</div>
              <div className="fov-title">{(rx&&rx.name)? window.CIGHT_FOV_tpl(L.titleFor,{n:rx.name}) : L.title}</div>
            </div>
          </div>
          <div className="fov-top-r">
            {LangSwitch && <LangSwitch lang={lang} setLang={setLang} />}
            <button className="fov-back" onClick={onBack}>{L.back}</button>
          </div>
        </div>

        <div className="fov-stage">
          <Lens side="l" keyId={leftKey} g={gL} power={power} intensity={intensity} showGrid={showGrid} lang={lang} L={L} />
          <div className="fov-vs"><span>{L.vs}</span></div>
          <Lens side="r" keyId={rightKey} g={gR} power={power} intensity={intensity} showGrid={showGrid} lang={lang} L={L} />
        </div>

        <div className="fov-ctl">
          <div className="fov-ctl-cell">
            <label className="fov-ctl-lab">{L.pickBasic}</label>
            <Select value={leftKey} onChange={setLeft} lang={lang} />
          </div>
          <div className="fov-ctl-rx">
            <div className="fov-rx-head">
              <span className="fov-rx-lab">{useRx&&hasRx ? L.rxFrom : L.rxSim}</span>
              {hasRx && (
                <button className={"fov-rx-toggle"+(useRx?" on":"")} onClick={()=>setUseRx(v=>!v)}>
                  {useRx ? L.rxUseCustom : L.rxUseManual}
                </button>
              )}
            </div>
            <div className="fov-slider" data-dim={(useRx&&hasRx)?'lock':''}>
              <span className="fov-sl-name">SPH</span>
              <input type="range" min="0" max="10" step="0.25" value={effSph} disabled={useRx&&hasRx} onChange={e=>setSph(parseFloat(e.target.value))} />
              <span className="fov-sl-val">-{effSph.toFixed(2)}</span>
            </div>
            <div className="fov-slider" data-dim={(useRx&&hasRx)?'lock':''}>
              <span className="fov-sl-name">CYL</span>
              <input type="range" min="0" max="4" step="0.25" value={effCyl} disabled={useRx&&hasRx} onChange={e=>setCyl(parseFloat(e.target.value))} />
              <span className="fov-sl-val">-{effCyl.toFixed(2)}</span>
            </div>
            <div className="fov-power">{L.power} <b>{(power).toFixed(2)}D</b> · {power>=6?L.pHigh:power>=3?L.pMid:L.pLow}</div>
          </div>
          <div className="fov-ctl-cell">
            <label className="fov-ctl-lab">{L.pickRec}</label>
            <Select value={rightKey} onChange={setRight} lang={lang} />
          </div>
        </div>

        <div className="fov-foot">
          <label className="fov-chk"><input type="checkbox" checked={showGrid} onChange={e=>setShowGrid(e.target.checked)} /><span>{L.grid}</span></label>
          <div className="fov-int">
            <span>{L.intensity}</span>
            <button className={intensity<=1.0?"on":""} onClick={()=>setIntensity(1.0)}>{L.intHonest}</button>
            <button className={intensity>1.0?"on":""} onClick={()=>setIntensity(1.5)}>{L.intDrama}</button>
          </div>
          <span className="fov-note">{L.note}</span>
        </div>
      </div>
    );
  }

  window.CMP_FOV = CMP_FOV;
})();
