// App shell — left sidebar rail + top bar + page chrome.

function Sidebar({ route, onNav, expanded, onToggle }) {
  const items = [
    { id: 'search',   label: 'Search',   icon: IconSearch },
    { id: 'bookings', label: 'Bookings', icon: IconCal },
  ];
  return (
    <aside className={"pp-sidebar" + (expanded ? " is-expanded" : "")}>
      <div className="pp-sidebar-top">
        {expanded ? (
          <div className="pp-sidebar-brand" aria-label="Bookable">
            <img className="pp-sidebar-brand-mark" src="assets/bookable-icon.png" alt="" draggable="false"/>
            <span className="pp-sidebar-brand-text">bookable</span>
          </div>
        ) : (
          <div className="pp-sidebar-mark" aria-label="Bookable">
            <img src="assets/bookable-icon.png" alt="Bookable" draggable="false"/>
          </div>
        )}
      </div>
      <nav className="pp-sidebar-nav">
        {items.map(it => {
          const Ico = it.icon;
          const active = (route.screen === it.id) || (it.id === 'search' && route.screen === 'results') || (it.id === 'bookings' && route.screen === 'bookings');
          return (
            <button key={it.id}
                    className={"pp-rail-btn" + (active ? " is-active" : "")}
                    onClick={() => onNav(it.id)}
                    title={!expanded ? it.label : undefined}
                    aria-label={it.label}>
              <Ico size={18}/>
              {expanded && <span className="pp-rail-btn-label">{it.label}</span>}
            </button>
          );
        })}
      </nav>
      <div className="pp-sidebar-bot">
        <button className={"pp-rail-btn" + (route.screen === 'apikeys' ? " is-active" : "")}
                onClick={() => onNav('apikeys')}
                title={!expanded ? 'API Keys' : undefined} aria-label="API Keys">
          <IconCog size={18}/>
          {expanded && <span className="pp-rail-btn-label">API Keys</span>}
        </button>
        <button className="pp-rail-collapse" onClick={onToggle}
                title={expanded ? 'Collapse' : 'Expand'}
                aria-label={expanded ? 'Collapse sidebar' : 'Expand sidebar'}
                aria-expanded={expanded}>
          <span className={"pp-rail-collapse-chev" + (expanded ? " is-flipped" : "")}>
            <IconChevron size={14}/>
          </span>
        </button>
      </div>
    </aside>
  );
}

function TopBar({ crumbs, liveStatus }) {
  return (
    <header className="pp-topbar">
      <div className="pp-crumbs">
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <span className="pp-crumb-sep"><IconChevron size={12}/></span>}
            <span className={"pp-crumb" + (i === crumbs.length - 1 ? " is-last" : "")}>
              {c.icon ? <c.icon size={14}/> : null}
              <span>{c.label}</span>
            </span>
          </React.Fragment>
        ))}
      </div>
      <div className="pp-topbar-right">
        {liveStatus && liveStatus.ready && liveStatus.live && (
          <span className="pp-status" title="Connected to Bookable production API">
            <span className="pp-status-dot" style={{ background: '#1f8a5b' }}/>
            <span style={{ fontSize: 12 }}>Live · Bookable</span>
          </span>
        )}
        {liveStatus && liveStatus.ready && !liveStatus.live && (
          <span className="pp-status" title={liveStatus.error || 'Could not reach the Bookable API'}>
            <span className="pp-status-dot" style={{ background: '#c14a3a' }}/>
            <span style={{ fontSize: 12 }}>Disconnected</span>
          </span>
        )}
        {liveStatus && !liveStatus.ready && (
          <span className="pp-status" title="Loading catalogue from Bookable…">
            <span className="pp-status-dot" style={{ background: '#c89b1a' }}/>
            <span style={{ fontSize: 12 }}>Connecting…</span>
          </span>
        )}
        <SessionChip/>
      </div>
    </header>
  );
}

// Topbar identity: shows the signed-in partner + operator count and a sign-out
// link. Falls back to the generic chip when auth is disabled (no session).
function SessionChip() {
  const s = window.__pp_session;
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);

  if (!s) {
    return (
      <button className="pp-pill-btn">
        <IconUser size={14}/>
        <span>PARTNER</span>
        <IconChevronDn size={14}/>
      </button>
    );
  }
  const name = s.name || s.email || 'Partner';
  return (
    <div className="pp-dd-wrap" ref={ref}>
      <button className={"pp-pill-btn pp-pill-btn--sm" + (open ? " is-open" : "")}
              title={s.email || ''} onClick={() => setOpen(o => !o)}>
        <IconUser size={14}/>
        <span>{name}</span>
        <IconChevronDn size={14}/>
      </button>
      {open && (
        <div className="pp-dd-menu pp-dd-menu--right" role="menu" style={{ minWidth: 160 }}>
          <a className="pp-dd-item" role="menuitem" href="/api/auth/logout"
             style={{ display: 'block', textDecoration: 'none' }}>Sign out</a>
        </div>
      )}
    </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 = PRODUCT_GLYPHS[id];
  return (
    <span className="pp-prod-pill">
      {G && <G size={12}/>}
      <span>{p.name}</span>
    </span>
  );
}

function StatusDot({ status }) {
  const map = {
    confirmed: { c:'#1f8a5b', l:'Confirmed' },
    pending:   { c:'#c98a1d', l:'Pending'   },
    cancelled: { c:'#b04a4a', 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, { Sidebar, TopBar, OperatorTag, ProductPill, StatusDot });
