// legal.jsx — Study WithU 법적 고지 공통 레이아웃 + 본문 렌더러
// docId 로 legal-docs.jsx 의 문서를 골라 렌더. 다크/라이트 토글, 스티키 목차 활성화 포함.
const { useState: useLgState, useEffect: useLgEffect, useRef: useLgRef } = React;

const LG_DOCS_NAV = [
  { id: "privacy", label: "개인정보처리방침", href: "privacy.html" },
  { id: "terms", label: "이용약관", href: "terms.html" },
  { id: "refund", label: "환불정책", href: "refund.html" },
];

// ── 블록 렌더 ──────────────────────────────────────────────
function LgBlock({ b }) {
  if (b.t === "p") return <p className={"lg-p" + (b.muted ? " muted" : "")} dangerouslySetInnerHTML={{ __html: b.html }} />;
  if (b.t === "clauses") return (
    <ol className="lg-list">{b.items.map((it, i) => <li key={i} dangerouslySetInnerHTML={{ __html: it }} />)}</ol>
  );
  if (b.t === "bullets") return (
    <ul className="lg-bullets">{b.items.map((it, i) => <li key={i} dangerouslySetInnerHTML={{ __html: it }} />)}</ul>
  );
  if (b.t === "note") return (
    <div className="lg-note">
      <svg className="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9.5"/><path d="M12 11v5M12 7.6v.01"/></svg>
      <p dangerouslySetInnerHTML={{ __html: b.html }} />
    </div>
  );
  if (b.t === "table") return (
    <div className="lg-table-scroll">
      <table className="lg-table">
        <thead><tr>{b.head.map((h, i) => <th key={i}>{h}</th>)}</tr></thead>
        <tbody>
          {b.rows.map((r, i) => (
            <tr key={i}>{r.map((c, j) => <td key={j} className={b.numCols && b.numCols.includes(j) ? "num" : undefined} dangerouslySetInnerHTML={{ __html: c }} />)}</tr>
          ))}
        </tbody>
      </table>
    </div>
  );
  return null;
}

// ── 목차 ───────────────────────────────────────────────────
function LgToc({ sections, active }) {
  return (
    <aside className="lg-toc">
      <div className="lg-toc-inner">
        <p className="lg-toc-label">목차</p>
        <ol>
          {sections.map((s) => (
            <li key={s.id}>
              <a href={"#" + s.id} className={active === s.id ? "is-active" : ""}>
                <span className="n">{s.no}</span><span>{s.title}</span>
              </a>
            </li>
          ))}
        </ol>
      </div>
    </aside>
  );
}

// ── 메인 레이아웃 ──────────────────────────────────────────
function LegalPage({ docId }) {
  const [mode, setMode] = useLgState(() => localStorage.getItem("swu-theme") || "light");
  const theme = mode === "system"
    ? (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light")
    : mode;
  useLgEffect(() => { localStorage.setItem("swu-theme", mode); }, [mode]);

  const doc = window.LEGAL_DOCS[docId];
  const [active, setActive] = useLgState(doc.sections[0] && doc.sections[0].id);

  // 앱(WebView)은 같은 창에서 이 문서로 들어온다 — 홈으로 보내면 결제 화면을 잃는다.
  // 히스토리가 있으면 되돌려 보낸다. JS 없이도 href="/" 로 동작.
  const [canBack, setCanBack] = useLgState(false);
  useLgEffect(() => { setCanBack(window.history.length > 1); }, []);
  const onBack = (e) => {
    if (window.history.length > 1) { e.preventDefault(); window.history.back(); }
  };
  const backLabel = canBack ? "돌아가기" : "홈으로";

  useLgEffect(() => {
    const els = doc.sections.map((s) => document.getElementById(s.id)).filter(Boolean);
    const io = new IntersectionObserver((entries) => {
      const vis = entries.filter((e) => e.isIntersecting).sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
      if (vis[0]) setActive(vis[0].target.id);
    }, { rootMargin: "-15% 0px -70% 0px", threshold: 0 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [docId]);

  return (
    <div className={"swu theme-" + theme} style={{ minHeight: "100vh" }}>
      {/* 네비 */}
      <header className="lg-nav">
        <a href="/" style={{ textDecoration: "none" }}><Logo size={22} /></a>
        <div className="lg-nav-right">
          <ThemeToggle value={mode} onChange={setMode} />
          <a className="lg-back" href="/" onClick={onBack}>
            <svg width="16" height="16" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4l-5 5 5 5"/></svg>
            {backLabel}
          </a>
        </div>
      </header>

      {/* 헤더 밴드 */}
      <section className="lg-header">
        <div className="lg-header-inner">
          <div className="lg-kicker">{doc.kicker}</div>
          <h1 className="lg-title">{doc.title}</h1>
          <div className="lg-meta">
            <span>시행일 <b>{doc.effective}</b></span>
            <span>최종 개정 <b>{doc.updated}</b></span>
            {doc.version && <span>버전 <b>{doc.version}</b></span>}
          </div>
          <nav className="lg-doc-switch">
            {LG_DOCS_NAV.map((d) => (
              <a key={d.id} href={d.href} aria-current={d.id === docId ? "page" : undefined}>{d.label}</a>
            ))}
          </nav>
        </div>
      </section>

      {/* 본문 */}
      <main className="lg-body">
        <div className="lg-wrap">
          <div className="lg-grid">
            <LgToc sections={doc.sections} active={active} />
            <article className="lg-article">
              {doc.intro && <p className="lg-intro" dangerouslySetInnerHTML={{ __html: doc.intro }} />}
              {doc.sections.map((s) => (
                <section key={s.id} id={s.id} className="lg-sec">
                  <div className="lg-sec-h">
                    <span className="lg-sec-no">{s.no}</span>
                    <h2 className="lg-sec-t">{s.title}</h2>
                  </div>
                  {s.blocks.map((b, i) => <LgBlock key={i} b={b} />)}
                </section>
              ))}

              {/* 문의처 */}
              {doc.contact && (
                <div className="lg-contact">
                  <h4>{doc.contact.title || "문의처"}</h4>
                  <dl>
                    {doc.contact.rows.map((r, i) => (
                      <React.Fragment key={i}><dt>{r[0]}</dt><dd dangerouslySetInnerHTML={{ __html: r[1] }} /></React.Fragment>
                    ))}
                  </dl>
                </div>
              )}
            </article>
          </div>
        </div>
      </main>

      {/* 푸터 */}
      <footer className="lg-foot">
        <div className="lg-foot-inner">
          <div>
            <Logo size={19} />
            <p className="lg-foot-copy" style={{ marginTop: 10 }}>© 2026 Study WithU. 카페처럼 편한 공부 공간.</p>
          </div>
          <nav className="lg-foot-links">
            <a href="/">홈</a>
            <a href="terms.html">이용약관</a>
            <a href="privacy.html">개인정보처리방침</a>
            <a href="refund.html">환불정책</a>
          </nav>
        </div>
      </footer>
    </div>
  );
}

Object.assign(window, { LegalPage });
