/* global React, LogoEnglish, LogoArabic */
const { useState, useEffect } = React;

// Current language (set by i18n.js / the inline head bootstrap before this runs).
// It only changes on a full reload, so reading it once at module scope is safe.
const AR = (typeof window !== "undefined" && window.WATHIQ_LANG === "ar");

// Distinct-path i18n: Arabic lives at the root, English under /en/. The language
// switch links to the TWIN path of the current page (not a ?lang param), so each
// language is a real, separately-indexable URL. Computed from location.pathname.
function langTwins() {
  var p = (typeof location !== "undefined" && location.pathname) ? location.pathname : "/";
  var isEn = p.indexOf("/en/") === 0 || p === "/en";
  var rel = isEn ? (p.replace(/^\/en/, "") || "/") : p;
  rel = rel.replace(/index\.html$/, "");   // /index.html -> /
  if (rel === "") rel = "/";
  return { ar: rel, en: rel === "/" ? "/en/" : "/en" + rel };
}

// Small globe for the language switch.
function GlobeIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" aria-hidden="true">
      <circle cx="12" cy="12" r="9" />
      <path d="M3 12h18" strokeLinecap="round" />
      <path d="M12 3c2.6 2.7 2.6 15.3 0 18M12 3c-2.6 2.7-2.6 15.3 0 18" strokeLinecap="round" />
    </svg>
  );
}

// The language switch is a globe button that opens a small menu to pick a language.
function LangSwitch() {
  const [open, setOpen] = useState(false);
  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (!e.target.closest(".lang-switch-wrap")) setOpen(false); };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("click", onDoc);
    document.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("click", onDoc); document.removeEventListener("keydown", onKey); };
  }, [open]);
  return (
    <div className="lang-switch-wrap">
      <button
        type="button"
        className="lang-switch"
        aria-label="Language / اللغة"
        aria-haspopup="true"
        aria-expanded={open}
        onClick={(e) => { e.stopPropagation(); setOpen((v) => !v); }}
      >
        <GlobeIcon />
      </button>
      <div className={`lang-menu ${open ? "is-open" : ""}`} role="menu">
        <a role="menuitem" data-lang="ar" className="lang-menu-item" href={langTwins().ar}>العربية</a>
        <a role="menuitem" data-lang="en" className="lang-menu-item" href={langTwins().en}>English</a>
      </div>
    </div>
  );
}

// Products shown in the nav hover mega-menu (bilingual).
const PRODUCT_MENU = [
  { tag: "AI Lab",      tagAr: "مختبر الذكاء الاصطناعي", href: "Product.html#assistant", desc: "Ask, analyze, and draft — grounded in Saudi law.",   descAr: "اسأل، حلّل، وصُغ — بسند من الأنظمة السعودية." },
  { tag: "Word Add-in", tagAr: "إضافة Word",            href: "Product.html#word",      desc: "Wathiq's AI, natively inside Microsoft Word.",    descAr: "ذكاء وثّق، داخل Microsoft Word مباشرةً." },
  { tag: "Knowledge",   tagAr: "قاعدة المعرفة",          href: "Product.html#knowledge", desc: "Saudi laws and regulations, fully searchable.",   descAr: "الأنظمة واللوائح السعودية كاملةً، وبحث يصل إلى كل مادة." },
  { tag: "Vault",       tagAr: "الخزنة",                 href: "Product.html#vault",     desc: "Store and analyze your documents securely.",      descAr: "احفظ مستنداتك وحلّلها في مكان آمن." },
  { tag: "Playbook",    tagAr: "دليل العمل",             href: "Product.html#playbook",  desc: "Codify your firm's standards into AI rules.",     descAr: "حوّل معايير مكتبك إلى قواعد ينفّذها الذكاء الاصطناعي." },
  { tag: "Library",     tagAr: "المكتبة",                href: "Product.html#library",   desc: "Reusable prompts, playbooks, and agents.",        descAr: "موجِّهات وأدلّة عمل ووكلاء جاهزون لإعادة الاستخدام." },
  { tag: "Workflow",    tagAr: "سير العمل",              href: "Product.html#workflow",  desc: "Build custom agents — no code required.",         descAr: "ابنِ وكلاءك — دون أي برمجة." },
];

/* ============================================================
   SHARED COMPONENTS — Nav, CTA band, Footer
   Used on every page.
   ============================================================ */

function Nav({ active = "home" }) {
  const [menuOpen, setMenuOpen] = useState(false);
  // React owns the light/dark theme so a re-render (e.g. opening the menu)
  // can't clobber the class motion.js used to set imperatively. Inner pages
  // are always light; the home hero is dark until you scroll past it.
  const [light, setLight] = useState(
    () => typeof document !== "undefined" && document.body.classList.contains("page-inner")
  );

  useEffect(() => {
    if (document.body.classList.contains("page-inner")) { setLight(true); return; }
    const update = () => setLight(window.scrollY > window.innerHeight * 0.85);
    update();
    window.addEventListener("scroll", update, { passive: true });
    window.addEventListener("resize", update);
    return () => {
      window.removeEventListener("scroll", update);
      window.removeEventListener("resize", update);
    };
  }, []);

  // Close the mobile menu if the viewport grows back to desktop, so the
  // overlay never lingers after a rotation/resize.
  useEffect(() => {
    if (!menuOpen) return;
    const onResize = () => { if (window.innerWidth > 760) setMenuOpen(false); };
    const onKey = (e) => { if (e.key === "Escape") setMenuOpen(false); };
    window.addEventListener("resize", onResize);
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("resize", onResize);
      window.removeEventListener("keydown", onKey);
    };
  }, [menuOpen]);

  const Logo = AR ? LogoArabic : LogoEnglish;
  const arrow = AR ? "←" : "→";

  return (
    <nav className={`nav ${light ? "is-light" : "is-dark"} ${menuOpen ? "is-menu-open" : ""}`}>
      <div className="container nav-inner">
        <div className="nav-left">
          <a href="index.html" className="brand" aria-label="Wathiq — وثّق">
            <Logo style={{ height: 24 }} />
          </a>
        </div>
        <div className="nav-mid">
          <div className="nav-dd">
            <a href="Product.html" className={`navlink nav-dd-trigger ${active === "product" ? "is-active" : ""}`}>
              {AR ? "المنتج" : "Product"} <span className="chev" aria-hidden="true"><svg viewBox="0 0 12 12" fill="none"><path d="M2.5 4.75 6 8.25l3.5-3.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg></span>
            </a>
            <div className="nav-mega" role="menu" aria-label={AR ? "منتجات وثّق" : "Wathiq products"}>
              <div className="nav-mega-card">
                <div className="nav-mega-head">
                  <span className="nav-mega-eyebrow">{AR ? "المنصة" : "The platform"}</span>
                  <span className="nav-mega-tag">{AR ? "مساحة عمل واحدة تجمع أعمالك القانونية كلها" : "One workspace, every part of legal work"}</span>
                </div>
                <div className="nav-mega-grid">
                  {PRODUCT_MENU.map((p) => (
                    <a key={p.tag} href={p.href} className="nav-mega-item" role="menuitem">
                      <span className="nav-mega-item-top">
                        <span className="nav-mega-item-name">{AR ? p.tagAr : p.tag}</span>
                        <span className="nav-mega-arrow" aria-hidden="true">{arrow}</span>
                      </span>
                      <span className="nav-mega-item-desc">{AR ? p.descAr : p.desc}</span>
                    </a>
                  ))}
                </div>
              </div>
            </div>
          </div>
          <a href="Security.html" className={`navlink ${active === "security" ? "is-active" : ""}`}>{AR ? "الأمان" : "Security"}</a>
          <a href="About.html" className={`navlink ${active === "about" ? "is-active" : ""}`}>{AR ? "من نحن" : "About"}</a>
        </div>
        <div className="nav-right">
          <LangSwitch />
          <a href="Contact.html" className="btn nav-cta" onClick={() => window.waTrack && window.waTrack("cta_demo_click", { cta_location: "nav" })}>{AR ? "اطلب عرضًا توضيحيًا" : "Request a Demo"}</a>
          <button
            type="button"
            className="nav-toggle"
            aria-label={menuOpen ? "Close menu" : "Open menu"}
            aria-expanded={menuOpen}
            aria-controls="nav-mobile-panel"
            onClick={() => setMenuOpen((v) => !v)}
          >
            <span aria-hidden="true" /><span aria-hidden="true" /><span aria-hidden="true" />
          </button>
        </div>
      </div>

      <div className="nav-mobile" id="nav-mobile-panel" role="menu" aria-label="Menu">
        <div className="nav-mobile-inner">
          <a href="Product.html" className={`nav-mobile-link ${active === "product" ? "is-active" : ""}`}>{AR ? "المنتج" : "Product"}</a>
          <a href="Security.html" className={`nav-mobile-link ${active === "security" ? "is-active" : ""}`}>{AR ? "الأمان" : "Security"}</a>
          <a href="About.html" className={`nav-mobile-link ${active === "about" ? "is-active" : ""}`}>{AR ? "من نحن" : "About"}</a>
          <a href="Contact.html" className={`nav-mobile-link ${active === "contact" ? "is-active" : ""}`}>{AR ? "تواصل معنا" : "Contact"}</a>
          <div className="nav-mobile-lang-head" aria-hidden="true"><GlobeIcon /><span>{AR ? "اللغة" : "Language"}</span></div>
          <a data-lang="ar" className={`nav-mobile-link ${AR ? "is-active" : ""}`} href={langTwins().ar}>العربية</a>
          <a data-lang="en" className={`nav-mobile-link ${!AR ? "is-active" : ""}`} href={langTwins().en}>English</a>
          <a href="Contact.html" className="btn btn-dark nav-mobile-cta" onClick={() => window.waTrack && window.waTrack("cta_demo_click", { cta_location: "nav_mobile" })}>
            {AR ? "اطلب عرضًا توضيحيًا" : "Request a Demo"} <span className="arrow">{arrow}</span>
          </a>
        </div>
      </div>
    </nav>
  );
}

function CtaBand() {
  const arrow = AR ? "←" : "→";
  return (
    <section className="cta-band">
      <div className="container cta-band-inner reveal">
        <h2>{AR ? "ذكاء اصطناعي بمستوى نخبة المهنة، بين يدي مكتبك" : "Unlock Professional Class AI for Your Firm"}</h2>
        <a href="Contact.html" className="btn btn-white" onClick={() => window.waTrack && window.waTrack("cta_demo_click", { cta_location: "cta_band" })}>
          {AR ? "احجز عرضًا توضيحيًا" : "Book a Demo"} <span className="arrow">{arrow}</span>
        </a>
      </div>
    </section>
  );
}

function Footer() {
  const Logo = AR ? LogoArabic : LogoEnglish;
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <p>
              {AR
                ? "مساحة العمل الذكية للفرق القانونية في السعودية. صُنعت في الرياض، وبُنيت على الأنظمة السعودية، وأصيلة في لغتها العربية."
                : "The AI workspace for Saudi legal teams. Built in Riyadh, grounded in Saudi law, native to Arabic."}
            </p>
            <div className="footer-social">
              <a href="https://www.linkedin.com/company/113185348" target="_blank" rel="noopener noreferrer"
                 aria-label={AR ? "وثّق على لينكدإن" : "Wathiq on LinkedIn"}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                  <path d="M4.98 3.5A2.5 2.5 0 1 0 5 8.5a2.5 2.5 0 0 0-.02-5ZM3 9h4v12H3V9Zm6 0h3.8v1.64h.05c.53-.95 1.83-1.95 3.77-1.95 4.03 0 4.78 2.5 4.78 5.75V21H21v-5.9c0-1.4-.03-3.2-2-3.2-2 0-2.3 1.53-2.3 3.1V21H9V9Z"/>
                </svg>
              </a>
            </div>
          </div>
          <div className="footer-col">
            <h4>{AR ? "الروابط" : "Navigation"}</h4>
            <ul>
              <li><a href="index.html">{AR ? "الرئيسية" : "Home"}</a></li>
              <li><a href="About.html">{AR ? "من نحن" : "About"}</a></li>
              <li><a href="Security.html">{AR ? "الأمان" : "Security"}</a></li>
              <li><a href="Contact.html">{AR ? "تواصل معنا" : "Contact"}</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>{AR ? "الشؤون القانونية" : "Legal"}</h4>
            <ul>
              <li><a href="Terms.html">{AR ? "الشروط والأحكام" : "Terms & conditions"}</a></li>
              <li><a href="Privacy.html">{AR ? "سياسة الخصوصية" : "Privacy policy"}</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-wordmark" aria-hidden="true">
          <Logo />
        </div>
        <div className="footer-bottom">
          <span>{AR ? "© 2026 وثّق — شركة فارس إبراهيم الغامدي وعبدالرحمن ياسر عسيلان · الرقم الوطني الموحد 7050363576" : "© 2026 Wathiq — Fares Ibrahim Alghamdi & Abdulrahman Yasser Osailan Company · Unified National No. 7050363576"}</span>
          <span>{AR ? "صُنع في السعودية" : "Made in Saudi Arabia"}</span>
        </div>
      </div>
    </footer>
  );
}

/* ============================================================
   HERO MARQUEE — partner institutions strip
   The marquee is now STATIC HTML in index.html (it paints with the hero before
   any JS). Its logo list + markup live there; the old HeroMarquee component +
   MARQUEE_LOGOS data were removed so there's a single source of truth.
   ============================================================ */

const CrestSvg = ({ variant }) => {
  const palms = (<g>
    <path d="M22 8 Q14 14 12 22 Q20 18 22 14 Z" fill="currentColor" opacity="0.85"/>
    <path d="M22 8 Q30 14 32 22 Q24 18 22 14 Z" fill="currentColor" opacity="0.85"/>
    <path d="M22 8 L22 32" stroke="currentColor" strokeWidth="1.4" opacity="0.9"/>
    <path d="M16 32 Q22 38 28 32" stroke="currentColor" strokeWidth="1.1" fill="none" opacity="0.9"/>
    <path d="M16 32 L28 32" stroke="currentColor" strokeWidth="1.1" opacity="0.8"/>
  </g>);
  const scales = (<g>
    <circle cx="22" cy="14" r="2" fill="none" stroke="currentColor" strokeWidth="1.2" opacity="1"/>
    <path d="M22 16 L22 36" stroke="currentColor" strokeWidth="1.3" opacity="1"/>
    <path d="M10 20 L34 20" stroke="currentColor" strokeWidth="1.1" opacity="0.9"/>
    <path d="M10 20 L7 28 Q10 31 13 28 Z" fill="none" stroke="currentColor" strokeWidth="1" opacity="0.9"/>
    <path d="M34 20 L31 28 Q34 31 37 28 Z" fill="none" stroke="currentColor" strokeWidth="1" opacity="0.9"/>
    <path d="M18 38 L26 38" stroke="currentColor" strokeWidth="1" opacity="0.9"/>
  </g>);
  const shield = (<g>
    <path d="M10 8 L34 8 L34 22 Q34 32 22 40 Q10 32 10 22 Z" fill="none" stroke="currentColor" strokeWidth="1.2" opacity="1"/>
    <path d="M22 14 L22 30" stroke="currentColor" strokeWidth="1" opacity="0.9"/>
    <path d="M16 18 Q22 22 28 18" stroke="currentColor" strokeWidth="1" fill="none" opacity="0.9"/>
    <path d="M16 24 L28 24" stroke="currentColor" strokeWidth="1" opacity="0.9"/>
  </g>);
  const sword = (<g>
    <path d="M22 6 L22 38" stroke="currentColor" strokeWidth="1.3" opacity="1"/>
    <path d="M16 12 L28 12" stroke="currentColor" strokeWidth="1.2" opacity="1"/>
    <path d="M22 6 L20 10 L24 10 Z" fill="currentColor" opacity="0.9"/>
  </g>);
  const variants = { palms, scales, shield, sword };
  const order = ["palms","scales","shield","sword"];
  const v = order[variant % 4] || "palms";
  return (
    <svg viewBox="0 0 44 44" xmlns="http://www.w3.org/2000/svg">{variants[v]}</svg>
  );
};

Object.assign(window, { Nav, CtaBand, Footer, LangSwitch, GlobeIcon });
