/* =============================================================
   Cight 선글라스렌즈 가격 비교표 — 메인 앱
   카테고리(단초점/누진/스포츠/변색/VR)를 탭으로, 각 탭은 등급 컬럼(좌=이상적).
   compare/styles.css 의 .cmp-* / .gd-* / .gp-* 클래스를 재사용.
   ============================================================= */
const SG_CATS = window.SG_CATS;
const SG_LANGS = window.SG_LANGS;
const sgWon = (n) => (n == null ? '' : n.toLocaleString('ko-KR'));
const sgTr = (v, lang) => (v == null ? '' : (typeof v === 'string' ? v : (v[lang] || v.ko || '')));

const SG_LANG0 = (() => { try {
  const p = new URLSearchParams(location.search).get('lang');
  const v = (p || localStorage.getItem('cight_lang') || 'ko');
  return (window.SG_I18N && window.SG_I18N[v]) ? v : 'ko';
} catch (e) { return 'ko'; } })();
const L_ = (lang) => (window.SG_I18N && window.SG_I18N[lang]) || window.SG_I18N.ko;
const tpl = (s, o) => (s || '').replace(/\{(\w+)\}/g, (_, k) => (o && o[k] != null) ? o[k] : '');

function SG_LangSwitch({ lang, setLang }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const cur = SG_LANGS.find(l => l.id === lang) || SG_LANGS[0];
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('mousedown', onDoc); document.removeEventListener('keydown', onKey); };
  }, [open]);
  return (
    <div className={"cmp-lang" + (open ? " open" : "")} ref={ref}>
      <button type="button" className="cmp-lang-trigger" aria-haspopup="listbox" aria-expanded={open} onClick={() => setOpen(o => !o)}>
        <svg className="cmp-lang-ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" aria-hidden="true"><circle cx="12" cy="12" r="9" /><path d="M3 12h18" /><path d="M12 3c2.6 2.4 4 5.6 4 9s-1.4 6.6-4 9c-2.6-2.4-4-5.6-4-9s1.4-6.6 4-9z" /></svg>
        <span className="cmp-lang-flag">{cur.flag}</span>
        <span className="cmp-lang-cur">{cur.native}</span>
        <svg className="cmp-lang-chev" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M6 9l6 6 6-6" /></svg>
      </button>
      {open && (
        <ul className="cmp-lang-menu" role="listbox">
          {SG_LANGS.map(l => (
            <li key={l.id} role="option" aria-selected={lang === l.id} className={"cmp-lang-opt" + (lang === l.id ? " on" : "")} onClick={() => { setLang(l.id); setOpen(false); }}>
              <span className="cmp-lang-flag">{l.flag}</span>
              <span className="cmp-lang-name">{l.native}</span>
              {lang === l.id && <svg className="cmp-lang-check" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 12l5 5L20 7" /></svg>}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

const SG_LOGO = () => (window.__resources && window.__resources.logo_teal) || "assets/cight_logo_teal.png";

/* 변색 렌즈 핵심 비교 요소 아이콘 (속도·농도·투명도) */
const SG_FOCUS_ICONS = {
  speed: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M13 3L4 14h6l-1 7 9-11h-6l1-7z" />
    </svg>
  ),
  shade: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <circle cx="12" cy="12" r="8" />
      <path d="M12 4a8 8 0 0 0 0 16z" fill="currentColor" stroke="none" />
    </svg>
  ),
  clear: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M12 3c3.5 4 6 7 6 10a6 6 0 0 1-12 0c0-3 2.5-6 6-10z" />
      <path d="M9.5 13.5a2.5 2.5 0 0 0 2.5 2.5" />
    </svg>
  ),
};

/* 최적화가 해결하는 불편 3가지 아이콘 (어지럼·울렁임·착용 불편) */
const SG_OPT_ICONS = [
  (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" key="dizzy">
      <path d="M12 12c0-1.66 1.34-3 3-3s3 1.34 3 3-1.79 4.5-6 4.5S5 13.5 5 9.5 8.13 4 12 4c2.9 0 5.5 1.4 7 3.6" />
    </svg>
  ),
  (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" key="wave">
      <path d="M3 9.5c2.2-3 4.3-3 6.5 0s4.3 3 6.5 0" />
      <path d="M3 15.5c2.2-3 4.3-3 6.5 0s4.3 3 6.5 0" />
    </svg>
  ),
  (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" key="glasses">
      <circle cx="6.5" cy="14" r="3.5" />
      <circle cx="17.5" cy="14" r="3.5" />
      <path d="M10 13c1.2-1 2.8-1 4 0" />
      <path d="M3 11.5l1.8-4H8" />
      <path d="M21 11.5l-1.8-4H16" />
    </svg>
  ),
];

function SG_Card({ card, premium, priceCols, lang, envCfg, focusCfg }) {
  const L = L_(lang);
  const brands = sgTr(card.brands, lang);
  const meter = (v) => Array.from({ length: 5 }, (_, i) => {
    const cls = (i + 1 <= v) ? "on" : (i + 0.5 <= v ? "half" : "");
    return <i key={i} className={cls} />;
  });
  const sl = L.statLabs || [];
  const el = (envCfg && envCfg.labs) || L.envLabs || [];
  const envHead = (envCfg && envCfg.head) || L.envHead;
  const pf = focusCfg ? (card.pf || focusCfg.def || []) : null;
  return (
    <div className="cmp-card">
      <div className="cmp-cbody">
        <div className="cmp-chead">
          <div className="cmp-cname2">
            <b>{brands}</b>
            <em>{sgTr(card.kr, lang)}</em>
          </div>
        </div>
        {card.feat && <div className="cmp-feat">{sgTr(card.feat, lang)}</div>}
        {card.rec && (
          <div className="cmp-recfit">
            <span className="cmp-recfit-lab">{L.recFit}</span>
            <span className="cmp-recfit-tx">{sgTr(card.rec, lang)}</span>
          </div>
        )}
        {card.bars && (
          <div className="cmp-skill">
            <div className="cmp-skill-grp bars">
              <span className="cmp-skill-h">{L.statHead}</span>
              {card.bars.map((v, i) => (
                <div className="cmp-srow" key={"b" + i}>
                  <span className="cmp-slab">{sl[i]}</span>
                  <span className="cmp-sbar">{meter(v)}</span>
                </div>
              ))}
            </div>
            {pf ? (
              <div className="cmp-skill-grp env pf">
                <span className="cmp-skill-h">{focusCfg.head}</span>
                {pf.map((v, i) => (
                  <div className="cmp-srow" key={"p" + i}>
                    <span className="cmp-slab">{focusCfg.labs[i]}</span>
                    <span className="cmp-sbar env">{meter(v)}</span>
                  </div>
                ))}
              </div>
            ) : (card.env && (
              <div className="cmp-skill-grp env">
                <span className="cmp-skill-h">{envHead}</span>
                {card.env.map((v, i) => (
                  <div className="cmp-srow" key={"e" + i}>
                    <span className="cmp-slab">{el[i]}</span>
                    <span className="cmp-sbar env">{meter(v)}</span>
                  </div>
                ))}
              </div>
            ))}
          </div>
        )}
        <div className="cmp-prices" style={{ gridTemplateColumns: `repeat(${priceCols.length},1fr)` }}>
          {priceCols.map((pc, i) => {
            const v = card.prices[i]; const none = v == null; const free = v === 0;
            return (
              <div className={"cmp-pcell" + (none ? " off" : "")} key={i}>
                <span className="cmp-pidx">{sgTr(pc, lang)}</span>
                <span className={"cmp-pval" + (free ? " free" : "")}>
                  {none ? "–" : free ? "무상" : sgWon(v)}
                </span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function SG_Compare({ catId, setCat, onHome, lang, setLang }) {
  const L = L_(lang);
  const cat = SG_CATS.find(c => c.id === catId) || SG_CATS[0];
  const envCfg = cat.envCfg ? { head: sgTr(cat.envCfg.head, lang), labs: (cat.envCfg.labs || []).map(x => sgTr(x, lang)) } : null;
  const focusCfg = cat.focus ? { head: sgTr(cat.focus.meterHead, lang), labs: (cat.focus.items || []).map(it => sgTr(it.lab, lang)), def: cat.focus.defaultPf } : null;
  const [variant, setVariant] = React.useState(0);
  React.useEffect(() => { setVariant(0); }, [catId]);
  const active = cat.variants ? (cat.variants[variant] || cat.variants[0]) : cat;
  const cols = active.cols;
  const priceCols = active.priceCols;
  const n = cols.length;
  return (
    <div className="cmp-app">
      <div className="cmp-top">
        <div className="cmp-brand">
          <img className="cmp-logo" src={SG_LOGO()} alt="Cight" role="button" tabIndex={0} title="처음으로" style={{ cursor: 'pointer' }} onClick={onHome} onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onHome && onHome(); } }} />
          <div>
            <div className="cmp-kicker">{L.kicker}</div>
            <div className="cmp-title">{L.titlePlain}</div>
          </div>
        </div>
        <div className="cmp-top-r">
          <SG_LangSwitch lang={lang} setLang={setLang} />
          <div className="cmp-tiers">
            {SG_CATS.map(c => (
              <button key={c.id} className={"cmp-tier" + (catId === c.id ? " on" : "")} onClick={() => setCat(c.id)}>
                {sgTr(c.tab, lang)}<span>{sgTr(c.tabSub, lang)}</span>
              </button>
            ))}
          </div>
        </div>
      </div>

      <div className="cmp-prog">
        {cat.variants && (
          <span className="sg-subtabs">
            {cat.variants.map((vr, i) => (
              <button key={i} className={"sg-subtab" + (variant === i ? " on" : "")} onClick={() => setVariant(i)}>{sgTr(vr.label, lang)}</button>
            ))}
          </span>
        )}
        <span className="cmp-prog-l on">{L.progUp}</span>
        <span className="cmp-stair" aria-hidden="true">
          <i style={{ height: '100%', opacity: 1 }} />
          <i style={{ height: '78%', opacity: .82 }} />
          <i style={{ height: '58%', opacity: .64 }} />
          <i style={{ height: '40%', opacity: .46 }} />
          <i style={{ height: '26%', opacity: .3 }} />
        </span>
        <span className="cmp-prog-t"><b>{L.progB}</b>{L.progRest}</span>
        <span className="cmp-prog-l r">{L.progEco}</span>
      </div>

      {cat.focus && (
        <div className="sg-focus" aria-label={sgTr(cat.focus.head, lang)}>
          <span className="sg-focus-head">{sgTr(cat.focus.head, lang)}</span>
          <div className="sg-focus-items">
            {cat.focus.items.map((it, i) => (
              <div className="sg-focus-it" key={i}>
                <span className="sg-focus-ic">{SG_FOCUS_ICONS[it.ic]}</span>
                <span className="sg-focus-tx">
                  <b>{sgTr(it.k, lang)}</b>
                  <span>{sgTr(it.d, lang)}</span>
                </span>
                {i < cat.focus.items.length - 1 && <span className="sg-focus-sep" aria-hidden="true" />}
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="cmp-cols">
        {cols.map((col, idx) => {
          const step = Math.max(1, n - idx);   // 좌측이 높은 단계
          const premium = !!col.ribbon;
          return (
            <div className={"cmp-col" + (premium ? " premium" : (idx === n - 1 ? " value" : ""))} key={idx} data-step={step}>
              <div className="cmp-chd">
                {premium && <span className="cmp-ribbon sg-ribbon-abs">{L.ribbon}</span>}
                <span className="cmp-steplvl" aria-hidden="true">
                  {[1, 2, 3, 4, 5].map(k => (<i key={k} className={k <= step ? "on" : ""} />))}
                </span>
                <span className="cmp-cname">{sgTr(col.tier, lang)}</span>
                <span className="cmp-cdesc">{sgTr(col.note, lang)}</span>
              </div>
              <div className="cmp-list">
                {col.cards.map((card, ci) => (
                  <SG_Card key={ci} card={card} premium={premium} priceCols={priceCols} lang={lang} envCfg={envCfg} focusCfg={focusCfg} />
                ))}
              </div>
            </div>
          );
        })}
      </div>

      <div className="cmp-foot">
        <span className="cmp-foot-l">{tpl(L.footTotal, { cat: sgTr(cat.tab, lang) })} · <span className="cmp-fn">{cat.footExtra ? sgTr(cat.footExtra, lang) : L.footNote}</span></span>
        <span className="cmp-legend">
          <span className="cmp-leg"><i className="prem" />{L.legend}</span>
          <span className="cmp-foot-r">{L.footAddon}</span>
        </span>
      </div>
    </div>
  );
}

/* ============ 가이드 (왜 다를까 · 등급 안내) ============ */
function SG_Guide({ lang, setLang, onStart }) {
  const L = L_(lang);
  const pages = [
    (
      <div className="gp gp-hero-pg" key="hero">
        <div className="gp-hero">
          <div className="gp-hero-tx">
            <div className="gd-kicker">{L.gKicker}</div>
            <h1 className="gd-title" style={{ whiteSpace: 'pre-line' }}>{L.gTitle}</h1>
            <p className="gd-sub">{L.gSub}</p>
          </div>
          <span className="gp-hero-img"><image-slot id="sg-hero" shape="rounded" radius="20" fit="cover" placeholder={L.gHeroPhoto} style={{ display: 'block', width: '100%', height: '100%' }}></image-slot></span>
        </div>
        <div className="gd-pillars">
          {[['01', L.p1t, L.p1d], ['02', L.p2t, L.p2d], ['03', L.p3t, L.p3d]].map((p, i) => (
            <div className="gd-pill" key={i}><span className="gd-pill-n">{p[0]}</span><b>{p[1]}</b><span className="gd-pill-d">{p[2]}</span></div>
          ))}
        </div>
      </div>
    ),
    (
      <div className="gp gp-thk" key="why">
        <div className="gp-head">
          <span className="gd-sec-tag">{L.s1tag}</span>
          <h2>{L.s1t}</h2>
          <p>{L.s1sub}</p>
        </div>
        <div className="sg-angles">
          {L.angles.map((a, i) => (
            <div className={"sg-angle" + (i === 2 ? " hl" : "")} key={i}>
              <div className="sg-angle-vis" aria-hidden="true">
                <span className="sg-angle-baseline" />
                <span className="sg-angle-ray" style={{ transform: `rotate(-${[8, 14, 21][i]}deg)` }} />
                <span className="sg-angle-deg">{a[1]}</span>
              </div>
              <b>{a[0]}</b>
              <span className="sg-angle-d">{a[2]}</span>
            </div>
          ))}
        </div>
        <div className="sg-curve">
          <div className="sg-curve-c">
            <span className="sg-curve-img"><image-slot id="sg-curve-normal" shape="rounded" radius="14" fit="cover" placeholder={L.curveNimg} style={{ display: 'block', width: '100%', height: '100%' }}></image-slot></span>
            <b>{L.curveN}</b>
          </div>
          <div className="sg-curve-c hl">
            <span className="sg-curve-img"><image-slot id="sg-curve-sun" shape="rounded" radius="14" fit="cover" placeholder={L.curveSimg} style={{ display: 'block', width: '100%', height: '100%' }}></image-slot></span>
            <b>{L.curveS}</b>
          </div>
        </div>
        <p className="idxnote">{L.s1foot}</p>
      </div>
    ),
    (
      <div className="gp gp-thk gp-grades" key="grades">
        <div className="gp-head">
          <span className="gd-sec-tag">{L.s2tag}</span>
          <h2>{L.s2t}</h2>
          <p>{L.s2sub}</p>
        </div>
        <div className="sg-grades">
          {L.grades.map((g, i) => [g, i]).reverse().map(([g, tier]) => (
            <div className={"sg-grade" + (tier === 4 ? " hl" : "")} key={tier}>
              <span className="sg-grade-lvl" aria-hidden="true">
                {[0, 1, 2, 3, 4].map(k => (<i key={k} className={k <= tier ? "on" : ""} />))}
              </span>
              <b>{g[0]}</b>
              <span className="sg-grade-d">{g[1]}</span>
            </div>
          ))}
        </div>

        <div className="sg-optfig">
          <div className="sg-optfig-chart">
            <span className="sg-optfig-yhi">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 13l4 4L19 7" /></svg>
              {L.s2axisHi}
            </span>
            <span className="sg-optfig-ylo">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M12 20V4" /><path d="M6 14l6 6 6-6" /></svg>
              {L.s2axisLo}
            </span>
            <svg className="sg-optfig-svg" viewBox="0 0 1000 230" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
              <defs>
                <linearGradient id="sgOptFill" x1="0" y1="0" x2="1" y2="0">
                  <stop offset="0" stopColor="var(--gold)" stopOpacity="0.18" />
                  <stop offset="1" stopColor="var(--accent)" stopOpacity="0.05" />
                </linearGradient>
                <linearGradient id="sgOptLine" x1="0" y1="0" x2="1" y2="0">
                  <stop offset="0" stopColor="var(--gold)" />
                  <stop offset="1" stopColor="var(--accent)" />
                </linearGradient>
              </defs>
              <path className="sg-optfig-grid" d="M40 60 H960 M40 112 H960 M40 164 H960" />
              {[100, 300, 500, 700, 900].map(x => (<path key={x} className="sg-optfig-guide" d={`M${x} 20 V205`} />))}
              <path d="M100 48 C167 58 233 69 300 80 C367 90 433 101 500 112 C567 124 633 137 700 150 C767 163 833 176 900 188 L900 205 L100 205 Z" fill="url(#sgOptFill)" />
              <path d="M100 48 C167 58 233 69 300 80 C367 90 433 101 500 112 C567 124 633 137 700 150 C767 163 833 176 900 188" fill="none" stroke="url(#sgOptLine)" strokeWidth="5" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
              {[[100, 48], [300, 80], [500, 112], [700, 150], [900, 188]].map(([cx, cy], i) => (
                <circle key={i} className={"sg-optfig-dot" + (i === 0 ? " hl" : "")} cx={cx} cy={cy} r="7" vectorEffect="non-scaling-stroke" />
              ))}
            </svg>
            <div className="sg-optfig-xaxis">
              <span className="hl">{L.grades[4][0]}</span>
              <span>{L.grades[0][0]}</span>
            </div>
          </div>

          <div className="sg-opthd">{L.s2figHd}</div>
          <ul className="sg-optlist">
            {(L.s2opt || []).map((o, i) => (
              <li className="sg-optitem" key={i}>
                <span className="sg-opticon">{SG_OPT_ICONS[i]}</span>
                <span className="sg-opttx"><b>{o[0]}</b><span>{o[1]}</span></span>
              </li>
            ))}
          </ul>
        </div>
      </div>
    ),
    (
      <div className="gp gp-end-pg" key="end">
        <div className="gp-end">
          <h2 className="gp-end-t" style={{ whiteSpace: 'pre-line' }}>{L.endT}</h2>
          <button className="gd-cta big" onClick={onStart}>{L.cta}</button>
          <span className="gd-foot">{L.foot}</span>
        </div>
      </div>
    ),
  ];

  const [page, setPage] = React.useState(0);
  const last = pages.length - 1;
  const go = (n) => setPage(Math.max(0, Math.min(last, n)));
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'ArrowRight') go(page + 1); else if (e.key === 'ArrowLeft') go(page - 1); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [page]);

  return (
    <div className="gd paged">
      <div className="gd-top">
        <img className="gd-logo" src={SG_LOGO()} alt="Cight" role="button" tabIndex={0} title="처음으로" style={{ cursor: 'pointer' }} onClick={() => go(0)} onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(0); } }} />
        <span className="gd-top-sp" />
        <SG_LangSwitch lang={lang} setLang={setLang} />
        <button className="gd-cta" onClick={onStart}>{L.cta}</button>
      </div>
      <div className="gd-viewport">
        <div className="gd-track" style={{ width: (pages.length * 100) + '%', transform: `translateX(-${page * (100 / pages.length)}%)` }}>
          {pages.map((pg, i) => (<div className="gd-slot" key={i} style={{ width: (100 / pages.length) + '%' }} aria-hidden={i !== page}>{pg}</div>))}
        </div>
      </div>
      <div className="gd-nav">
        <button className="gd-arrow" onClick={() => go(page - 1)} disabled={page === 0} aria-label={L.prev}>‹</button>
        <div className="gd-dots">
          {pages.map((_, i) => (<button key={i} className={"gd-dot" + (i === page ? " on" : "")} onClick={() => go(i)} aria-label={"page " + (i + 1)} />))}
        </div>
        {page === last
          ? <button className="gd-arrow next cta" onClick={onStart}>{L.cta}</button>
          : <button className="gd-arrow next" onClick={() => go(page + 1)} aria-label={L.next}>›</button>}
      </div>
    </div>
  );
}

function SG_App() {
  const [mode, setMode] = React.useState('guide');
  const [catId, setCat] = React.useState(SG_CATS[0].id);
  const [lang, setLangS] = React.useState(SG_LANG0);
  const setLang = (l) => { setLangS(l); try { localStorage.setItem('cight_lang', l); } catch (e) {} };
  React.useEffect(() => { document.documentElement.lang = lang; }, [lang]);

  if (mode === 'guide') return <SG_Guide lang={lang} setLang={setLang} onStart={() => setMode('table')} />;
  return <SG_Compare catId={catId} setCat={setCat} onHome={() => setMode('guide')} lang={lang} setLang={setLang} />;
}

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