// topbar.jsx — shared responsive topbar for all RBI dashboard pages.
// Exposes window.RBITopbar.
//
// Props:
//   business    — { name, owner, bank }
//   activeView  — "home" | "creditscore" | "cashflow" | "insights"
//   onMobile    — optional, called when mobile-preview btn clicked (home only)
//   onTweaks    — called when mock-controls btn clicked
//
// On ≤980px the desktop nav and labels collapse.
// A hamburger opens a slide-in drawer with the full nav + account info.

(function () {
  const { useState, useEffect, useRef } = React;

  const NAV_ITEMS = [
    { view: "home", label: "Overview" },
    { view: "creditscore", label: "Business Credit" },
    { view: "insights", label: "Industry insights" },
  ];

  // ── Hamburger icon SVG ─────────────────────────────────────────
  function HamburgerIcon() {
    return (
      <svg width="16" height="14" viewBox="0 0 16 14" fill="none" aria-hidden="true">
        <rect y="0" width="16" height="2" rx="1" fill="currentColor" />
        <rect y="6" width="16" height="2" rx="1" fill="currentColor" />
        <rect y="12" width="16" height="2" rx="1" fill="currentColor" />
      </svg>
    );
  }

  // ── Mobile drawer ──────────────────────────────────────────────
  function MobileDrawer({ open, onClose, business, activeView, onTweaks }) {
    const drawerRef = useRef(null);
    const initials = business.owner.split(" ").map(w => w[0]).join("");

    // Close on Escape
    useEffect(() => {
      if (!open) return;
      const onKey = (e) => { if (e.key === "Escape") onClose(); };
      window.addEventListener("keydown", onKey);
      document.body.style.overflow = "hidden";
      return () => {
        window.removeEventListener("keydown", onKey);
        document.body.style.overflow = "";
      };
    }, [open, onClose]);

    // Focus trap — move focus into drawer when it opens
    useEffect(() => {
      if (open && drawerRef.current) {
        const first = drawerRef.current.querySelector("button, a, [tabindex]");
        if (first) first.focus();
      }
    }, [open]);

    function nav(view) {
      onClose();
      if (view) window.RBI_NAV(view);
    }

    return (
      <div
        className={"rbi-mobile-nav" + (open ? " open" : "")}
        role="dialog"
        aria-modal="true"
        aria-label="Navigation menu"
      >
        <div className="rbi-mobile-nav-scrim" onClick={onClose} />
        <div className="rbi-mobile-nav-drawer" ref={drawerRef}>

          {/* Header row */}
          <div className="rbi-mobile-nav-head">
            <img
              src="design-system/logos/Revenued_Digital_logo.svg"
              alt="Revenued"
              style={{ height: 20, display: "block" }}
            />
            <button
              className="rbi-mobile-nav-close"
              onClick={onClose}
              aria-label="Close navigation"
            >×</button>
          </div>

          {/* Account */}
          <div className="rbi-mobile-nav-acct">
            <div className="rbi-avatar">{initials}</div>
            <div className="rbi-mobile-nav-acct-info">
              <div className="rbi-mobile-nav-acct-name">{business.owner}</div>
              <div className="rbi-mobile-nav-acct-role">
                Owner
                {business.dunsLoading ? (
                  <React.Fragment>
                    {" · "}
                    <span className="cs-skel cs-skel-line"
                      style={{ display: "inline-block", width: 92, verticalAlign: "middle" }} />
                  </React.Fragment>
                ) : business.duns ? (
                  " · DUNS " + business.duns
                ) : business.bank ? (
                  " · " + business.bank.split(" ····")[0]
                ) : null}
              </div>
            </div>
          </div>

          {/* Nav links */}
          <div className="rbi-mobile-nav-links" role="navigation">
            {NAV_ITEMS.map((item, i) => (
              <button
                key={i}
                className={
                  "rbi-mobile-nav-link" +
                  (item.muted ? " muted" : "") +
                  (!item.muted && item.view === activeView ? " active" : "")
                }
                onClick={() => !item.muted && nav(item.view)}
                tabIndex={item.muted ? -1 : 0}
              >
                {item.label}
              </button>
            ))}
          </div>

          <div className="rbi-mobile-nav-divider" />

          {/* Footer actions */}
          <div className="rbi-mobile-nav-footer">
            {/* <button
              className="rbi-btn rbi-btn-ghost"
              style={{ width: "100%", justifyContent: "center", display: "flex", gap: 8, alignItems: "center", fontSize: 13 }}
              onClick={() => { onClose(); if (onTweaks) onTweaks(); }}
            >
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <line x1="4" y1="21" x2="4" y2="14" /><line x1="4" y1="10" x2="4" y2="3" />
                <line x1="12" y1="21" x2="12" y2="12" /><line x1="12" y1="8" x2="12" y2="3" />
                <line x1="20" y1="21" x2="20" y2="16" /><line x1="20" y1="12" x2="20" y2="3" />
                <line x1="1" y1="14" x2="7" y2="14" /><line x1="9" y1="8" x2="15" y2="8" />
                <line x1="17" y1="16" x2="23" y2="16" />
              </svg>
              Mock controls
            </button> */}
            <button
              className="rbi-btn rbi-btn-ghost"
              style={{ width: "100%", justifyContent: "center", display: "flex", fontSize: 13 }}
              onClick={() => window.RBI_SIGNOUT()}
            >
              Sign out
            </button>
          </div>
        </div>
      </div>
    );
  }

  // ── Main topbar ────────────────────────────────────────────────
  function RBITopbar({ business, activeView, onMobile, onTweaks }) {
    const [drawerOpen, setDrawerOpen] = useState(false);
    const initials = business.owner.split(" ").map(w => w[0]).join("");

    return (
      <>
        <div className="rbi-topbar">
          {/* Left: logo + product label */}
          <div className="rbi-topbar-left">
            <div className="rbi-topbar-logo">
              <a
                href="index.html"
                onClick={(e) => { e.preventDefault(); window.RBI_NAV("home"); }}
              >
                <img src="design-system/logos/Revenued_Digital_logo.svg" alt="Revenued" />
              </a>
            </div>
            <div className="rbi-topbar-divider" />
            <div className="rbi-topbar-product">
              <span>Business Intelligence</span>
              <b title={business.name}>{business.name}</b>
            </div>
          </div>

          {/* Centre: desktop nav */}
          <nav className="cf-topnav" aria-label="Main navigation">
            {NAV_ITEMS.map((item, i) => (
              <a
                key={i}
                className={
                  "cf-topnav-link" +
                  (item.muted ? " cf-topnav-mute" : "") +
                  (!item.muted && item.view === activeView ? " cf-topnav-active" : "")
                }
                href={item.view ? "#" : undefined}
                onClick={item.view && !item.muted
                  ? (e) => { e.preventDefault(); window.RBI_NAV(item.view); }
                  : (e) => e.preventDefault()
                }
              >
                {item.label}
              </a>
            ))}
          </nav>

          {/* Right: actions + account */}
          <div className="rbi-topbar-right">
            {onMobile && (
              <button
                className="rbi-topbar-help rbi-topbar-mobile-btn"
                onClick={onMobile}
                title="Preview on mobile"
              >
                <svg width="12" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="5" y="2" width="14" height="20" rx="2" />
                </svg>
                Mobile
              </button>
            )}
            {/* <button
              className="rbi-topbar-tweaks-btn"
              onClick={onTweaks}
              title="Switch states & layout variants"
            >
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <line x1="4" y1="21" x2="4" y2="14" /><line x1="4" y1="10" x2="4" y2="3" />
                <line x1="12" y1="21" x2="12" y2="12" /><line x1="12" y1="8" x2="12" y2="3" />
                <line x1="20" y1="21" x2="20" y2="16" /><line x1="20" y1="12" x2="20" y2="3" />
                <line x1="1" y1="14" x2="7" y2="14" /><line x1="9" y1="8" x2="15" y2="8" />
                <line x1="17" y1="16" x2="23" y2="16" />
              </svg>
              <span>Mock controls</span>
            </button> */}
            <button
              className="rbi-btn rbi-btn-ghost"
              style={{ width: "100%", justifyContent: "center", display: "flex", fontSize: 13 }}
              onClick={() => window.RBI_SIGNOUT()}
            >
              Sign out
            </button>
            {/* <span className="rbi-topbar-help">Help</span> */}
            <div className="rbi-topbar-acct">
              <div style={{ textAlign: "right" }}>
                <div className="rbi-topbar-acct-name">{business.owner}</div>
                <div className="rbi-topbar-acct-role">{business.city}</div>
              </div>
              <div className="rbi-avatar">{initials}</div>
            </div>
            {/* Hamburger — visible ≤980px */}
            <button
              className="rbi-topbar-hamburger"
              onClick={() => setDrawerOpen(true)}
              aria-label="Open navigation menu"
              aria-expanded={drawerOpen}
            >
              <HamburgerIcon />
            </button>
          </div>
        </div>

        <MobileDrawer
          open={drawerOpen}
          onClose={() => setDrawerOpen(false)}
          business={business}
          activeView={activeView}
          onTweaks={onTweaks}
        />
      </>
    );
  }

  window.RBITopbar = RBITopbar;
})();