/* ============================================================
   AfricaMart — Chrome: Logo, Navbar, Footer, SEO Inspector, Toast
   ============================================================ */

/* ---------- Logo ---------- */
function Logo({ light = false, size = 30 }) {
  const ink = light ? "#fff" : "var(--navy-800)";
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
      <svg width={size} height={size} viewBox="0 0 40 40" fill="none" aria-hidden="true">
        <rect width="40" height="40" rx="10" fill="var(--navy-800)" />
        <path d="M20 8 L31 30 L25.5 30 L20 18 L14.5 30 L9 30 Z" fill="var(--gold-500)" />
        <circle cx="20" cy="27.5" r="2.4" fill="var(--navy-800)" />
      </svg>
      <span style={{ fontWeight: 800, fontSize: size * 0.62, letterSpacing: "-0.03em", color: ink }}>
        Africa<span style={{ color: "var(--gold-500)" }}>Mart</span>
      </span>
    </span>
  );
}

/* ---------- Navbar ---------- */
function Navbar({ nav, route, currency, setCurrency, auth, onSignOut }) {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [acctOpen, setAcctOpen] = useState(false);
  const acctRef = useRef(null);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    const onDoc = e => { if (acctRef.current && !acctRef.current.contains(e.target)) setAcctOpen(false); };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);
  const acct = auth
    ? { name: auth.name || "Account", initials: auth.initials || "?", sub: auth.sub || "" }
    : { name: "Account", initials: "?", sub: "" };
  const links = [
    { label: "Browse", page: "browse" },
    { label: "Suppliers", page: "suppliers" },
    { label: "RFQ Board", page: "rfq" },
  ];
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 50, background: "rgba(255,255,255,.92)",
      backdropFilter: "blur(12px)", borderBottom: "1px solid " + (scrolled ? "var(--border)" : "transparent"),
      boxShadow: scrolled ? "var(--sh-sm)" : "none", transition: "box-shadow .2s, border-color .2s",
    }}>
      <div className="wrap" style={{ height: "var(--nav-h)", display: "flex", alignItems: "center", gap: 20 }}>
        <a onClick={() => nav("home")} style={{ cursor: "pointer", flexShrink: 0 }}><Logo /></a>

        <nav className="nav-links" style={{ display: "flex", gap: 4, marginLeft: 8 }}>
          {links.map(l => (
            <a key={l.page} onClick={() => nav(l.page)} style={{
              cursor: "pointer", padding: "8px 14px", borderRadius: 8, fontWeight: 600, fontSize: 14.5,
              color: route.page === l.page ? "var(--navy-800)" : "var(--ink-700)",
              background: route.page === l.page ? "var(--navy-50)" : "transparent",
            }}
              onMouseEnter={e => { if (route.page !== l.page) e.currentTarget.style.background = "var(--navy-50)"; }}
              onMouseLeave={e => { if (route.page !== l.page) e.currentTarget.style.background = "transparent"; }}>
              {l.label}
            </a>
          ))}
        </nav>

        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 10 }}>
          <select className="select cur-select" value={currency} onChange={e => setCurrency(e.target.value)}
            style={{ width: "auto", padding: "7px 10px", fontSize: 13, fontWeight: 600, borderColor: "var(--border)" }}>
            {Object.keys(AM.CURRENCIES).map(c => <option key={c} value={c}>{c}</option>)}
          </select>
          {auth ? (
            <div ref={acctRef} style={{ position: "relative" }} className="nav-acct">
              <button onClick={() => setAcctOpen(o => !o)} style={{ display: "flex", alignItems: "center", gap: 9, padding: "5px 8px 5px 5px", borderRadius: 999, border: "1px solid var(--border)", background: "#fff" }}>
                <span style={{ width: 30, height: 30, borderRadius: "50%", background: "var(--navy-800)", color: "var(--gold-400)", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 12 }}>{acct.initials}</span>
                <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink-900)" }}>{acct.name.split(" ")[0]}</span>
                <Icon name="chevron-down" size={15} style={{ color: "var(--ink-400)" }} />
              </button>
              {acctOpen && (
                <div className="route-anim" style={{ position: "absolute", right: 0, top: "calc(100% + 8px)", width: 232, background: "#fff", border: "1px solid var(--border)", borderRadius: 12, boxShadow: "var(--sh-lg)", overflow: "hidden", zIndex: 60 }}>
                  <div style={{ padding: "13px 16px", borderBottom: "1px solid var(--border)" }}>
                    <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink-900)" }}>{acct.name}</div>
                    <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{acct.sub}</div>
                  </div>
                  {[["layout-grid", "Dashboard", () => { nav("dashboard", { role: auth?.role }); setAcctOpen(false); }], ["user", "Profile settings", () => { nav("dashboard", { role: auth?.role }); setAcctOpen(false); }]].map(([ic, lbl, fn]) => (
                    <button key={lbl} onClick={fn} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "11px 16px", fontSize: 13.5, fontWeight: 500, color: "var(--ink-700)", textAlign: "left" }}
                      onMouseEnter={e => e.currentTarget.style.background = "var(--navy-50)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                      <Icon name={ic} size={16} style={{ color: "var(--ink-400)" }} /> {lbl}
                    </button>
                  ))}
                  <button onClick={() => { onSignOut && onSignOut(); setAcctOpen(false); }} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "11px 16px", fontSize: 13.5, fontWeight: 500, color: "var(--danger-700)", textAlign: "left", borderTop: "1px solid var(--border)" }}
                    onMouseEnter={e => e.currentTarget.style.background = "var(--danger-50)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                    <Icon name="log-out" size={16} /> Sign out
                  </button>
                </div>
              )}
            </div>
          ) : (
            <>
              <a className="btn btn-ghost btn-sm nav-login" onClick={() => nav("auth", { mode: "login" })} style={{ cursor: "pointer" }}>Login</a>
              <a className="btn btn-gold btn-sm" onClick={() => nav("auth", { mode: "register" })} style={{ cursor: "pointer" }}>Register</a>
            </>
          )}
          <button className="mobile-toggle" onClick={() => setMobileOpen(o => !o)} style={{ display: "none", padding: 6 }}>
            <Icon name={mobileOpen ? "x" : "menu"} size={24} />
          </button>
        </div>
      </div>

      {mobileOpen && (
        <div className="mobile-menu" style={{ borderTop: "1px solid var(--border)", padding: "8px 16px 16px", background: "#fff" }}>
          {links.map(l => (
            <a key={l.page} onClick={() => { nav(l.page); setMobileOpen(false); }}
              style={{ display: "block", padding: "12px 8px", fontWeight: 600, borderBottom: "1px solid var(--border)", cursor: "pointer" }}>
              {l.label}
            </a>
          ))}
          {auth ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 14 }}>
              <a className="btn btn-navy btn-block" onClick={() => { nav("dashboard", { role: auth }); setMobileOpen(false); }}>Go to dashboard</a>
              <a className="btn btn-ghost btn-block" onClick={() => { onSignOut && onSignOut(); setMobileOpen(false); }}>Sign out</a>
            </div>
          ) : (
            <div style={{ display: "flex", gap: 10, marginTop: 14 }}>
              <a className="btn btn-ghost btn-block" onClick={() => { nav("auth", { mode: "login" }); setMobileOpen(false); }}>Login</a>
              <a className="btn btn-gold btn-block" onClick={() => { nav("auth", { mode: "register" }); setMobileOpen(false); }}>Register</a>
            </div>
          )}
        </div>
      )}
    </header>
  );
}

/* ---------- Footer ---------- */
function Footer({ nav }) {
  const cols = [
    { h: "Categories", links: AM.CATEGORIES.slice(0, 6).map(c => ({ label: c.name, action: () => nav("browse", { cat: c.id }) })) },
    { h: "Countries", links: AM.COUNTRIES.slice(0, 6).map(c => ({ label: c.name, action: () => nav("browse", { country: c.code }) })) },
    { h: "Platform", links: [
      { label: "Browse products", action: () => nav("browse") },
      { label: "Find suppliers", action: () => nav("suppliers") },
      { label: "Post an RFQ", action: () => nav("rfq") },
      { label: "Become a supplier", action: () => nav("auth", { mode: "register", role: "supplier" }) },
      { label: "Buyer dashboard", action: () => nav("dashboard", { role: "buyer" }) },
    ] },
    { h: "Company", links: [
      { label: "About AfricaMart", action: () => {} },
      { label: "Trust & safety", action: () => {} },
      { label: "Trade assurance", action: () => {} },
      { label: "Help center", action: () => {} },
      { label: "Contact", action: () => {} },
    ] },
  ];
  return (
    <footer style={{ background: "var(--navy-800)", color: "#fff", marginTop: 0 }}>
      <div className="wrap" style={{ padding: "56px 24px 32px" }}>
        <div className="footer-grid" style={{ display: "grid", gridTemplateColumns: "1.5fr repeat(4, 1fr)", gap: 32 }}>
          <div>
            <Logo light />
            <p style={{ color: "var(--navy-200)", fontSize: 14, marginTop: 14, maxWidth: 260, lineHeight: 1.6 }}>
              The pan-African B2B marketplace connecting verified suppliers and buyers across all 54 countries.
            </p>
            <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
              {["linkedin", "twitter", "facebook", "instagram"].map(s => (
                <span key={s} style={{ width: 36, height: 36, borderRadius: 8, background: "rgba(255,255,255,.08)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}
                  title={s}>
                  <span style={{ color: "var(--navy-200)", fontWeight: 700, fontSize: 13, textTransform: "capitalize" }}>{s[0].toUpperCase()}</span>
                </span>
              ))}
            </div>
          </div>
          {cols.map(col => (
            <div key={col.h}>
              <div style={{ fontWeight: 700, fontSize: 13, letterSpacing: ".06em", textTransform: "uppercase", color: "var(--gold-400)", marginBottom: 14 }}>{col.h}</div>
              <ul style={{ display: "flex", flexDirection: "column", gap: 9 }}>
                {col.links.map(l => (
                  <li key={l.label}><a onClick={l.action} style={{ cursor: "pointer", color: "var(--navy-200)", fontSize: 13.5 }}
                    onMouseEnter={e => e.currentTarget.style.color = "#fff"} onMouseLeave={e => e.currentTarget.style.color = "var(--navy-200)"}>{l.label}</a></li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ borderTop: "1px solid rgba(255,255,255,.1)", marginTop: 40, paddingTop: 22, display: "flex", flexWrap: "wrap", gap: 12, justifyContent: "space-between", color: "var(--navy-300)", fontSize: 13 }}>
          <span>© 2026 AfricaMart Ltd. All rights reserved.</span>
          <div style={{ display: "flex", gap: 20 }}>
            <a style={{ cursor: "pointer" }}>Privacy</a><a style={{ cursor: "pointer" }}>Terms</a>
            <a style={{ cursor: "pointer" }}>Sitemap</a><a style={{ cursor: "pointer" }}>robots.txt</a>
            <a href="admin/Admin.html" style={{ cursor: "pointer" }}>Admin</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ---------- SEO Inspector (demonstrates SEO build) ---------- */
function SEOInspector({ seo }) {
  const [open, setOpen] = useState(false);
  return (
    <>
      <button onClick={() => setOpen(o => !o)} title="Inspect page SEO" style={{
        position: "fixed", right: 18, bottom: 18, zIndex: 60, width: 48, height: 48, borderRadius: "50%",
        background: "var(--navy-800)", color: "var(--gold-400)", boxShadow: "var(--sh-lg)",
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <Icon name={open ? "x" : "search-code"} size={22} />
      </button>
      {open && (
        <div className="route-anim" style={{
          position: "fixed", right: 18, bottom: 78, zIndex: 60, width: "min(420px, calc(100vw - 36px))",
          maxHeight: "70vh", overflow: "auto", background: "#fff", borderRadius: 14, boxShadow: "var(--sh-lg)",
          border: "1px solid var(--border)",
        }} className="thin-scroll">
          <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 8, position: "sticky", top: 0, background: "#fff" }}>
            <Icon name="search-code" size={18} style={{ color: "var(--gold-600)" }} />
            <b style={{ fontSize: 14 }}>SEO inspector</b>
            <span className="badge badge-green" style={{ marginLeft: "auto" }}><Icon name="check" size={11} /> Indexable</span>
          </div>
          <div style={{ padding: 18, display: "flex", flexDirection: "column", gap: 16, fontSize: 12.5 }}>
            <SeoRow label="URL slug"><code className="mono">{seo.url}</code></SeoRow>
            <SeoRow label="Meta title">{seo.title}</SeoRow>
            <SeoRow label="Meta description">{seo.description}</SeoRow>
            <SeoRow label="Canonical"><code className="mono">https://africamart.com{seo.url}</code></SeoRow>
            <SeoRow label="Open Graph">
              <div className="mono" style={{ fontSize: 11.5, color: "var(--ink-500)", lineHeight: 1.7 }}>
                og:title · og:description · og:image<br/>og:type = {seo.ogType || "website"} · twitter:card = summary_large_image
              </div>
            </SeoRow>
            {seo.jsonld && (
              <SeoRow label={"JSON-LD schema (" + seo.jsonld["@type"] + ")"}>
                <pre className="mono" style={{ margin: 0, fontSize: 11, background: "var(--navy-50)", padding: 12, borderRadius: 8, overflow: "auto", lineHeight: 1.5, maxHeight: 220 }}>{JSON.stringify(seo.jsonld, null, 2)}</pre>
              </SeoRow>
            )}
          </div>
        </div>
      )}
    </>
  );
}
function SeoRow({ label, children }) {
  return (
    <div>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase", color: "var(--ink-400)", marginBottom: 5 }}>{label}</div>
      <div style={{ color: "var(--ink-900)", wordBreak: "break-word" }}>{children}</div>
    </div>
  );
}

/* ---------- Toast ---------- */
function useToast() {
  const [toast, setToast] = useState(null);
  const show = (msg, icon = "check-circle") => {
    setToast({ msg, icon });
    setTimeout(() => setToast(null), 2800);
  };
  const node = toast ? (
    <div className="route-anim" style={{
      position: "fixed", bottom: 24, left: "50%", transform: "translateX(-50%)", zIndex: 70,
      background: "var(--navy-800)", color: "#fff", padding: "13px 20px", borderRadius: 10,
      boxShadow: "var(--sh-lg)", display: "flex", alignItems: "center", gap: 10, fontSize: 14, fontWeight: 500,
    }}>
      <Icon name={toast.icon} size={18} style={{ color: "var(--gold-400)" }} /> {toast.msg}
    </div>
  ) : null;
  return [node, show];
}

Object.assign(window, { Logo, Navbar, Footer, SEOInspector, useToast });
