// App chrome — sidebar, top bar, persona switcher, search, notifications.

const NAV = [
  { id: 'home',        label: 'Home',         icon: 'home' },
  { id: 'portfolio',   label: 'Portfolio',    icon: 'portfolio' },  { id: 'initiatives', label: 'Initiatives',  icon: 'initiatives' },
  { id: 'projects',    label: 'Projects',     icon: 'projects' },
  { id: 'ideas',       label: 'Ideas',        icon: 'ideas' },
  { id: 'components',  label: 'Components',   icon: 'components' },
  { id: 'tickets',     label: 'Tickets',      icon: 'tickets' },
  { id: 'messages',    label: 'Messages',     icon: 'bell' },
  { id: 'help',        label: 'Help Board',   icon: 'help' },
  { id: 'admin',       label: 'Admin',        icon: 'admin' },
];

// ── Sidebar ──────────────────────────────────────────────────────────
const Sidebar = ({ route, onNavigate, persona, counts = {} }) => {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const menuRef = React.useRef(null);
  
  React.useEffect(() => {
    if (!menuOpen) return;
    const handleClick = (e) => {
      if (menuRef.current && !menuRef.current.contains(e.target)) {
        setMenuOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [menuOpen]);

  return (
    <aside style={{
      width: 232, flexShrink: 0,
      background: 'var(--apm-bg-2)',
      borderRight: '1px solid var(--apm-line)',
      display: 'flex', flexDirection: 'column',
      height: '100vh', position: 'sticky', top: 0,
    }}>
      {/* logo */}
      <div style={{ padding: '26px 18px', borderBottom: '1px solid var(--apm-line)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 30, height: 30, borderRadius: 8,
            background: 'var(--apm-ink)', color: 'var(--apm-bg-2)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--apm-font-display)', fontSize: 18, fontWeight: 600,
            letterSpacing: '-0.02em',
          }}>ai</div>
          <div>
            <div style={{ fontFamily: 'var(--apm-font-display)', fontSize: 17, lineHeight: 1, letterSpacing: '-0.01em' }}>portfolio manager</div>
            <div style={{ fontSize: 10.5, color: 'var(--apm-muted)', textTransform: 'uppercase', letterSpacing: '0.16em', marginTop: 3 }}>Earlens · APM</div>
          </div>
        </div>
      </div>

      {/* nav */}
      <nav style={{ flex: 1, padding: '12px 10px', display: 'flex', flexDirection: 'column', gap: 1, overflowY: 'auto' }}>
        {NAV.map(item => {
          const active = route.page === item.id;
          const c = counts[item.id];
          return (
            <button key={item.id} onClick={() => onNavigate(item.id)} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '8px 10px', borderRadius: 6,
              background: active ? 'var(--apm-bg-sunken)' : 'transparent',
              color: active ? 'var(--apm-ink)' : 'var(--apm-ink-2)',
              border: 'none', textAlign: 'left',
              fontFamily: 'var(--apm-font-body)', fontSize: 13.5,
              fontWeight: active ? 600 : 500,
              cursor: 'pointer', position: 'relative',
            }}
              onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--apm-bg-sunken)'; }}
              onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
              {active && <div style={{ position: 'absolute', left: 0, top: 6, bottom: 6, width: 2, background: 'var(--apm-accent)', borderRadius: 2 }} />}
              <Icon name={item.icon} size={16} style={{ color: active ? 'var(--apm-accent)' : 'var(--apm-muted)' }} />
              <span style={{ flex: 1 }}>{item.label}</span>
              {c != null && c > 0 && (
                <span style={{
                  fontSize: 11, color: 'var(--apm-muted)',
                  background: active ? 'var(--apm-card)' : 'transparent',
                  padding: '1px 6px', borderRadius: 999, minWidth: 20, textAlign: 'center',
                }}>{c}</span>
              )}
            </button>
          );
        })}
      </nav>

      {/* persona footer */}
      <div ref={menuRef} style={{ padding: 12, borderTop: '1px solid var(--apm-line)', position: 'relative' }}>
        {menuOpen && (
          <div style={{
            position: 'absolute',
            bottom: '100%',
            left: 12,
            right: 12,
            marginBottom: 4,
            background: 'var(--apm-card)',
            border: '1px solid var(--apm-line)',
            borderRadius: 'var(--apm-radius-lg)',
            boxShadow: 'var(--apm-shadow-lg)',
            padding: 4,
            zIndex: 1000,
          }}>
            <button onClick={() => { setMenuOpen(false); onNavigate('profile'); }} style={{
              width: '100%',
              padding: '8px 12px',
              background: 'transparent',
              border: 'none',
              borderRadius: 'var(--apm-radius)',
              textAlign: 'left',
              cursor: 'pointer',
              fontSize: 13,
              color: 'var(--apm-ink)',
              display: 'flex',
              alignItems: 'center',
              gap: 8,
            }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--apm-bg-sunken)'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <Icon name="user" size={14} style={{ color: 'var(--apm-muted)' }} />
              Profile
            </button>
            <div style={{ height: 1, background: 'var(--apm-line)', margin: '4px 0' }} />
            <button onClick={() => { setMenuOpen(false); alert('Signed out'); }} style={{
              width: '100%',
              padding: '8px 12px',
              background: 'transparent',
              border: 'none',
              borderRadius: 'var(--apm-radius)',
              textAlign: 'left',
              cursor: 'pointer',
              fontSize: 13,
              color: 'var(--apm-ink)',
              display: 'flex',
              alignItems: 'center',
              gap: 8,
            }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--apm-bg-sunken)'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <Icon name="logout" size={14} style={{ color: 'var(--apm-muted)' }} />
              Sign out
            </button>
          </div>
        )}
        <button onClick={() => onNavigate('profile')} style={{
          display: 'flex', alignItems: 'center', gap: 12, width: '100%',
          padding: 8, borderRadius: 8,
          background: 'transparent', border: '1px solid var(--apm-line)',
          textAlign: 'left', cursor: 'pointer',
        }}>
          <Avatar person={persona} size={32} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, lineHeight: 1.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{persona.name}</div>
            <div style={{ fontSize: 11, color: 'var(--apm-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{APM_ROLES[persona.role].label}</div>
          </div>
          <div onClick={(e) => { e.stopPropagation(); setMenuOpen(!menuOpen); }} style={{ padding: 4, cursor: 'pointer' }}>
            <Icon name="chevron_down" size={14} style={{ color: 'var(--apm-muted)' }} />
          </div>
        </button>
      </div>
    </aside>
  );
};

// ── Top bar ──────────────────────────────────────────────────────────
const TopBar = ({ breadcrumbs = [], onSearch, onChat, onNew, onMessages, onProfile, persona, msgCount = 0 }) => {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 24px', borderBottom: '1px solid var(--apm-line)',
      background: 'var(--apm-bg-2)',
      position: 'sticky', top: 0, zIndex: 10,
    }}>
      {/* breadcrumbs */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flex: 1, minWidth: 0 }}>
        {breadcrumbs.map((b, i) => (
          <React.Fragment key={i}>
            {i > 0 && <Icon name="chevron_right" size={12} style={{ color: 'var(--apm-muted-2)' }} />}
            <button onClick={b.onClick} style={{
              border: 'none', background: 'transparent',
              padding: 0, cursor: b.onClick ? 'pointer' : 'default',
              fontFamily: 'var(--apm-font-body)', fontSize: 13,
              color: i === breadcrumbs.length - 1 ? 'var(--apm-ink)' : 'var(--apm-muted)',
              fontWeight: i === breadcrumbs.length - 1 ? 600 : 400,
              whiteSpace: 'nowrap',
            }}>{b.label}</button>
          </React.Fragment>
        ))}
      </div>

      {/* search */}
      <button onClick={onSearch} style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '0 12px', height: 34, width: 280,
        background: 'var(--apm-bg)', border: '1px solid var(--apm-line)',
        borderRadius: 'var(--apm-radius)', cursor: 'pointer',
        color: 'var(--apm-muted)', fontSize: 13, fontFamily: 'var(--apm-font-body)',
      }}>
        <Icon name="search" size={14} />
        <span style={{ flex: 1, textAlign: 'left' }}>Search projects, tickets, components…</span>
        <Kbd>⌘K</Kbd>
      </button>

      {/* chat */}
      <Button variant="outline" size="sm" icon={<Icon name="chat" size={14} />} onClick={onChat}>
        Ask Claude
      </Button>

      {/* new */}
      <Button variant="primary" size="sm" icon={<Icon name="plus" size={14} />} onClick={onNew}>
        New
      </Button>

      {/* notifications / messages */}
      <button onClick={onMessages} style={{
        width: 34, height: 34, borderRadius: 8,
        background: 'transparent', border: '1px solid var(--apm-line)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer', color: 'var(--apm-ink-2)', position: 'relative',
      }}>
        <Icon name="bell" size={14} />
        {msgCount > 0 && <span style={{
          position: 'absolute', top: 7, right: 7,
          width: 7, height: 7, borderRadius: '50%',
          background: 'var(--apm-accent)', border: '1.5px solid var(--apm-bg-2)',
        }} />}
      </button>

      {/* user profile */}
      <button onClick={onProfile} style={{
        width: 34, height: 34, borderRadius: 8,
        background: 'transparent', border: '1px solid var(--apm-line)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer', color: 'var(--apm-ink-2)', padding: 0, overflow: 'hidden',
      }}>
        <Avatar person={persona} size={34} />
      </button>
    </div>
  );
};

// ── Page shell (used by every page) ─────────────────────────────────
const Page = ({ children, max = 1280, pad = true }) => (
  <div style={{
    padding: pad ? 'var(--apm-page-top) var(--apm-page-pad) var(--apm-page-pad)' : 0,
    maxWidth: max, margin: '0 auto', width: '100%',
  }}>{children}</div>
);

const PageHeader = ({ kicker, title, subtitle, action, meta }) => (
  <div style={{ marginBottom: 'var(--apm-section-gap)' }}>
    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 24 }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        {kicker && (
          <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.14em', color: 'var(--apm-muted)', marginBottom: 8, fontWeight: 500 }}>
            {kicker}
          </div>
        )}
        <h1 style={{
          margin: 0, fontFamily: 'var(--apm-font-display)',
          fontWeight: 400, fontSize: 'var(--apm-text-3xl)',
          letterSpacing: '-0.02em', lineHeight: 1.1, color: 'var(--apm-ink)',
          textWrap: 'pretty',
        }}>{title}</h1>
        {subtitle && (
          <div style={{ marginTop: 8, color: 'var(--apm-muted)', fontSize: 14, maxWidth: 720, textWrap: 'pretty' }}>
            {subtitle}
          </div>
        )}
        {meta && <div style={{ marginTop: 12, display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>{meta}</div>}
      </div>
      {action && <div style={{ flexShrink: 0 }}>{action}</div>}
    </div>
  </div>
);

const AppShell = ({ persona, route, goto, openChat, openCompose, setTweak, children }) => {
  const crumbs = (() => {
    if (!route || route.name === 'home') return [{ label: 'Home' }];
    const cap = s => s[0].toUpperCase() + s.slice(1);
    const out = [{ label: cap(route.name), onClick: () => goto(route.name) }];
    if (route.id) {
      let nm = route.id;
      if (route.name === 'project' || route.name === 'projects') nm = (PROJ_BY_ID[route.id]||{}).name;
      else if (route.name === 'initiative' || route.name === 'initiatives') nm = (INI_BY_ID[route.id]||{}).name;
      else if (route.name === 'components') nm = (COMP_BY_ID[route.id]||{}).name;
      else if (route.name === 'ideas') nm = (APM_IDEAS.find(i => i.id === route.id)||{}).title;
      if (nm) out.push({ label: nm });
    }
    return out;
  })();
  const counts = {
    tickets: APM_TICKETS.filter(t => t.status === 'open').length,
    ideas: APM_IDEAS.filter(i => i.status === 'new').length,
    help: APM_HELP.filter(h => h.status === 'open').length,
    messages: APM_TICKETS.filter(t => t.assignee === persona.id).length
      + (persona.role === 'owner' ? 3 : 0),
  };
  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: 'var(--apm-bg)' }}>
      <Sidebar route={route.name} onNavigate={goto} persona={persona} counts={counts} />
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        <TopBar
          breadcrumbs={crumbs}
          onSearch={() => {}}
          onChat={openChat}
          onNew={openCompose}
          onMessages={() => goto('messages')}
          onProfile={() => goto('profile')}
          persona={persona}
          msgCount={counts.messages}
          setTweak={setTweak}
        />
        <main style={{ flex: 1, minWidth: 0 }}>{children}</main>
      </div>
    </div>
  );
};

Object.assign(window, { Sidebar, TopBar, Page, PageHeader, NAV, AppShell });
