// App chrome — the prototype's top bar: hamburger menu, wordmark, partner name
// and avatar (Agency Portal Prototype.dc.html, lines 24-53). There is no sidebar
// rail any more; navigation lives in the hamburger dropdown, which is also where
// Settings, the connection status and Sign out went.

function TopBar({ screen, onNav, liveStatus, upcomingCount }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  React.useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') setMenuOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [menuOpen]);

  const session = window.__pp_session;
  const who = (session && (session.name || session.email)) || 'Partner';
  const go = (id) => () => { setMenuOpen(false); onNav(id); };
  const items = [
    { id: 'search', label: 'Availability', icon: IconSearch, on: screen === 'results' },
    { id: 'bookings', label: 'Bookings' + (upcomingCount ? ' (' + upcomingCount + ' upcoming)' : ''), icon: IconCal, on: screen === 'bookings' },
    { id: 'apikeys', label: 'Settings', icon: IconCog, on: screen === 'apikeys' },
  ];

  return (
    <header className="pp-topbar">
      <div className="pp-topbar-left">
        <button className="pp-burger" onClick={() => setMenuOpen(o => !o)}
                aria-label="Menu" aria-expanded={menuOpen}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
            <path d="M3 6h18M3 12h18M3 18h18"/>
          </svg>
        </button>
        <div className="pp-wordmark">
          <img className="pp-wordmark-mark" src="assets/bookable-icon.png" alt="" draggable="false"/>
          <span className="pp-wordmark-name">Partner Portal</span>
          <span className="pp-wordmark-by">by Bookable</span>
        </div>
      </div>

      <div className="pp-topbar-right">
        <span className="pp-topbar-who">{who}</span>
        <span className="pp-avatar-initials" aria-hidden="true">{initialsOf(who)}</span>
      </div>

      {menuOpen && (
        <React.Fragment>
          <div className="pp-burger-scrim" onClick={() => setMenuOpen(false)}/>
          <nav className="pp-burger-menu">
            {items.map(it => (
              <button key={it.id} className={"pp-burger-item" + (it.on ? " is-on" : "")} onClick={go(it.id)}>
                <span className="pp-burger-item-icon"><it.icon size={15}/></span>
                {it.label}
              </button>
            ))}
            <div className="pp-burger-foot">
              <StatusLine liveStatus={liveStatus}/>
              <a className="pp-burger-signout" href="/api/auth/logout">Sign out</a>
            </div>
          </nav>
        </React.Fragment>
      )}
    </header>
  );
}

// Connection state. In the prototype's top bar there is nothing like this, so it
// moved into the menu footer rather than being dropped — "Disconnected" vs "no
// inventory shared" is the first thing you need when the listing looks empty.
function StatusLine({ liveStatus }) {
  if (!liveStatus) return null;
  const s = !liveStatus.ready ? { c: 'var(--pp-warn-ink)', l: 'Connecting…' }
          : liveStatus.live ? { c: 'var(--pp-mint-ink)', l: 'Live · Bookable' }
          : liveStatus.empty ? { c: 'var(--pp-warn-ink)', l: 'No inventory shared' }
          : { c: 'var(--pp-err-ink)', l: 'Disconnected' };
  return (
    <span className="pp-burger-status" title={liveStatus.error || undefined}>
      <span className="pp-status-dot" style={{ background: s.c }}/>
      {s.l}
    </span>
  );
}

function initialsOf(name) {
  const parts = String(name || '').replace(/@.*/, '').split(/[\s._-]+/).filter(Boolean);
  return (parts.slice(0, 2).map(w => w[0]).join('') || 'P').toUpperCase();
}

// Full-width strip pinned above the top bar while sandbox mode is on, so it's
// always clear the partner is looking at test data, not live bookings.
function SandboxBanner() {
  if (!(window.ppSandboxOn && window.ppSandboxOn())) return null;
  // Fallback = boot auto-switched to sandbox because the user's PRODUCTION
  // catalogue was empty (no live venues shared with them). Explain why, and what
  // unlocks production — and DON'T offer "Switch to production": there's no
  // production data, so it would just reload straight back into sandbox.
  const fallback = !!window.__pp_sandbox_fallback;
  return (
    <div className="pp-sandbox-banner" role="status">
      <span className="pp-status-dot" style={{ background: 'var(--pp-warn)' }}/>
      {fallback ? (
        <span>No live venues are shared with your account yet — showing sandbox (test) data so you can explore. To go live, a venue needs to share their inventory with you.</span>
      ) : (
        <React.Fragment>
          <span>Sandbox mode — showing test bookings and availability. Bookings you make here don’t affect live data.</span>
          <button onClick={() => window.ppSetSandbox(false)}>Switch to production</button>
        </React.Fragment>
      )}
    </div>
  );
}

// Mint-style operator chip used in tables & cards.
function OperatorTag({ id, size = 'sm' }) {
  const op = operatorById(id);
  if (!op) return null;
  return (
    <span className={"pp-op-tag pp-op-tag--" + size}>
      <IconTag size={11}/>
      <span>{op.name}</span>
    </span>
  );
}

// Subtle outline chip for product type / status.
function ProductPill({ id }) {
  const p = productById(id);
  if (!p) return null;
  const G = glyphFor(id);
  return (
    <span className="pp-prod-pill">
      {G && <G size={12}/>}
      <span>{p.name}</span>
    </span>
  );
}

function StatusDot({ status }) {
  const map = {
    confirmed: { c:'var(--pp-mint-ink)', l:'Confirmed' },
    pending:   { c:'var(--pp-warn-ink)', l:'Pending'   },
    cancelled: { c:'var(--pp-err-ink)', l:'Cancelled' },
  };
  const s = map[status] || map.confirmed;
  return (
    <span className="pp-status" style={{ color: s.c }}>
      <span className="pp-status-dot" style={{ background: s.c }}/>
      <span>{s.l}</span>
    </span>
  );
}

Object.assign(window, { TopBar, SandboxBanner, OperatorTag, ProductPill, StatusDot, initialsOf });
