// Shared Nav + Footer for all pages
const D_NAV = window.MISLAK_DATA;

function useHashRoute() {
  const [hash, setHash] = React.useState(window.location.hash || "#/");
  React.useEffect(() => {
    const onChange = () => {
      setHash(window.location.hash || "#/");
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onChange);
    return () => window.removeEventListener("hashchange", onChange);
  }, []);
  return hash;
}

function parseRoute(hash) {
  // formats: #/, #/services, #/services/unified, #/sectors, #/sectors/ecom, #/how, #/ai, #/pricing, #/contact
  const path = hash.replace(/^#\/?/, "");
  const [seg, sub] = path.split("/");
  return { seg: seg || "home", sub: sub || null };
}

function NavLink({ href, label }) {
  const hash = useHashRoute();
  const target = `#${href}`;
  const active = hash === target || (href !== "/" && hash.startsWith(target));
  return (
    <a href={target} className={active ? "active" : ""}>{label}</a>
  );
}

function goToSection(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const y = el.getBoundingClientRect().top + window.scrollY - 72;
  window.scrollTo({ top: y, behavior: "smooth" });
}

function NavScrollLink({ id, label, onNavigate }) {
  const onClick = (e) => {
    e.preventDefault();
    if (onNavigate) onNavigate();
    const h = window.location.hash;
    const isHome = h === "" || h === "#" || h === "#/";
    if (isHome) {
      goToSection(id);
    } else {
      window.__pendingScroll = id;
      window.location.hash = "#/";
    }
  };
  return <a href="#/" onClick={onClick}>{label}</a>;
}

function NavDropdown({ href, label }) {
  const hash = useHashRoute();
  const [open, setOpen] = React.useState(false);
  const target = `#${href}`;
  const active = hash.startsWith(target);
  const sectors = window.getData().sectors;
  const closeT = React.useRef(null);
  const enter = () => { clearTimeout(closeT.current); setOpen(true); };
  const leave = () => { closeT.current = setTimeout(() => setOpen(false), 120); };
  return (
    <div className="nav-dd" onMouseEnter={enter} onMouseLeave={leave}>
      <a href={target} className={(active ? "active " : "") + "nav-dd-trigger"}>
        {label}
        <span className="nav-dd-caret" aria-hidden="true">▾</span>
      </a>
      <div className={"nav-dd-menu" + (open ? " open" : "")}>
        {sectors.map((s) => (
          <a key={s.id} href={`#/sectors/${s.id}`} onClick={() => setOpen(false)}>{s.tab}</a>
        ))}
        <a className="nav-dd-all" href={target} onClick={() => setOpen(false)}>
          {window.L("كافة القطاعات", "All sectors")} <span className="mono">{window.ARR()}</span>
        </a>
      </div>
    </div>
  );
}

function Nav() {
  const [open, setOpen] = React.useState(false);
  const hash = useHashRoute();
  const lang = window.useLang();
  const isHome = hash === "#/" || hash === "#" || hash === "";
  const [atTop, setAtTop] = React.useState(true);
  React.useEffect(() => {
    const onScroll = () => setAtTop(window.scrollY < 40);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const onHero = !open;
  React.useEffect(() => { setOpen(false); }, [hash]);
  React.useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const links = [
    { section: "features", label: window.L("الخدمات", "Services") },
    { section: "sectors", label: window.L("القطاعات", "Sectors") },
    { section: "agents", label: window.L("وكلاء الذكاء الاصطناعي", "AI Agents") },
    { href: "/contact", label: window.L("تواصل معنا", "Contact"), contactScroll: true },
  ];
  const renderLink = (l, close) => l.contactScroll
    ? <NavScrollLink key="contact" id="contact" label={l.label} onNavigate={close} />
    : l.section
    ? <NavScrollLink key={l.section} id={l.section} label={l.label} onNavigate={close} />
    : <NavLink key={l.href} href={l.href} label={l.label} />;

  return (
    <header className={"nav" + (onHero ? " nav-on-hero" : "")}>
      <div className="container nav-inner">
        <a href="#/" className="brand" onClick={(e) => {
          setOpen(false);
          const h = window.location.hash;
          if (h === "" || h === "#" || h === "#/") {
            e.preventDefault();
            window.scrollTo({ top: 0, behavior: "smooth" });
          }
        }}>
          <img className="brand-logo" src={onHero ? "assets/mislak-logo-white.png" : "assets/mislak-logo-purple.png"} alt="مسلاك · MISLAK" />
        </a>
        <nav className="nav-links">
          {links.map((l) => renderLink(l))}
        </nav>
        <div className="nav-cta">
          <button className="lang-toggle" onClick={() => window.setLang(lang === "ar" ? "en" : "ar")} aria-label="Toggle language">
            <span className={"mono" + (lang === "en" ? " lt-on" : "")}>EN</span>
            <span>/</span>
            <span className={lang === "ar" ? "lt-on" : ""}>ع</span>
          </button>
          <a className="btn btn-sm btn-accent nav-login-btn" href="#/login">{window.L("تسجيل الدخول", "Log in")}</a>
          <button
            className={"nav-burger" + (open ? " open" : "")}
            aria-label={window.L("القائمة", "Menu")}
            aria-expanded={open}
            onClick={() => setOpen((v) => !v)}
          >
            <span></span><span></span><span></span>
          </button>
        </div>
      </div>

      <div className={"nav-mobile" + (open ? " open" : "")}>
        <nav className="nav-mobile-links">
          {links.map((l) => renderLink(l, () => setOpen(false)))}
        </nav>
        <a className="btn btn-ghost nav-mobile-cta" href="#/login" onClick={() => setOpen(false)} style={{marginTop: 10}}>{window.L("تسجيل الدخول", "Log in")}</a>
        <button className="lang-toggle nav-mobile-lang" onClick={() => window.setLang(lang === "ar" ? "en" : "ar")}>
          <span className={"mono" + (lang === "en" ? " lt-on" : "")}>English</span>
          <span>/</span>
          <span className={lang === "ar" ? "lt-on" : ""}>العربية</span>
        </button>
      </div>
      <div className={"nav-scrim" + (open ? " open" : "")} onClick={() => setOpen(false)}></div>
    </header>
  );
}

function Footer() {
  return (
    <footer>
      <div className="container">
        <div className="foot-grid">
          <div className="foot-col foot-about">
            <a href="#/" className="brand" onClick={(e) => {
              const h = window.location.hash;
              if (h === "" || h === "#" || h === "#/") {
                e.preventDefault();
                window.scrollTo({ top: 0, behavior: "smooth" });
              }
            }}>
              <img className="brand-logo brand-logo-foot" src="assets/mislak-logo-white.png" alt="مسلاك · MISLAK" />
            </a>
            <p>{window.L(<>البنية الحديثة لاتصالات الأعمال.<br/>تجمع كل ما يحتاجه فريقك للتواصل والعمل بكفاءة.</>, <>The modern infrastructure for business communications.<br/>Everything your team needs to communicate and work efficiently, in one place.</>)}</p>
            <div className="foot-social">
              <a href="https://www.linkedin.com/company/mislak-sa/about/" target="_blank" rel="noopener" aria-label="LinkedIn">
                <svg width="17" height="17" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                  <path d="M20.45 20.45h-3.56v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.35V9h3.41v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43a2.06 2.06 0 1 1 0-4.13 2.06 2.06 0 0 1 0 4.13zM7.12 20.45H3.55V9h3.57v11.45zM22.22 0H1.77C.8 0 0 .78 0 1.74v20.52C0 23.22.8 24 1.77 24h20.45c.98 0 1.78-.78 1.78-1.74V1.74C24 .78 23.2 0 22.22 0z"></path>
                </svg>
              </a>
              <a href="https://x.com/Mislak_sa" target="_blank" rel="noopener" aria-label="X">𝕏</a>
              <a href="https://www.instagram.com/mislak_sa" target="_blank" rel="noopener" aria-label="Instagram">
                <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect>
                  <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path>
                  <line x1="17.5" y1="6.5" x2="17.51" y2="6.5"></line>
                </svg>
              </a>
              <a href="https://vt.tiktok.com/ZSC8Y8Mes" target="_blank" rel="noopener" aria-label="TikTok">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                  <path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-5.2 1.74 2.89 2.89 0 0 1 2.31-4.64c.3 0 .59.04.87.13V9.4a6.84 6.84 0 0 0-1-.05A6.33 6.33 0 0 0 5 20.1a6.34 6.34 0 0 0 10.86-4.43v-7a8.16 8.16 0 0 0 4.77 1.52v-3.4a4.85 4.85 0 0 1-1.04-.1z"></path>
                </svg>
              </a>
            </div>
          </div>
          <div className="foot-col">
            <h5>{window.L("الشركة", "Company")}</h5>
            <ul>
              <li><a href="#/about">{window.L("من نحن", "About")}</a></li>
              <li><a href="#/careers">{window.L("الوظائف", "Careers")}</a></li>
            </ul>
          </div>
          <div className="foot-col">
            <h5>{window.L("الدعم", "Support")}</h5>
            <ul>
              <li><a href="#/contact">{window.L("تواصل معنا", "Contact")}</a></li>
              <li><a href="#/deletion">{window.L("حذف البيانات الشخصية", "Personal Data Deletion")}</a></li>
              <li><a href="#/privacy">{window.L("الخصوصية", "Privacy")}</a></li>
              <li><a href="#/terms">{window.L("الشروط", "Terms")}</a></li>
            </ul>
          </div>
        </div>
        <div className="foot-bot">
          <div>{window.L("© 2026 مسلاك. جميع الحقوق محفوظة.", "© 2026 Mislak. All rights reserved.")}</div>
        </div>
      </div>
    </footer>
  );
}

// Shared page-top hero for inner pages
function PageHero({ eyebrow, title, sub, breadcrumbs }) {
  return (
    <section className="page-hero">
      <div className="container">
        {breadcrumbs && (
          <div className="crumbs">
            {breadcrumbs.map((c, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span className="crumb-sep">{window.ARR()}</span>}
                {c.href ? <a href={c.href}>{c.label}</a> : <span>{c.label}</span>}
              </React.Fragment>
            ))}
          </div>
        )}
        <div className="sec-eyebrow">{eyebrow}</div>
        <h1 className="page-h1">{title}</h1>
        {sub && <p className="page-sub">{sub}</p>}
      </div>
    </section>
  );
}

// Page CTA — used at bottom of inner pages
function PageCTA({ h, btn, href = "#/contact" }) {
  return (
    <section style={{paddingTop: 20, paddingBottom: 72}}>
      <div className="container">
        <div className="page-cta">
          <h3>{h}</h3>
          <a className="btn btn-accent" href={href}>{btn} <span className="mono">{window.ARR()}</span></a>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Footer, useHashRoute, parseRoute, PageHero, PageCTA, NavLink });
