/* global React, ReactDOM, useReveal, HeaderEs, HeaderEn, FooterEs, FooterEn, WhatsAppFabEs, WhatsAppFabEn, LegalDocsEs, LegalDocsEn */
// ============================================================
// Bootstrap for the legal area — ONE page (legal.html) client-routed
// under the site-wide language prefix, mirroring the landing's /es · /en:
//
//     /es/legal/privacy-notice        /en/legal/privacy-notice
//     /es/legal/terms-and-conditions  /en/legal/terms-and-conditions
//     /es/legal/data-protection       /en/legal/data-protection
//
// The language lives in the URL (the /es · /en segment) exactly like the
// rest of the site; the document slug is always English. Vercel rewrites
// every /es/legal/* and /en/legal/* path to legal.html (see vercel.json);
// this router reads {lang, doc} from the URL and switches either axis in
// place — history.pushState + a state change, never a full navigation.
//
// ES and EN Header/Footer/WhatsAppFab/content are loaded side by side
// under namespaced globals (HeaderEs/HeaderEn, ...) so both languages can
// coexist on this one page without clobbering each other.
// ============================================================
const { useState, useEffect, useCallback } = React;

// English key -> {slug (canonical, English, URL-facing), es, en}
// es/en hold whatever LegalDocs[key] exposes for that document: label,
// title, updated, Content.
const ORDER = ["privacy", "terms", "dataProtection"];
const DOCS = {};
ORDER.forEach((enKey) => {
  const enDoc = LegalDocsEn[enKey];
  const esKey = Object.keys(LegalDocsEs).find((k) => LegalDocsEs[k].enSlug === enDoc.slug);
  DOCS[enKey] = { slug: enDoc.slug, es: LegalDocsEs[esKey], en: enDoc };
});

const SLUG_TO_KEY = Object.fromEntries(ORDER.map((k) => [DOCS[k].slug, k]));

const STRINGS = {
  es: {
    eyebrow: "Legal", heading: "Documentos legales", navLabel: "Documentos legales",
    updated: "Última actualización:", homeHref: "/es",
  },
  en: {
    eyebrow: "Legal", heading: "Legal documents", navLabel: "Legal documents",
    updated: "Last updated:", homeHref: "/en",
  },
};

const LANG_KEY = "meefi-lang";

// Path shape: /{lang}/legal/{slug}. Language comes from the leading
// segment; the doc slug is the third. Anything unrecognized falls back to
// Spanish + the first document.
function resolveRoute(pathname) {
  const parts = pathname.replace(/^\/+|\/+$/g, "").split("/");
  const lang = parts[0] === "en" ? "en" : "es";
  const key = SLUG_TO_KEY[parts[2]] || ORDER[0];
  return { lang, key };
}

function legalHref(lang, key) {
  return `/${lang}/legal/${DOCS[key].slug}`;
}

function LegalPage() {
  useReveal();
  const [route, setRoute] = useState(() => resolveRoute(window.location.pathname));
  const { lang, key } = route;

  const doc = DOCS[key];
  const active = doc[lang];
  const t = STRINGS[lang];
  const Header = lang === "es" ? HeaderEs : HeaderEn;
  const Footer = lang === "es" ? FooterEs : FooterEn;
  const WhatsAppFab = lang === "es" ? WhatsAppFabEs : WhatsAppFabEn;

  useEffect(() => {
    document.title = `${active.title} — Meefi`;
    document.documentElement.lang = lang;
    // Keep the site-wide language preference in sync with the URL, so
    // the landing (/es · /en) opens in whatever language the visitor
    // last read the legal docs in.
    try { localStorage.setItem(LANG_KEY, lang); } catch (e) {}
  }, [active, lang]);

  useEffect(() => {
    const onPop = () => setRoute(resolveRoute(window.location.pathname));
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  const goToDoc = useCallback((k) => {
    setRoute((cur) => {
      if (k === cur.key) return cur;
      window.history.pushState({}, "", legalHref(cur.lang, k));
      window.scrollTo(0, 0);
      return { lang: cur.lang, key: k };
    });
  }, []);

  // Language is part of the URL here, so toggling swaps the /es ↔ /en
  // segment (same document) and the address bar updates to match.
  const toggleLang = useCallback(() => {
    setRoute((cur) => {
      const next = cur.lang === "es" ? "en" : "es";
      window.history.pushState({}, "", legalHref(next, cur.key));
      window.scrollTo(0, 0);
      return { lang: next, key: cur.key };
    });
  }, []);

  return (
    <>
      <Header
        baseHref={t.homeHref}
        onToggleLang={toggleLang}
        enHref={legalHref("en", key)}
        esHref={legalHref("es", key)}
      />
      <main>
        <section className="legal-section">
          <div className="wrap-narrow">
            <div className="legal-head reveal">
              <span className="eyebrow"><span className="dot"/> {t.eyebrow}</span>
              <h1 className="legal-h1">{t.heading}</h1>
            </div>

            <nav className="legal-tabs reveal" aria-label={t.navLabel}>
              {ORDER.map((k) => (
                <a
                  key={k}
                  href={legalHref(lang, k)}
                  className={`legal-tab${k === key ? " is-active" : ""}`}
                  aria-current={k === key ? "page" : undefined}
                  onClick={(e) => { e.preventDefault(); goToDoc(k); }}
                >
                  {DOCS[k][lang].label}
                </a>
              ))}
            </nav>

            {/* key={lang+key} remounts just this panel on doc/language
                switch — header, footer, and tab nav stay mounted, so
                nothing but the document itself re-renders (and re-plays
                its fade-in). No "reveal" class here: that class fades in
                only once ~12% of the element's own area has scrolled
                into view, and Terms and Conditions is tall enough that
                the threshold wasn't met until well past the fold —
                reading as a stuck/slow-to-appear page. Legal text should
                just be visible immediately. */}
            <div className="legal-panel" key={`${lang}-${key}`}>
              <p className="legal-meta"><strong>{t.updated}</strong> {active.updated}</p>
              <h2 className="legal-doc-title">{active.title}</h2>
              <active.Content/>
            </div>
          </div>
        </section>
      </main>
      <Footer baseHref={t.homeHref}/>
      <WhatsAppFab/>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<LegalPage/>);
