/* global React, Icon, Avatar */
// ============================================================
// Sidebar & Topbar
// ============================================================

var { useState, useEffect, useRef } = React;

const NAV = [
{
  label: "Overview",
  items: [
  { id: "dashboard", label: "Dashboard", icon: "Dashboard" },
  { id: "sales", label: "Sales Manager", icon: "Trend" },
  { id: "rebooking", label: "Rebooking Tool", icon: "Refresh" }]

},
{
  label: "Operations",
  items: [
  // badge resolved at render-time in Sidebar via window.TrekkoAPI.getBookings()
  { id: "bookings", label: "Bookings", icon: "Bookings", badgeFromBookings: true },
  { id: "payments", label: "Payment Management", icon: "Payment" }]

},
{
  label: "Network",
  items: [
  { id: "agencies", label: "Travel Agencies", icon: "Building" },
  { id: "travelGroups", label: "Travel Groups", icon: "Tag" },
  { id: "vendors", label: "Vendors", icon: "Vendor" },
  { id: "mapping", label: "Hotel Mapping", icon: "Pin" },
  { id: "markups", label: "Markups", icon: "Tag" }]

},
{
  label: "Configuration",
  items: [
  { id: "users", label: "Sub Users & Roles", icon: "Users" },
  { id: "homepage", label: "Homepage & SEO", icon: "Globe" },
  { id: "settings", label: "Settings", icon: "Settings" }]

}];


function Sidebar({ active, onNav }) {
  // Fetch the live booking count once on mount + listen for the same
  // event PageBookings dispatches when it finishes its own fetch (so we
  // don't double-call the endpoint and stress the DB pool).
  const [bookingCount, setBookingCount] = useState(null);
  useEffect(() => {
    if (!window.TrekkoAPI) return;
    let alive = true;
    window.TrekkoAPI.getBookings().then((rows) => {
      if (!alive) return;
      if (rows && rows.backendTotal != null) setBookingCount(rows.backendTotal);
      else if (rows && rows.length) setBookingCount(rows.length);
    }).catch(() => {});
    // Listen for updates from any other page that re-fetched bookings.
    const h = (e) => { if (e.detail && typeof e.detail.total === "number") setBookingCount(e.detail.total); };
    window.addEventListener("trekko:bookingsCount", h);
    return () => { alive = false; window.removeEventListener("trekko:bookingsCount", h); };
  }, []);
  return (
    <aside className="side">
      <div className="side__brand" data-comment-anchor="cf31944594-div-46-7">
        <div className="side__brand-mark">T</div>
        <div className="side__brand-name">Trekko</div>
        <div className="side__brand-env">Admin</div>
      </div>
      <nav className="side__nav">
        {NAV.map((group) =>
        <div className="side__group" key={group.label}>
            <div className="side__group-label">{group.label}</div>
            {group.items.map((it) => {
            const IcCmp = Icon[it.icon] || Icon.Home;
            const badge = it.badgeFromBookings ? (bookingCount != null ? bookingCount : "") : it.badge;
            return (
              <button
                key={it.id}
                className={`side__item${active === it.id ? " side__item--active" : ""}`}
                onClick={() => onNav(it.id)}>

                  <IcCmp />
                  <span>{it.label}</span>
                  {badge !== "" && badge != null && <span className="side__item-badge">{badge}</span>}
                </button>);

          })}
          </div>
        )}
      </nav>
      <div className="side__foot">
        <Avatar name="Nabil Demo" />
        <div className="side__who">
          <div className="side__who-name">Nabil Demo</div>
          <div className="side__who-role">Super Administrator</div>
        </div>
        <button className="top__icon" title="Sign out" style={{ width: 28, height: 28 }}>
          <Icon.Logout />
        </button>
      </div>
    </aside>);

}

// ============================================================
// Topbar
// ============================================================
function Topbar({ crumbs = [], onNav }) {
  const [notifOpen, setNotifOpen] = useState(false);
  const notifRef = useRef(null);
  useEffect(() => {
    const onClick = (e) => {
      if (notifRef.current && !notifRef.current.contains(e.target)) setNotifOpen(false);
    };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);
  return (
    <header className="top">
      <div className="top__crumbs">
        <a href="#" onClick={(e) => {e.preventDefault();onNav && onNav("dashboard");}}>
          <Icon.Home size={14} style={{ verticalAlign: "-2px" }} />
        </a>
        {crumbs.map((c, i) =>
        <React.Fragment key={i}>
            <span className="sep"><Icon.ChevronRight size={12} /></span>
            {i === crumbs.length - 1 ?
          <span className="now">{c.label}</span> :
          <a href="#" onClick={(e) => {e.preventDefault();c.to && onNav && onNav(c.to);}}>{c.label}</a>}
          </React.Fragment>
        )}
      </div>
      <div className="top__search">
        <Icon.Search size={14} />
        <input placeholder="Search bookings, agencies, vendors…" />
        <span className="top__kbd">⌘K</span>
      </div>
      <div className="top__icons" ref={notifRef} style={{ position: "relative" }}>
        <button className="top__icon" title="Help"><Icon.Help /></button>
        <button className="top__icon" title="Notifications" onClick={() => setNotifOpen((v) => !v)}>
          <Icon.Bell />
          <span className="dot" />
        </button>
        {notifOpen &&
        <div className="notif">
            <div className="notif__head">
              <div className="notif__title">Notifications</div>
              <button className="btn btn--ghost btn--sm" style={{ marginLeft: "auto" }}>Mark all read</button>
            </div>
            <div className="notif__list">
              {window.MOCK.NOTIFICATIONS.map((n) =>
            <div key={n.id} className={`notif__item${n.unread ? "" : " notif__item--read"}`}>
                  <span className="notif__dot" />
                  <div className="notif__body">
                    <div>{n.body}</div>
                    <div className="notif__time">{n.time}</div>
                  </div>
                </div>
            )}
            </div>
          </div>
        }
      </div>
    </header>);

}

Object.assign(window, { Sidebar, Topbar });