// Shell — TopNav + Sidebar + AppShell wrapper

function TroveAIIcon({ className }) {
  return (
    <span className={`troveai-logo ${className || ''}`}>
      <I.Logo />
    </span>
  );
}

function TopNav({ activeTab, onTab, theme, onTheme, onSearchClick, aiOpen, onToggleAI, onPage, onCollection, activeCollection, activePage }) {
  const PUBLIC = typeof window !== 'undefined' && window.__PUBLIC_MODE__ && !window.__FULL_ACCESS__;
  const [mobileMenuOpen, setMobileMenuOpen] = React.useState(false);

  return (
    <React.Fragment>
      <header className="nav">
        <div className="nav-left">
          <a className="nav-brand" href="https://www.usetrove.app" target="_blank" rel="noopener noreferrer">
            <I.Logo />
            <span>Trove</span>
          </a>
          <div className="vdiv" />
          <nav className="nav-tabs">
            {[
              { id: "catchup", label: "Catch Up" },
              { id: "collections", label: "Collections" },
              { id: "bookmarks", label: "Bookmarks" },
              { id: "map", label: "Insights" },
              { id: "community", label: "Community" },
            ].filter(t => !(PUBLIC && (t.id === 'bookmarks' || t.id === 'map'))).map((t) => (
              <a
                key={t.id}
                className={`nav-tab ${activeTab === t.id ? "active" : ""}`}
                onClick={() => onTab(t.id)}
              >
                {t.label}
              </a>
            ))}
          </nav>
        </div>

        <div className="nav-right">
          <button className="search-trigger nav-link" onClick={onSearchClick} style={{display:'inline-flex',alignItems:'center',gap:6}}>
            <I.Search className="icon icon-sm" />
            <span style={{fontSize:12}}>Search</span>
            <span className="kbd">⌘K</span>
          </button>
          <a className="nav-link" onClick={() => onPage && onPage('feedback')} style={{cursor:'pointer', display: PUBLIC ? 'none' : undefined}}>Feedback</a>
          <a className="nav-link" style={{display: PUBLIC ? 'none' : 'inline-flex',alignItems:'center',gap:5}}>
            <I.Connect className="icon icon-sm" /> Connect AI
          </a>
          <button
            className={`troveai-trigger ${aiOpen ? 'active' : ''}`}
            onClick={onToggleAI}
            aria-pressed={aiOpen}
            aria-label="Toggle TroveAI panel"
          >
            <TroveAIIcon />
            <span>Ask Trove</span>
          </button>
          <div className="vdiv" />
          <button className="btn-icon tooltip-host tooltip-below" data-tip={theme === 'dark' ? 'Light mode' : 'Dark mode'} onClick={onTheme}>
            {theme === 'dark' ? <I.Sun className="icon" /> : <I.Moon className="icon" />}
          </button>
          <button className="btn-icon tooltip-host tooltip-below" data-tip="Settings"><I.Settings className="icon" /></button>
          <div className="avatar">{SAMPLE.user.initials}</div>
          {/* Hamburger — visible on mobile only via CSS */}
          <button
            className="nav-hamburger"
            onClick={() => setMobileMenuOpen(true)}
            aria-label="Open menu"
          >
            <svg viewBox="0 0 24 24" className="icon icon-sm" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <path d="M4 6h16M4 12h16M4 18h16"/>
            </svg>
          </button>
        </div>
      </header>

      <MobileDrawer
        open={mobileMenuOpen}
        onClose={() => setMobileMenuOpen(false)}
        activePage={activePage}
        activeCollection={activeCollection}
        onPage={(id) => { onPage(id); setMobileMenuOpen(false); }}
        onTab={(id) => { onTab(id); setMobileMenuOpen(false); }}
        onCollection={(id) => { onCollection && onCollection(id); setMobileMenuOpen(false); }}
        theme={theme}
        onTheme={onTheme}
      />
    </React.Fragment>
  );
}

function MobileDrawer({ open, onClose, activePage, activeCollection, onPage, onTab, onCollection, theme, onTheme }) {
  const PUBLIC = typeof window !== 'undefined' && window.__PUBLIC_MODE__ && !window.__FULL_ACCESS__;

  // ESC to close
  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [open, onClose]);

  if (!open) return null;

  const navPages = [
    { id: 'catchup',     label: 'Catch Up',    icon: <I.Sparkle className="icon icon-sm" /> },
    { id: 'collections', label: 'Collections',  icon: <I.Folder className="icon icon-sm" /> },
    !PUBLIC && { id: 'bookmarks', label: 'Bookmarks', icon: <I.Bookmark className="icon icon-sm" /> },
    !PUBLIC && { id: 'map',       label: 'Insights',  icon: <I.Map className="icon icon-sm" /> },
    { id: 'community',   label: 'Community',    icon: <I.Globe className="icon icon-sm" /> },
  ].filter(Boolean);

  return (
    <div className="mob-overlay">
      <div className="mob-backdrop" onClick={onClose} />
      <div className="mob-panel">

        {/* Header */}
        <div className="mob-header">
          <span className="mob-header-title">Menu</span>
          <button className="btn-icon" onClick={onClose} aria-label="Close menu">
            <I.Close className="icon icon-sm" />
          </button>
        </div>

        {/* Scrollable body */}
        <div className="mob-body">
          <div className="mob-section">
            <div className="mob-section-label">Navigate</div>
            {navPages.map(p => (
              <button
                key={p.id}
                className={`mob-nav-item ${activePage === p.id ? 'active' : ''}`}
                onClick={() => onPage(p.id)}
              >
                <span className="mob-nav-icon">{p.icon}</span>
                <span>{p.label}</span>
              </button>
            ))}
          </div>

          <div className="mob-divider" />

          <div className="mob-section">
            <div className="mob-section-label">More</div>
            {!PUBLIC && (
              <button
                className={`mob-nav-item ${activePage === 'feedback' ? 'active' : ''}`}
                onClick={() => onPage('feedback')}
              >
                <span className="mob-nav-icon"><I.MsgCircle className="icon icon-sm" /></span>
                <span>Feedback</span>
              </button>
            )}
            <div className="mob-nav-item" style={{opacity:0.45, cursor:'not-allowed'}}>
              <span className="mob-nav-icon"><I.Bulb className="icon icon-sm" /></span>
              <span>About</span>
              <span className="mob-soon">Soon</span>
            </div>
          </div>
        </div>

        {/* Footer — always visible */}
        <div className="mob-footer">
          <button className="mob-nav-item" onClick={onTheme}>
            <span className="mob-nav-icon">
              {theme === 'dark' ? <I.Sun className="icon icon-sm" /> : <I.Moon className="icon icon-sm" />}
            </span>
            <span>{theme === 'dark' ? 'Light Mode' : 'Dark Mode'}</span>
          </button>
          <div className="mob-profile">
            <div className="avatar">{SAMPLE.user.initials}</div>
            <span className="mob-profile-name">{SAMPLE.user.name}</span>
          </div>
        </div>

      </div>
    </div>
  );
}

function Sidebar({ activePage, onPage, activeCollection, onCollection, collapsed, onToggleCollapse }) {
  const PUBLIC = typeof window !== 'undefined' && window.__PUBLIC_MODE__ && !window.__FULL_ACCESS__;
  if (collapsed) {
    return (
      <aside className="sidebar sidebar-collapsed" style={{width:52, padding:'12px 6px', alignItems:'center', gap:8}}>
        <button className="btn-icon" onClick={onToggleCollapse} style={{marginBottom:8}}>
          <I.ChevronRight className="icon icon-sm" />
        </button>
        <button className={`btn-icon ${activePage === 'catchup' ? 'active-icon' : ''}`} onClick={() => onPage('catchup')} style={{color: activePage==='catchup' ? 'var(--blue)' : 'var(--text-3)'}}>
          <I.Sparkle className="icon icon-sm" />
        </button>
        <button className={`btn-icon ${activePage === 'bookmarks' ? 'active-icon' : ''}`} onClick={() => onPage('bookmarks')} style={{display: PUBLIC ? 'none' : undefined, color: activePage==='bookmarks' ? 'var(--blue)' : 'var(--text-3)'}}>
          <I.Bookmark className="icon icon-sm" />
        </button>
        <button className={`btn-icon ${activePage === 'map' ? 'active-icon' : ''}`} onClick={() => onPage('map')} style={{display: PUBLIC ? 'none' : undefined, color: activePage==='map' ? 'var(--blue)' : 'var(--text-3)'}}>
          <I.Map className="icon icon-sm" />
        </button>
        <button className={`btn-icon ${activePage === 'community' ? 'active-icon' : ''}`} onClick={() => onPage('community')} style={{color: activePage==='community' ? 'var(--blue)' : 'var(--text-3)'}}>
          <I.Globe className="icon icon-sm" />
        </button>
        <div style={{flex:1}} />
        {SAMPLE.collections.filter(c => !c.parentId && c.id !== 'inbox').slice(0, 5).map(c => (
          <button key={c.id} className="btn-icon tooltip-host" data-tip={c.name} onClick={() => onCollection(c.id)}>
            <span style={{width:8, height:8, borderRadius:2, background: c.color, display:'block'}} />
          </button>
        ))}
        <div style={{flex:1}} />
        <button className="btn-icon" style={{color:'var(--text-4)'}}><I.Archive className="icon icon-sm" /></button>
        <button className="btn-icon" style={{color:'var(--text-4)'}}><I.Upload className="icon icon-sm" /></button>
      </aside>
    );
  }

  return (
    <aside className="sidebar">
      <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 8px 8px 12px'}}>
        <span style={{fontSize:10, fontWeight:700, color:'var(--text-4)', letterSpacing:'0.08em', textTransform:'uppercase'}}>Navigate</span>
        <button className="btn-icon" onClick={onToggleCollapse} style={{width:24, height:24}}>
          <I.ChevronRight className="icon icon-xs" style={{transform:'rotate(180deg)'}} />
        </button>
      </div>

      <div className="sb-section">
        <a className={`sb-item ${activePage === 'catchup' && !activeCollection ? 'active' : ''}`} onClick={() => onPage('catchup')}>
          <I.Sparkle className="icon icon-sm" /> Catch Up
        </a>
        <a className={`sb-item ${activePage === 'bookmarks' && !activeCollection ? 'active' : ''}`} onClick={() => onPage('bookmarks')} style={{display: PUBLIC ? 'none' : undefined}}>
          <I.Bookmark className="icon icon-sm" /> All Bookmarks <span className="count">{SAMPLE.bookmarks.length}</span>
        </a>
        <a className={`sb-item ${activePage === 'map' ? 'active' : ''}`} onClick={() => onPage('map')} style={{display: PUBLIC ? 'none' : undefined}}>
          <I.Map className="icon icon-sm" /> Insights
        </a>
        <a className={`sb-item ${activePage === 'community' ? 'active' : ''}`} onClick={() => onPage('community')}>
          <I.Globe className="icon icon-sm" /> Community
        </a>
      </div>

      <div className="sb-section" style={{flex:1}}>
        <div className="sb-label">
          <span>Collections</span>
          <button className="add-btn tooltip-host" data-tip="New collection"><I.PlusSm /></button>
        </div>
        <SidebarCollections activeCollection={activeCollection} onCollection={onCollection} />
      </div>

      <div className="sb-footer">
        <a className="sb-item" onClick={() => onPage('archive')}>
          <I.Archive className="icon icon-sm" style={{width:12, height:12}} /> Archive
        </a>
        <a className="sb-item">Bulk Upload</a>
        <a className="sb-item">Reading Log</a>
        <a className="sb-item">About</a>
      </div>
    </aside>
  );
}

function SidebarCollections({ activeCollection, onCollection }) {
  // Default-expand the parent of any active collection so it's visible
  const initialExpanded = React.useMemo(() => {
    const set = new Set();
    if (activeCollection) {
      const path = SAMPLE.collectionPath(activeCollection);
      path.forEach(c => set.add(c.id));
    }
    // Auto-expand AI by default since it's the showcase
    set.add('ai');
    return set;
  }, []);
  const [expanded, setExpanded] = React.useState(initialExpanded);

  const toggle = (id) => {
    const next = new Set(expanded);
    next.has(id) ? next.delete(id) : next.add(id);
    setExpanded(next);
  };

  const topLevel = SAMPLE.collections.filter(c => !c.parentId && c.id !== 'inbox');

  return (
    <>
      {topLevel.map(c => {
        const children = SAMPLE.childCollections(c.id);
        const isExpanded = expanded.has(c.id);
        const hasChildren = children.length > 0;
        return (
          <React.Fragment key={c.id}>
            <a
              className={`sb-item ${activeCollection === c.id ? 'active' : ''}`}
              onClick={() => onCollection(c.id)}
              style={{paddingRight: 6}}
            >
              {hasChildren ? (
                <button
                  className="sb-chevron"
                  onClick={(e) => { e.stopPropagation(); toggle(c.id); }}
                  aria-label={isExpanded ? 'Collapse' : 'Expand'}
                >
                  <I.ChevronRight
                    className="icon icon-xs"
                    style={{
                      transform: isExpanded ? 'rotate(90deg)' : 'rotate(0)',
                      transition: 'transform var(--t-fast) var(--ease)',
                    }}
                  />
                </button>
              ) : (
                <span className="sb-chevron-spacer" />
              )}
              <span className="dot" style={{background: c.color}}></span>
              {c.name}
              <span className="count">{c.count}</span>
            </a>
            {isExpanded && hasChildren && (
              <div className="sb-children">
                {children.map(child => (
                  <a
                    key={child.id}
                    className={`sb-item sb-child ${activeCollection === child.id ? 'active' : ''}`}
                    onClick={() => onCollection(child.id)}
                  >
                    <span className="dot" style={{background: child.color, opacity: 0.8}}></span>
                    {child.name}
                    <span className="count">{child.count}</span>
                  </a>
                ))}
              </div>
            )}
          </React.Fragment>
        );
      })}
    </>
  );
}

window.TopNav = TopNav;
window.Sidebar = Sidebar;
window.TroveAIIcon = TroveAIIcon;