// QYAS — shared Nav, Footer, Page shell
const { useState, useEffect } = React;

const LANGS = [
  { code: "en", label: "EN", dir: "ltr" },
  { code: "ar", label: "AR", dir: "rtl" },
  { code: "fr", label: "FR", dir: "ltr" },
  { code: "de", label: "DE", dir: "ltr" },
];

function useLang() {
  const [lang, setLang] = useState(() => {
    try { return localStorage.getItem("qyas-lang") || "en"; } catch { return "en"; }
  });
  useEffect(() => {
    try { localStorage.setItem("qyas-lang", lang); } catch {}
    const meta = LANGS.find(l => l.code === lang);
    document.documentElement.lang = lang;
    document.documentElement.dir = meta?.dir || "ltr";
  }, [lang]);
  const t = window.I18N[lang] || window.I18N.en;
  return { lang, setLang, t };
}

// === Floating background icons (calculator / water drop / dashboard gauge) ===
// Sits ABOVE section backgrounds but BELOW content so it's visible on every page.
(function injectFloatingIcons() {
  if (document.getElementById('qyas-floating-bg')) return;

  // Three inline SVGs. Use currentColor so they pick up the section color.
  // 0 = Calculator (handheld device with screen + keypad)
  // 1 = Water drop
  // 2 = Dashboard gauge (speedometer)
  const svgs = [
    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">' +
      '<rect x="4" y="2.5" width="16" height="19" rx="2.2"/>' +
      '<rect x="6.5" y="5" width="11" height="4" rx="0.8"/>' +
      '<line x1="8" y1="7" x2="13" y2="7"/>' +
      '<circle cx="8.2" cy="12" r="0.9" fill="currentColor"/>' +
      '<circle cx="12" cy="12" r="0.9" fill="currentColor"/>' +
      '<circle cx="15.8" cy="12" r="0.9" fill="currentColor"/>' +
      '<circle cx="8.2" cy="15.2" r="0.9" fill="currentColor"/>' +
      '<circle cx="12" cy="15.2" r="0.9" fill="currentColor"/>' +
      '<circle cx="15.8" cy="15.2" r="0.9" fill="currentColor"/>' +
      '<circle cx="8.2" cy="18.4" r="0.9" fill="currentColor"/>' +
      '<circle cx="12" cy="18.4" r="0.9" fill="currentColor"/>' +
      '<rect x="14.9" y="17.5" width="1.9" height="1.9" rx="0.4" fill="currentColor"/>' +
    '</svg>',
    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">' +
      '<path d="M12 2.5 C12 2.5 5.5 9.5 5.5 14.5 a6.5 6.5 0 0 0 13 0 C18.5 9.5 12 2.5 12 2.5 z"/>' +
      '<path d="M9 14 a3.5 3.5 0 0 0 3 3" opacity="0.6"/>' +
    '</svg>',
    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">' +
      '<path d="M3.5 17 a8.5 8.5 0 0 1 17 0"/>' +
      '<line x1="12" y1="17" x2="16.2" y2="10.8"/>' +
      '<circle cx="12" cy="17" r="1.5" fill="currentColor"/>' +
      '<line x1="5" y1="17" x2="6.2" y2="17" stroke-width="1.2"/>' +
      '<line x1="8" y1="11.5" x2="8.8" y2="12.3" stroke-width="1.2"/>' +
      '<line x1="12" y1="9" x2="12" y2="10" stroke-width="1.2"/>' +
      '<line x1="16" y1="11.5" x2="15.2" y2="12.3" stroke-width="1.2"/>' +
      '<line x1="19" y1="17" x2="17.8" y2="17" stroke-width="1.2"/>' +
    '</svg>',
  ];

  const container = document.createElement('div');
  container.id = 'qyas-floating-bg';
  for (let i = 0; i < 45; i++) {
    const svg = svgs[i % svgs.length];
    const size = 28 + Math.random() * 42;
    const left = Math.random() * 100;
    const dur = 22 + Math.random() * 28;
    const delay = -(Math.random() * 50);
    const rot = Math.floor(Math.random() * 360);
    const drift = (Math.random() * 100 - 50).toFixed(0);
    const anims = ['swimUp', 'swimDiag', 'swimWave'];
    const anim = anims[i % anims.length];
    const el = document.createElement('span');
    el.innerHTML = svg;
    el.style.cssText =
      'position:absolute;' +
      'left:' + left + '%;' +
      'bottom:-100px;' +
      'width:' + size + 'px;' +
      'height:' + size + 'px;' +
      'transform:rotate(' + rot + 'deg);' +
      '--drift:' + drift + 'px;' +
      'animation:' + anim + ' ' + dur + 's linear ' + delay + 's infinite;' +
      'will-change:transform;';
    container.appendChild(el);
  }
  const mount = () => document.body.appendChild(container);
  if (document.body) mount(); else document.addEventListener('DOMContentLoaded', mount);
})();

function Nav({ active, lang, setLang }) {
  const t = (window.I18N[lang] || window.I18N.en).nav;
  const [open, setOpen] = useState(false);
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);
  const links = [
    { href: "index.html", key: "home", label: t.home },
    { href: "features.html", key: "features", label: t.features },
    { href: "how-it-works.html", key: "howItWorks", label: t.howItWorks },
    { href: "pricing.html", key: "pricing", label: t.pricing },
    { href: "faq.html", key: "faq", label: t.faq },
    { href: "contact.html", key: "contact", label: t.contact },
  ];
  const cta = (window.I18N[lang] || window.I18N.en).cta.download;
  return (
    <>
    <nav className={"nav" + (open ? " nav-open" : "")}>
      <div className="container nav-inner">
        <a href="index.html" className="nav-logo">
          <img src="public/qyas-logo.webp" alt="QYAS" />
        </a>
        <div className="nav-links">
          {links.map(l => (
            <a key={l.key} href={l.href} className={"nav-link" + (active === l.key ? " active" : "")}>{l.label}</a>
          ))}
        </div>
        <div className="nav-actions">
          <div className="lang-switch">
            {LANGS.map(l => (
              <button key={l.code} className={"lang-btn" + (lang === l.code ? " active" : "")} onClick={() => setLang(l.code)}>{l.label}</button>
            ))}
          </div>
          <a href="contact.html" className="btn btn-primary nav-cta">{cta} <span aria-hidden="true">↓</span></a>
          <button
            className="nav-burger"
            aria-label={open ? "Close menu" : "Open menu"}
            aria-expanded={open}
            onClick={() => setOpen(!open)}
          >
            <span></span><span></span><span></span>
          </button>
        </div>
      </div>
    </nav>
    {/* Mobile drawer — rendered OUTSIDE <nav> so it escapes nav's backdrop-filter
        containing block and positions against the viewport. */}
    <div className={"nav-drawer" + (open ? " open" : "")} role="dialog" aria-hidden={!open}>
      <div className="nav-drawer-links">
        {links.map(l => (
          <a
            key={l.key}
            href={l.href}
            className={"nav-drawer-link" + (active === l.key ? " active" : "")}
            onClick={() => setOpen(false)}
          >
            {l.label}
          </a>
        ))}
      </div>
      <div className="nav-drawer-cta">
        <a href="contact.html" className="btn btn-primary" style={{ width: "100%", justifyContent: "center" }} onClick={() => setOpen(false)}>{cta} <span aria-hidden="true">↓</span></a>
      </div>
    </div>
    </>
  );
}

function Footer({ lang }) {
  const isAR = lang === "ar";
  const cols = {
    en: {
      tagline: "Meter management for water & utility operations.",
      product: { title: "Product", links: ["Features","How it works","Pricing","Changelog","Status"] },
      company: { title: "Company", links: ["About","Customers","Press","Careers"] },
      resources: { title: "Resources", links: ["Documentation","API","Integrations","Security"] },
      legal: { title: "Legal", links: ["Privacy","Terms","DPA","SLA"] },
      copy: "© 2026 QYAS Systems · v1.595 (Beta)",
      built: "Built in Riyadh · Made for utility operators",
    },
    ar: {
      tagline: "إدارة العدّادات لعمليات المياه والمرافق.",
      product: { title: "المنتج", links: ["الميزات","كيف يعمل","الأسعار","التحديثات","الحالة"] },
      company: { title: "الشركة", links: ["من نحن","العملاء","الصحافة","الوظائف"] },
      resources: { title: "موارد", links: ["التوثيق","API","التكاملات","الأمان"] },
      legal: { title: "قانوني", links: ["الخصوصية","الشروط","DPA","SLA"] },
      copy: "© 2026 قياس · الإصدار 1.595 (تجريبي)",
      built: "صُنع في الرياض · لمشغّلي المرافق",
    },
    fr: {
      tagline: "Gestion des compteurs pour les opérations d'eau et de services.",
      product: { title: "Produit", links: ["Fonctions","Fonctionnement","Tarifs","Changelog","Statut"] },
      company: { title: "Société", links: ["À propos","Clients","Presse","Carrières"] },
      resources: { title: "Ressources", links: ["Documentation","API","Intégrations","Sécurité"] },
      legal: { title: "Légal", links: ["Confidentialité","Conditions","DPA","SLA"] },
      copy: "© 2026 QYAS Systems · v1.595 (Beta)",
      built: "Conçu à Riyad · Pour les opérateurs",
    },
    de: {
      tagline: "Zählermanagement für Wasser- und Versorgungsbetriebe.",
      product: { title: "Produkt", links: ["Funktionen","So geht's","Preise","Changelog","Status"] },
      company: { title: "Firma", links: ["Über uns","Kunden","Presse","Karriere"] },
      resources: { title: "Ressourcen", links: ["Dokumentation","API","Integrationen","Sicherheit"] },
      legal: { title: "Rechtliches", links: ["Datenschutz","AGB","DPA","SLA"] },
      copy: "© 2026 QYAS Systems · v1.595 (Beta)",
      built: "Gebaut in Riad · Für Betreiber",
    },
  };
  const c = cols[lang] || cols.en;
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
              <img src="public/qyas-logo.webp" alt="QYAS" style={{ height: 36, filter: "brightness(0) invert(1)" }} />
              <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, color: "#fff" }}>QYAS</span>
            </div>
            <p style={{ maxWidth: 280, lineHeight: 1.6 }}>{c.tagline}</p>
            <div style={{ marginTop: 24, display: "flex", gap: 8 }}>
              <span className="tag tag-dark"><span className="dot pulse" style={{ color: "#34d399" }}></span>SYSTEM OPERATIONAL</span>
            </div>
          </div>
          {[c.product, c.company, c.resources, c.legal].map((col, i) => (
            <div key={i}>
              <h5>{col.title}</h5>
              <ul style={{ listStyle: "none", display: "grid", gap: 10 }}>
                {col.links.map(l => <li key={l}><a href="#">{l}</a></li>)}
              </ul>
            </div>
          ))}
        </div>
        <div className="footer-bottom">
          <span>{c.copy}</span>
          <span>{c.built}</span>
        </div>
      </div>
    </footer>
  );
}

window.QyasShell = { Nav, Footer, useLang };
