// Legal pages (privacy + cookies) and the site-wide cookie banner.
// Light kit for a site that collects no personal data server-side.
// RO is primary; a small in-page toggle mirrors to EN. Persisted via blogLang.

// Resolve {operator}/{regcom}/{cui}/{address}/{privacyEmail} placeholders in copy.
function fillLegal(str, op) {
  return (str || "")
    .replace(/\{operator\}/g, op.name)
    .replace(/\{regcom\}/g, op.regcom)
    .replace(/\{cui\}/g, op.cui)
    .replace(/\{address\}/g, op.address)
    .replace(/\{privacyEmail\}/g, op.privacyEmail);
}

function LegalLangToggle({ lang, onPick }) {
  return (
    <div className="lang-toggle" role="group" aria-label="Language">
      {["ro", "en"].map((l) => (
        <button
          key={l}
          className={"lang-toggle__btn" + (lang === l ? " is-active" : "")}
          onClick={() => onPick(l)}
          aria-pressed={lang === l}>
          {l.toUpperCase()}
        </button>
      ))}
    </div>);

}

function LegalSection({ s, op }) {
  return (
    <section className="legal__section">
      <h2 className="article__h">{s.h}</h2>
      {(s.p || []).map((para, i) => (
        <p key={i} className="article__p">{fillLegal(para, op)}</p>
      ))}
      {s.list && (
        <ul className="article__ul">
          {s.list.map((li, i) => <li key={i}>{fillLegal(li, op)}</li>)}
        </ul>
      )}
    </section>);

}

// which: "privacy" | "cookies"
function LegalPage({ which }) {
  const L = window.LEGAL || {};
  const op = L.operator || {};
  const [lang, setLang] = React.useState(() => {
    try { return localStorage.getItem("blogLang") === "en" ? "en" : "ro"; }
    catch (e) { return "ro"; }
  });
  const pick = (l) => { setLang(l); try { localStorage.setItem("blogLang", l); } catch (e) {} };

  const t = L[lang] || L.ro || {};
  const doc = (which === "cookies" ? t.cookies : t.privacy) || {};
  const otherHref = which === "cookies" ? "/privacy" : "/cookies";
  const otherLabel = which === "cookies"
    ? (lang === "ro" ? "Politică de confidențialitate" : "Privacy notice")
    : (lang === "ro" ? "Politică de cookies" : "Cookie notice");

  return (
    <div className="page page--narrow">
      <header className="writing-head">
        <Eyebrow>{doc.eyebrow}</Eyebrow>
        <h1 className="writing-head__title">{doc.title}</h1>
        <p className="writing-head__lead">{doc.lead}</p>
        <div className="legal__head-meta">
          <LegalLangToggle lang={lang} onPick={pick} />
          <span className="legal__updated">{t.updated}</span>
        </div>
      </header>

      <article className="article__body legal__body">
        {(doc.sections || []).map((s, i) => <LegalSection key={i} s={s} op={op} />)}

        <div className="article__foot">
          <p className="article__byline">
            <strong>{op.name}</strong> · {op.regcom} · CUI {op.cui} · {op.address}
          </p>
          <p className="legal__cross">
            <a href={otherHref} onClick={(e) => { e.preventDefault(); goTo(otherHref); }}>
              {otherLabel} <span aria-hidden="true">→</span>
            </a>
          </p>
        </div>
      </article>
    </div>);

}

// Site-wide cookie notice banner. Honest, dismissible, not a tracking wall.
function CookieBanner() {
  const L = window.LEGAL || {};
  const [acked, setAcked] = React.useState(() => {
    try { return localStorage.getItem("cookieNoticeAck") === "1"; }
    catch (e) { return true; } // if storage is blocked, don't nag
  });
  // Banner language follows the same blogLang preference; default RO.
  const lang = (() => {
    try { return localStorage.getItem("blogLang") === "en" ? "en" : "ro"; }
    catch (e) { return "ro"; }
  })();
  const b = ((L[lang] || L.ro || {}).banner) || {};

  const dismiss = () => {
    try { localStorage.setItem("cookieNoticeAck", "1"); } catch (e) {}
    setAcked(true);
  };

  if (acked || !b.text) return null;

  return (
    <div className="cookie-banner" role="region" aria-label={lang === "ro" ? "Notificare cookies" : "Cookie notice"}>
      <div className="page cookie-banner__inner">
        <p className="cookie-banner__text">{b.text}</p>
        <div className="cookie-banner__actions">
          <a
            className="cookie-banner__link"
            href="/cookies"
            onClick={(e) => { e.preventDefault(); goTo("/cookies"); }}>
            {b.policy}
          </a>
          <button className="btn btn--primary cookie-banner__btn" onClick={dismiss}>
            {b.accept}
          </button>
        </div>
      </div>
    </div>);

}

Object.assign(window, { LegalPage, CookieBanner });
