/* Juridische pagina's: privacybeleid, cookiebeleid, disclaimer, toegankelijkheidsverklaring.
   Inhoud staat in legal-content.js. Deze module doet alleen de opmaak. */

function bbLegalInline(text, keyBase) {
  // Splitst op {{todo}}, e‑mailadressen en URL's
  const parts = String(text).split(/(\{\{[^}]+\}\}|[\w.+-]+@[\w-]+(?:\.[\w-]+)*\.[a-z]{2,}|https?:\/\/[^\s)]*[\w\/]|www\.[\w-]+(?:\.[\w-]+)*\.[a-z]{2,})/g);
  return parts.map((p, i) => {
    const k = keyBase + "-" + i;
    if (!p) return null;
    if (/^\{\{.+\}\}$/.test(p)) {
      return <mark key={k} className="bb-legal__todo">nog aanvullen: {p.slice(2, -2)}</mark>;
    }
    if (/^[\w.+-]+@[\w-]+(?:\.[\w-]+)*\.[a-z]{2,}$/i.test(p)) {
      return <a key={k} href={"mailto:" + p}>{p}</a>;
    }
    if (/^https?:\/\//.test(p) || /^www\./.test(p)) {
      const href = /^https?:/.test(p) ? p : "https://" + p;
      return <a key={k} href={href} target="_blank" rel="noopener noreferrer">{p}</a>;
    }
    return <React.Fragment key={k}>{p}</React.Fragment>;
  });
}

function LegalBlock({ block, idx, sid }) {
  const key = sid + "-" + idx;
  if (block.p) {
    return <p className={"bb-legal__p" + (block.added ? " is-added" : "")}>{bbLegalInline(block.p, key)}</p>;
  }
  if (block.h) {
    return <h3 className="bb-legal__h3">{block.h}</h3>;
  }
  if (block.subkicker) {
    return <p className="bb-legal__subkicker">{block.subkicker}</p>;
  }
  if (block.cols) {
    return (
      <div className="bb-legal__cols">
        {block.cols.map((col, i) => (
          <div className={"bb-legal__col" + (col.tone === "niet" ? " is-niet" : "")} key={key + "-c" + i}>
            <h4>{col.title}</h4>
            {col.intro && <p className="bb-legal__colintro">{col.intro}</p>}
            <ul>
              {col.items.map((li, n) => <li key={key + "-c" + i + "-" + n}>{bbLegalInline(li, key + "-c" + i + "-" + n)}</li>)}
            </ul>
            {col.outro && <p className="bb-legal__colintro bb-legal__coloutro">{bbLegalInline(col.outro, key + "-o" + i)}</p>}
          </div>
        ))}
      </div>
    );
  }
  if (block.ul) {
    return (
      <ul className="bb-legal__ul">
        {block.ul.map((li, i) => <li key={key + "-" + i}>{bbLegalInline(li, key + "-" + i)}</li>)}
      </ul>
    );
  }
  if (block.dl) {
    return (
      <dl className="bb-legal__dl">
        {block.dl.map((row, i) => (
          <div className="bb-legal__dlrow" key={key + "-" + i}>
            <dt>{row[0]}</dt>
            <dd>{bbLegalInline(row[1], key + "-d" + i)}</dd>
          </div>
        ))}
      </dl>
    );
  }
  if (block.note) {
    return (
      <aside className="bb-legal__note">
        <h4>{block.note.title}</h4>
        <p>{bbLegalInline(block.note.p, key)}</p>
      </aside>
    );
  }
  if (block.table) {
    return <LegalTable key={key} t={block.table} k={key} />;
  }
  return null;
}

function LegalTable({ t, k }) {
  const ref = useRef(null);
  const [scrollbaar, setScrollbaar] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const meet = () => setScrollbaar(el.scrollWidth > el.clientWidth + 1);
    meet();
    if (typeof ResizeObserver === "undefined") {
      window.addEventListener("resize", meet);
      return () => window.removeEventListener("resize", meet);
    }
    const ro = new ResizeObserver(meet);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);
  return (
    <div
      ref={ref}
      className={"bb-legal__tablewrap" + (scrollbaar ? " is-scrollbaar" : "")}
      tabIndex={scrollbaar ? 0 : undefined}
      role={scrollbaar ? "region" : undefined}
      aria-label={scrollbaar ? "Tabel: " + t.head.join(", ") + ". Horizontaal scrollbaar." : undefined}
    >
      <table className="bb-legal__table">
        <thead>
          <tr>{t.head.map((h, i) => <th key={k + "-h" + i} scope="col">{h}</th>)}</tr>
        </thead>
        <tbody>
          {t.rows.map((r, i) => (
            <tr key={k + "-r" + i}>
              {r.map((c, j) => (
                j === 0
                  ? <th key={k + "-c" + i + "-" + j} scope="row">{bbLegalInline(c, k + "-c" + i + j)}</th>
                  : <td key={k + "-c" + i + "-" + j}>{bbLegalInline(c, k + "-c" + i + j)}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function LegalToc({ sections, active, onJump }) {
  const [wide, setWide] = useState(() => window.matchMedia("(min-width: 1024px)").matches);
  useEffect(() => {
    const mq = window.matchMedia("(min-width: 1024px)");
    const on = () => setWide(mq.matches);
    mq.addEventListener("change", on);
    return () => mq.removeEventListener("change", on);
  }, []);
  return (
    <details className="bb-legal__toc" open={wide} key={wide ? "w" : "n"}>
      <summary className="bb-legal__tocsum">Op deze pagina<span className="c">{sections.length}</span></summary>
      <p className="bb-legal__toctitle">Op deze pagina</p>
      <ol>
        {sections.map((s, i) => (
          <li key={s.id}>
            <a
              href={"#" + s.id}
              className={active === s.id ? "is-active" : ""}
              aria-current={active === s.id ? "true" : undefined}
              onClick={(e) => { e.preventDefault(); onJump(s.id); }}
            >
              <span className="num" aria-hidden="true">{i + 1}</span>
              <span className="lbl">{s.title}</span>
            </a>
          </li>
        ))}
      </ol>
    </details>
  );
}

function LegalPage({ slug, go }) {
  const doc = window.BB_LEGAL[slug];
  const [active, setActive] = useState(doc.sections[0].id);
  const bodyRef = useRef(null);

  useEffect(() => {
    const ids = doc.sections.map((s) => s.id);
    let raf = 0;
    const measure = () => {
      raf = 0;
      let cur = ids[0];
      for (const id of ids) {
        const el = document.getElementById("sec-" + id);
        if (el && el.getBoundingClientRect().top <= 170) cur = id;
      }
      setActive(cur);
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(measure); };
    measure();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      if (raf) cancelAnimationFrame(raf);
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, [slug]);

  const jump = (id) => {
    const el = document.getElementById("sec-" + id);
    if (!el) return;
    const top = window.scrollY + el.getBoundingClientRect().top - 96;
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches
      || document.documentElement.classList.contains("bb-rm-force");
    window.scrollTo({ top, behavior: reduce ? "auto" : "smooth" });
    setActive(id);
    const h = el.querySelector("h2");
    if (h) { h.setAttribute("tabindex", "-1"); h.focus({ preventScroll: true }); }
  };

  const others = window.BB_LEGAL_ORDER.filter((k) => k !== slug);

  return (
    <main id="main" tabIndex="-1" data-screen-label={"Juridisch · " + doc.title}>
      <header className="bb-legal__head">
        <Container>
          <nav className="bb-legal__crumb" aria-label="Kruimelpad">
            <a href={window.bbHref("home")} onClick={(e) => { e.preventDefault(); go("home"); }}>Home</a>
            <span aria-hidden="true">/</span>
            <span>{doc.title}</span>
          </nav>
          <p className="bb-legal__kicker">{doc.kicker}</p>
          <h1>{doc.title}</h1>
          <p className="bb-legal__lead">{doc.lead}</p>
          <dl className="bb-legal__meta">
            <div><dt>Laatst bijgewerkt</dt><dd>{doc.updated}</dd></div>
            <div><dt>Versie</dt><dd>{doc.version}</dd></div>
            <div><dt>Vragen</dt><dd><a href="mailto:info@buitenbuddies.org">info@buitenbuddies.org</a></dd></div>
          </dl>
        </Container>
      </header>

      <div className="bb-legal">
        <Container>
          <div className="bb-legal__grid">
            <div className="bb-legal__side">
              <LegalToc sections={doc.sections} active={active} onJump={jump} />
            </div>

            <article className="bb-legal__body" ref={bodyRef}>
              {doc.summary && (
                <section className="bb-legal__summary" aria-labelledby="bb-legal-summary">
                  <h2 id="bb-legal-summary">{doc.summary.title}</h2>
                  <ul>
                    {doc.summary.items.map((it, i) => <li key={"sum" + i}>{bbLegalInline(it, "sum" + i)}</li>)}
                  </ul>
                  <p className="bb-legal__summarynote">{doc.summary.note}</p>
                </section>
              )}

              {doc.sections.map((s, i) => (
                <section className="bb-legal__sec" id={"sec-" + s.id} data-sid={s.id} key={s.id}>
                  <h2>
                    <span className="bb-legal__num" aria-hidden="true">{i + 1}.</span>
                    <span>{s.title}</span>
                  </h2>
                  {s.blocks.map((b, j) => <LegalBlock block={b} idx={j} sid={s.id} key={s.id + j} />)}
                </section>
              ))}

              <section className="bb-legal__contact" aria-labelledby="bb-legal-contact">
                <h2 id="bb-legal-contact">Nog een vraag?</h2>
                <p>Sabrina leest zelf de e‑mail. Je krijgt altijd antwoord van een mens, niet van een systeem.</p>
                <div className="bb-legal__contactrow">
                  <Button variant="primary" href="mailto:info@buitenbuddies.org">
                    <Icon name="mail" /> info@buitenbuddies.org
                  </Button>
                  <Button variant="secondary" onClick={() => go("contact")}>Naar de contactpagina</Button>
                </div>
              </section>

              <nav className="bb-legal__others" aria-label="Overige juridische pagina's">
                {others.map((k) => (
                  <a href={window.bbHref(k)} key={k} onClick={(e) => { e.preventDefault(); go(k); }}>
                    <span className="t">{window.BB_LEGAL[k].title}</span>
                    <span className="d">{window.BB_LEGAL_SHORT[k]}</span>
                    <span className="a" aria-hidden="true"><Icon name="arrowRight" size={18} /></span>
                  </a>
                ))}
              </nav>
            </article>
          </div>
        </Container>
      </div>
    </main>
  );
}

Object.assign(window, { LegalPage, LegalToc, LegalBlock, LegalTable });
