// Legal page shell — shared by Terms & Privacy.
// Renders a doc layout with sticky TOC. Tracks the active section via IntersectionObserver.

const LegalShell = ({ crumb, title, version, effectiveDate, lastUpdated, toc, children, navigate }) => {
  const [active, setActive] = React.useState(toc[0]?.id);

  React.useEffect(() => {
    const obs = new IntersectionObserver(
      (entries) => {
        // Pick the topmost section that's "in view"
        const visible = entries
          .filter(e => e.isIntersecting)
          .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
        if (visible[0]) {
          setActive(visible[0].target.id);
        }
      },
      { rootMargin: "-80px 0px -70% 0px", threshold: 0 }
    );
    toc.forEach(t => {
      const el = document.getElementById(t.id);
      if (el) obs.observe(el);
    });
    return () => obs.disconnect();
  }, [toc]);

  const onJump = (e, id) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY - 80;
      window.scrollTo({ top, behavior: 'smooth' });
      setActive(id);
    }
  };

  return (
    <main>
      <div className="legal-head">
        <div className="container">
          <div className="crumb">{crumb}</div>
          <h1>{title}</h1>
          <div className="meta">
            <span><strong>버전</strong> {version}</span>
            <span><strong>시행일</strong> {effectiveDate}</span>
            <span><strong>최종 수정</strong> {lastUpdated}</span>
          </div>
        </div>
      </div>

      <div className="container">
        <div className="legal-shell">
          <nav className="legal-toc">
            <h4>목차</h4>
            <ol className="legal-toc-list">
              {toc.map((t, i) => (
                <li key={t.id}>
                  <a href={`#${t.id}`}
                     className={active === t.id ? "active" : ""}
                     onClick={(e) => onJump(e, t.id)}>
                    {String(i + 1).padStart(2, "0")}. {t.label}
                  </a>
                </li>
              ))}
            </ol>
          </nav>

          <article className="legal-doc">
            {children}

            <div className="legal-foot">
              <div className="ic"><Icon name="msg" size={16}/></div>
              <div style={{ flex: 1 }}>
                내용에 대한 문의가 있으신가요?
                <a href="#" onClick={e => { e.preventDefault(); navigate('chat'); }}
                  style={{ color: "var(--primary)", fontWeight: 600, marginLeft: 6 }}>
                  1:1 채팅으로 문의 →
                </a>
              </div>
              <span>privacy@solveit.kr</span>
            </div>
          </article>
        </div>
      </div>
    </main>
  );
};

window.LegalShell = LegalShell;
