/* ============================================================
   Shared chrome — Nav, Footer, Router helpers
   ============================================================ */

const { useState, useEffect, useRef, useMemo } = React;

/* ---------- Hash router ---------- */
function useHashRoute() {
  const [route, setRoute] = useState(() => (window.location.hash || "#/").replace(/^#/, "") || "/");
  useEffect(() => {
    const onHash = () => {
      setRoute((window.location.hash || "#/").replace(/^#/, "") || "/");
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return route;
}

function Link({ to, children, className = "", style = {}, onClick }) {
  // External / WHMCS links: render as real anchor (new tab optional)
  const isExternal = /^https?:\/\//.test(to) || to.startsWith("/whmcs") || to.startsWith("mailto:");
  const href = isExternal ? to : "#" + to;
  return (
    <a
      href={href}
      className={className}
      style={style}
      onClick={(e) => { onClick && onClick(e); }}
    >
      {children}
    </a>
  );
}

/* ---------- WHMCS endpoint constants ----------
   Loominost WHMCS lives at /whmcs/ — update if yours differs. */
const WHMCS = {
  signup:   "/whmcs/index.php?rp=/store/shared-hosting-cpanel",
  login:    "/whmcs/index.php?rp=/login",
  register: "/whmcs/index.php?rp=/register",
  cart:     "/whmcs/cart.php",
  ticket:   "/whmcs/submitticket.php",
  sales:    "/whmcs/submitticket.php?step=2&deptid=1",
  support:  "/whmcs/submitticket.php?step=2&deptid=2",
  abuse:    "/whmcs/contact.php",
  status:   "/whmcs/serverstatus.php",
  kb:       "/whmcs/knowledgebase.php",
  news:     "/whmcs/announcements.php",
  clientarea: "/whmcs/clientarea.php",
};
window.WHMCS = WHMCS;

/* ---------- Announcement bar ---------- */
function AnnouncementBar() {
  return (
    <div style={{
      background: "var(--ink)",
      color: "var(--bg)",
      fontFamily: "var(--font-mono)",
      fontSize: 12,
      letterSpacing: "0.02em",
      textAlign: "center",
      padding: "8px 16px",
    }}>
      <span style={{ color: "var(--accent-glow)" }}>●</span>{" "}
      UNLIMITED Resources cPanel hosting from <b style={{ color: "#fff" }}>$2.95/mo</b>.{" "}
      <Link to={WHMCS.signup} style={{ textDecoration: "underline", textUnderlineOffset: 3 }}>
        See plans →
      </Link>
    </div>
  );
}

/* ---------- Top Nav ---------- */
function TopNav({ route }) {
  const [open, setOpen] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const navItems = [
    { to: "/hosting", label: "cPanel Hosting" },
    { to: "/pricing", label: "Pricing" },
    { to: "/locations", label: "Locations" },
    { to: "/docs", label: "Docs" },
    { label: "Free Tools", children: [
      { to: "https://reallydownornot.com", label: "Website Checker" },
    ]},
    { to: "https://loominost.com/whmcs/contact.php", label: "Contact" },
  ];
  return (
    <header style={{
      position: "sticky",
      top: 0,
      zIndex: 40,
      background: "#ffffff",
      backdropFilter: "blur(12px) saturate(140%)",
      WebkitBackdropFilter: "blur(12px) saturate(140%)",
      borderBottom: "1px solid var(--line)",
    }}>
      <div className="wrap" style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        height: 72,
      }}>
        <Link to="/" style={{ display: "flex", alignItems: "center" }}>
          <LoominostLogo size={42} />
        </Link>

        <nav className="nav-menu" style={{ display: "flex", gap: 4, alignItems: "center" }}>
          {navItems.map(n => {
            if (n.children) {
              return (
                <div
                  key={n.label}
                  style={{ position: "relative" }}
                  onMouseEnter={(e) => {
                    const dd = e.currentTarget.querySelector("[data-dropdown]");
                    if (dd) { dd.style.opacity = "1"; dd.style.pointerEvents = "auto"; dd.style.transform = "translateY(0)"; }
                  }}
                  onMouseLeave={(e) => {
                    const dd = e.currentTarget.querySelector("[data-dropdown]");
                    if (dd) { dd.style.opacity = "0"; dd.style.pointerEvents = "none"; dd.style.transform = "translateY(-4px)"; }
                  }}
                >
                  <span style={{
                    fontSize: 14,
                    padding: "8px 14px",
                    borderRadius: 999,
                    color: "var(--ink-2)",
                    cursor: "default",
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 4,
                  }}>
                    {n.label}
                    <svg width="10" height="10" viewBox="0 0 12 12" fill="none" style={{ marginTop: 1 }}>
                      <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </span>
                  <div
                    data-dropdown
                    style={{
                      position: "absolute",
                      top: "100%",
                      left: 0,
                      paddingTop: 8,
                      opacity: 0,
                      pointerEvents: "none",
                      transform: "translateY(-4px)",
                      transition: "opacity 160ms var(--ease), transform 160ms var(--ease)",
                      zIndex: 50,
                    }}
                  >
                    <div style={{
                      background: "#fff",
                      border: "1px solid var(--line)",
                      borderRadius: 12,
                      boxShadow: "0 8px 32px rgba(10,18,32,0.08)",
                      padding: 6,
                      minWidth: 200,
                    }}>
                      {n.children.map(c => (
                        <Link
                          key={c.label}
                          to={c.to}
                          style={{
                            display: "block",
                            padding: "10px 14px",
                            borderRadius: 8,
                            fontSize: 14,
                            color: "var(--ink)",
                            transition: "background 120ms var(--ease)",
                          }}
                          onMouseEnter={(e) => { e.currentTarget.style.background = "var(--bg-3)"; }}
                          onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}
                        >
                          {c.label}
                        </Link>
                      ))}
                    </div>
                  </div>
                </div>
              );
            }
            const active = route === n.to || (n.to !== "/" && route.startsWith(n.to));
            return (
              <Link
                key={n.to}
                to={n.to}
                style={{
                  fontSize: 14,
                  padding: "8px 14px",
                  borderRadius: 999,
                  color: active ? "var(--ink)" : "var(--ink-2)",
                  background: active ? "var(--bg-3)" : "transparent",
                  fontWeight: active ? 500 : 400,
                  transition: "all 140ms var(--ease)",
                }}
              >
                {n.label}
              </Link>
            );
          })}
        </nav>

        <div className="nav-actions" style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <Link to={WHMCS.login} className="btn btn-ghost btn-sm">Client Login</Link>
          <Link to="/pricing" className="btn btn-primary btn-sm">
            Get started <span className="arrow">→</span>
          </Link>
          <button
            className="nav-mobile-toggle"
            aria-label="Menu"
            onClick={() => setMobileOpen(v => !v)}
            style={{
              background: "transparent",
              border: "1px solid var(--line)",
              borderRadius: 10,
              width: 40, height: 40,
              alignItems: "center",
              justifyContent: "center",
              cursor: "pointer",
              padding: 0,
            }}
          >
            <svg width="18" height="14" viewBox="0 0 18 14" fill="none">
              {mobileOpen ? (
                <>
                  <path d="M2 2L16 12" stroke="var(--ink)" strokeWidth="1.8" strokeLinecap="round"/>
                  <path d="M16 2L2 12" stroke="var(--ink)" strokeWidth="1.8" strokeLinecap="round"/>
                </>
              ) : (
                <>
                  <path d="M1 1H17" stroke="var(--ink)" strokeWidth="1.8" strokeLinecap="round"/>
                  <path d="M1 7H17" stroke="var(--ink)" strokeWidth="1.8" strokeLinecap="round"/>
                  <path d="M1 13H17" stroke="var(--ink)" strokeWidth="1.8" strokeLinecap="round"/>
                </>
              )}
            </svg>
          </button>
        </div>
      </div>
      {mobileOpen && (
        <div className="nav-drawer" onClick={() => setMobileOpen(false)}>
          {navItems.map(n => {
            if (n.children) {
              return (
                <div key={n.label}>
                  <div style={{ padding: "14px 0", fontSize: 12, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--ink-3)", borderBottom: "1px solid var(--line)" }}>{n.label}</div>
                  {n.children.map(c => (
                    <Link key={c.label} to={c.to} style={{ paddingLeft: 12 }}>{c.label}</Link>
                  ))}
                </div>
              );
            }
            return <Link key={n.to} to={n.to}>{n.label}</Link>;
          })}
          <Link to={WHMCS.login} style={{ marginTop: 16, color: "var(--accent)" }}>Client Login</Link>
          <Link to="/pricing" className="btn btn-primary" style={{ marginTop: 16, width: "100%", justifyContent: "center" }}>
            Get started <span className="arrow">→</span>
          </Link>
        </div>
      )}
    </header>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  return (
    <footer style={{
      background: "var(--ink)",
      color: "#C9C4BA",
      paddingTop: 80,
      paddingBottom: 28,
      marginTop: 120,
    }}>
      <div className="wrap">
        {/* Big lockup */}
        <div style={{
          display: "flex",
          alignItems: "flex-end",
          justifyContent: "space-between",
          gap: 40,
          paddingBottom: 64,
          borderBottom: "1px solid #2a2a2a",
          flexWrap: "wrap",
        }}>
          <div style={{ flex: "1 1 380px", minWidth: 280 }}>
            <div style={{
              fontFamily: "var(--font-serif)",
              fontSize: "clamp(40px, 5vw, 72px)",
              lineHeight: 0.95,
              letterSpacing: "-0.02em",
              color: "#fff",
            }}>
              Ready when<br/>
              <em style={{ color: "var(--accent-glow)", fontStyle: "italic" }}>you are.</em>
            </div>
          </div>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            <Link to={WHMCS.signup} className="btn btn-accent">
              Start hosting <span className="arrow">→</span>
            </Link>
          </div>
        </div>

        {/* Link cols */}
        <div style={{
          display: "grid",
          gridTemplateColumns: "1.4fr 1fr 1fr 1fr 1fr",
          gap: 40,
          padding: "56px 0",
          borderBottom: "1px solid #2a2a2a",
        }}>
          <div>
            <LoominostLogo size={40} color="#fff" />
            <p style={{
              marginTop: 18,
              fontSize: 13,
              color: "#8a857c",
              maxWidth: 260,
              lineHeight: 1.6,
            }}>
              Fast, reliable cPanel web hosting. LiteSpeed + NVMe in Florida, Seattle, and Frankfurt.
            </p>
            <div style={{ marginTop: 20 }}>
              <span className="pill" style={{
                background: "transparent",
                borderColor: "#2a2a2a",
                color: "#C9C4BA",
              }}>
                <span className="dot" />
                All systems operational
              </span>
            </div>
          </div>
          <FooterCol title="Product" items={[
            ["cPanel Hosting", "/hosting"],
            ["Pricing", "/pricing"],
            ["Locations", "/locations"],
            ["Migration", "/hosting#migration"],
          ]} />
          <FooterCol title="Resources" items={[
            ["Docs", "/docs"],
            ["Knowledgebase", WHMCS.kb],
            ["Announcements", WHMCS.news],
            ["Server Status", WHMCS.status],
          ]} />
          <FooterCol title="Company" items={[
            ["Contact sales", WHMCS.sales],
            ["Open a ticket", WHMCS.ticket],
            ["Client area", WHMCS.clientarea],
            ["Report abuse", WHMCS.abuse],
          ]} />
          <FooterCol title="Legal" items={[
            ["Terms of Service", "/legal/tos"],
            ["Privacy Policy", "/legal/privacy"],
            ["Acceptable Use", "/legal/aup"],
          ]} />
        </div>

        {/* Bottom bar */}
        <div style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          paddingTop: 28,
          fontFamily: "var(--font-mono)",
          fontSize: 11,
          color: "#6a655c",
          letterSpacing: "0.04em",
        }}>
          <div>© 2023–2026 Loominost LLP · LLP0037896-LGN</div>
          <div>hello@loominost.com · support@loominost.com</div>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, items }) {
  return (
    <div>
      <div style={{
        fontFamily: "var(--font-mono)",
        fontSize: 11,
        letterSpacing: "0.12em",
        textTransform: "uppercase",
        color: "#8a857c",
        marginBottom: 16,
      }}>{title}</div>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 10 }}>
        {items.map(([label, to]) => (
          <li key={label}>
            <Link to={to} style={{ fontSize: 14, color: "#C9C4BA" }}>{label}</Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

Object.assign(window, { useHashRoute, Link, AnnouncementBar, TopNav, Footer });
