// Sidebar + Topbar shell for INLEARN CRM

function Sidebar({ view, setView, contacts, deals, rawLeads, collapsed, setCollapsed }) {
  const counts = useMemo(() => ({
    rawLeads: (rawLeads || []).length,
    leads: (deals || []).length,
    contacts: (contacts || []).length,
    activeDeals: (deals || []).filter(d => isActiveStage(d.stage)).length,
    calls: (deals || []).filter(d => d.stage === 'CallScheduled').length,
  }), [contacts, deals, rawLeads]);

  const NavItem = ({ id, label, icon, badge, accent, pill }) => {
    const active = view === id;
    if (collapsed) {
      return (
        <button onClick={() => setView(id)} title={label}
          className={`group relative w-10 h-10 mx-auto flex items-center justify-center rounded-lg transition-colors ${
            active ? 'bg-slate-900 text-white' : 'text-slate-500 hover:bg-slate-100 hover:text-slate-900'
          }`}>
          {icon}
          {badge != null && badge > 0 && (
            <span className={`absolute -top-0.5 -right-0.5 text-[9px] min-w-[16px] h-[16px] px-1 rounded-full font-bold tabular-nums inline-flex items-center justify-center ${
              active ? 'bg-white text-slate-900' : 'bg-slate-900 text-white'
            }`}>{badge}</span>
          )}
          {/* Tooltip */}
          <span className="absolute left-full ml-2 px-2 py-1 bg-slate-900 text-white text-[11px] rounded whitespace-nowrap opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity z-50">
            {label}
          </span>
        </button>
      );
    }
    return (
      <button onClick={() => setView(id)}
        className={`group w-full flex items-center gap-2.5 h-9 px-2.5 rounded-lg text-sm font-medium transition-colors ${
          active ? 'bg-slate-900 text-white' : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
        }`}>
        <span className={`shrink-0 ${active ? 'text-white' : 'text-slate-500 group-hover:text-slate-700'}`}>{icon}</span>
        <span className="flex-1 text-left">{label}</span>
        {pill && (
          <span className="text-[9px] px-1.5 h-4 rounded-full font-bold uppercase tracking-wide inline-flex items-center bg-amber-100 text-amber-700">{pill}</span>
        )}
        {badge != null && (
          <span className={`text-[11px] px-1.5 h-5 rounded-md font-semibold tabular-nums inline-flex items-center ${
            active ? 'bg-white/15 text-white' : (accent || 'bg-slate-100 text-slate-600')
          }`}>{badge}</span>
        )}
      </button>
    );
  };

  const SectionLabel = ({ children }) =>
    collapsed ? (
      <div className="my-2 h-px mx-3 bg-slate-200"/>
    ) : (
      <div className="px-1.5 pt-3 pb-1.5 text-[10px] font-semibold uppercase tracking-wider text-slate-400">{children}</div>
    );

  return (
    <aside className={`shrink-0 border-r border-slate-200 bg-white flex flex-col h-screen sticky top-0 transition-[width] duration-200 ${
      collapsed ? 'w-[60px]' : 'w-56'
    }`}>
      {/* Brand */}
      <div className={`h-16 flex items-center gap-2.5 border-b border-slate-200 ${collapsed ? 'justify-center px-2' : 'px-4'}`}>
        <div className="h-8 w-8 rounded-lg bg-slate-900 text-white flex items-center justify-center font-bold tracking-tight text-[13px] shrink-0">
          IL
        </div>
        {!collapsed && (
          <div className="flex flex-col leading-tight min-w-0">
            <span className="text-sm font-semibold text-slate-900 truncate">INLEARN (Pty) Ltd</span>
            <span className="text-[11px] text-slate-500 truncate">Leads &amp; Sales CRM</span>
          </div>
        )}
      </div>

      {/* Nav */}
      <nav className={`flex-1 overflow-y-auto overflow-x-hidden py-2 ${collapsed ? 'px-1.5' : 'px-2.5'} space-y-0.5`}>
        <SectionLabel>Marketing</SectionLabel>
        <NavItem id="campaigns" label="Campaigns" icon={<Icon.Trend />} pill="Beta" />

        <SectionLabel>Sales</SectionLabel>
        <NavItem id="dashboard" label="Dashboard" icon={<Icon.Pie />} />
        <NavItem id="leads"     label="Leads" icon={<Icon.Users />} badge={counts.leads} />
        <NavItem id="contacts"  label="Contacts" icon={<Icon.Users />} badge={counts.contacts} />
        <NavItem id="deals"     label="Deals" icon={<Icon.Layers />} badge={counts.activeDeals} />
        <NavItem id="calls"     label="Calls Today" icon={<Icon.Calendar />} badge={counts.calls} />

        <SectionLabel>Catalog</SectionLabel>
        <NavItem id="services"  label="Services" icon={<Icon.Box />} />

        <SectionLabel>Insights</SectionLabel>
        <NavItem id="reports"   label="Reports" icon={<Icon.Trend />} />
        <NavItem id="playbook"  label="Playbooks" icon={<Icon.Book />} />

        <SectionLabel>Manage</SectionLabel>
        <NavItem id="settings"  label="Settings" icon={<Icon.Settings />} />
      </nav>

      {/* Collapse toggle */}
      <div className={`border-t border-slate-200 ${collapsed ? 'p-1.5' : 'p-2'}`}>
        <button onClick={() => setCollapsed(!collapsed)}
          title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
          className={`group w-full flex items-center gap-2 h-9 rounded-lg text-[12px] font-medium text-slate-500 hover:bg-slate-100 hover:text-slate-700 transition-colors ${
            collapsed ? 'justify-center px-0' : 'px-2.5'
          }`}>
          <span className="shrink-0">
            {collapsed ? <Icon.ChevronRight size={16}/> : <Icon.ChevronLeft size={16}/>}
          </span>
          {!collapsed && <span>Collapse</span>}
        </button>
      </div>

      {/* User card */}
      {(() => {
        // When signed in (live site) show the authenticated Google account + sign out.
        // In preview/local there's no auth, so fall back to the demo identity.
        const auth = window.INLEARN_AUTH;
        const signedIn = !!(auth && auth.user);
        const isOwner = !!(auth && auth.isOwner);
        const name = signedIn ? (auth.user.displayName || auth.user.email) : 'Gugu Ndlovu';
        const sub  = signedIn ? auth.user.email : 'Sales Coordinator';
        const onAccount = signedIn ? auth.signOut : undefined;
        return (
          <div className={`border-t border-slate-200 ${collapsed ? 'p-1.5' : 'p-3'}`}>
            {collapsed ? (
              <div className="flex justify-center" title={`${name}${signedIn ? ' — Sign out' : ' — Sales Coordinator'}`}>
                <button onClick={onAccount} className="rounded-full" title={signedIn ? 'Sign out' : name}>
                  <Avatar name={name} color="#4F46E5" size={32} />
                </button>
              </div>
            ) : (
              <div className="flex items-center gap-2.5">
                <Avatar name={name} color="#4F46E5" size={32} />
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium text-slate-900 truncate">{name}</div>
                  <div className="text-[11px] text-slate-500 truncate">{sub}</div>
                </div>
                {isOwner && <IconButton icon={<Icon.Shield />} title="Manage access" onClick={() => auth.openAccessManager()} />}
                {signedIn
                  ? <IconButton icon={<Icon.Logout />} title="Sign out" onClick={onAccount} />
                  : <IconButton icon={<Icon.More />} title="Account" />}
              </div>
            )}
          </div>
        );
      })()}
    </aside>
  );
}
window.Sidebar = Sidebar;

function Topbar({ view, onNewLead, onSearch, search, contacts, deals, onJumpToContact, onJumpToDeal }) {
  const titles = {
    dashboard: { t: 'Dashboard',  s: 'Pipeline health, conversion and revenue at a glance' },
    campaigns: { t: 'Campaigns',  s: 'Plan and track marketing campaigns that feed your leads' },
    leads:     { t: 'Leads',      s: 'Searchable table of every lead in your CRM' },
    contacts:  { t: 'Contacts',   s: 'Every person you’ve ever interacted with' },
    deals:     { t: 'Deals',      s: 'Drag deals between stages to update your sales flow' },
    calls:     { t: 'Calls Today',s: 'Clarity calls booked for today — prep and run them' },
    services:  { t: 'Services',   s: 'The tutoring packages and subjects INLEARN offers' },
    reports:   { t: 'Reports',    s: 'Funnel, source, revenue and referral analytics' },
    playbook:  { t: 'Playbooks',  s: 'Stage-by-stage sales scripts and next actions' },
    settings:  { t: 'Settings',   s: 'Pipeline stages, lead sources and team configuration' },
  };
  const meta = titles[view] || titles.dashboard;
  const [searchOpen, setSearchOpen] = useState(false);

  // Quick lookup: contacts + deals
  const matches = useMemo(() => {
    if (!search || search.length < 1) return { contacts: [], deals: [] };
    const q = search.toLowerCase();
    const cs = (contacts || []).filter(c =>
      contactFullName(c).toLowerCase().includes(q) ||
      (c.email || '').toLowerCase().includes(q) ||
      (c.phone || '').includes(q) ||
      (c.subjects || []).some(s => s.toLowerCase().includes(q))
    ).slice(0, 5);
    const ds = (deals || []).filter(d =>
      d.title.toLowerCase().includes(q) ||
      (d.subjects || []).some(s => s.toLowerCase().includes(q))
    ).slice(0, 5);
    return { contacts: cs, deals: ds };
  }, [search, contacts, deals]);

  const hasMatches = matches.contacts.length > 0 || matches.deals.length > 0;

  return (
    <header className="h-16 border-b border-slate-200 bg-white sticky top-0 z-30">
      <div className="h-full px-7 flex items-center justify-between gap-6">
        <div className="min-w-0">
          <div className="text-[18px] font-semibold tracking-tight text-slate-900">{meta.t}</div>
          <div className="text-xs text-slate-500 truncate">{meta.s}</div>
        </div>

        <div className="flex items-center gap-2.5">
          {/* Search */}
          <div className="relative">
            <div className="relative">
              <span className="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400"><Icon.Search size={14}/></span>
              <input
                type="text" value={search}
                onChange={(e) => onSearch(e.target.value)}
                onFocus={() => setSearchOpen(true)}
                onBlur={() => setTimeout(() => setSearchOpen(false), 150)}
                placeholder="Search contacts, deals…"
                className="h-9 w-72 pl-8 pr-3 bg-slate-50 hover:bg-white focus:bg-white text-sm border border-slate-200 focus:border-slate-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-100 transition-colors text-slate-900 placeholder:text-slate-400"
              />
              <span className="absolute right-2 top-1/2 -translate-y-1/2 text-[10px] text-slate-400 border border-slate-200 px-1 rounded">⌘K</span>
            </div>
            {searchOpen && hasMatches && (
              <div className="absolute top-11 right-0 w-96 bg-white border border-slate-200 rounded-lg shadow-lg p-1.5 z-50 max-h-[70vh] overflow-y-auto">
                {matches.contacts.length > 0 && (
                  <>
                    <div className="text-[10px] uppercase tracking-wider text-slate-400 px-2 py-1.5">Contacts</div>
                    {matches.contacts.map(c => (
                      <button key={c.id}
                        onMouseDown={(e) => { e.preventDefault(); onJumpToContact(c); }}
                        className="w-full flex items-center gap-3 px-2 py-1.5 rounded-md hover:bg-slate-50 text-left">
                        <Avatar name={contactFullName(c)} size={26}/>
                        <div className="flex-1 min-w-0">
                          <div className="text-sm font-medium text-slate-900 truncate">{contactFullName(c)}</div>
                          <div className="text-[11px] text-slate-500 truncate">{c.type}{c.gradeOrYear ? ` • ${c.gradeOrYear}` : ''}</div>
                        </div>
                        <TypeBadge type={c.type}/>
                      </button>
                    ))}
                  </>
                )}
                {matches.deals.length > 0 && (
                  <>
                    <div className="text-[10px] uppercase tracking-wider text-slate-400 px-2 py-1.5">Deals</div>
                    {matches.deals.map(d => (
                      <button key={d.id}
                        onMouseDown={(e) => { e.preventDefault(); onJumpToDeal(d); }}
                        className="w-full flex items-center gap-3 px-2 py-1.5 rounded-md hover:bg-slate-50 text-left">
                        <span className="h-6 w-6 rounded-md bg-amber-50 text-amber-700 flex items-center justify-center shrink-0"><Icon.Layers size={13}/></span>
                        <div className="flex-1 min-w-0">
                          <div className="text-sm font-medium text-slate-900 truncate">{d.title}</div>
                          <div className="text-[11px] text-slate-500 truncate">{(d.subjects || []).join(', ')}</div>
                        </div>
                        <StageChip stageId={d.stage} />
                      </button>
                    ))}
                  </>
                )}
              </div>
            )}
          </div>

          <IconButton icon={<Icon.Bell size={16}/>} title="Notifications" variant="outline" />

          <Button variant="brand" size="md" icon={<Icon.Plus size={16}/>} onClick={onNewLead}>
            New Lead
          </Button>
        </div>
      </div>
    </header>
  );
}
window.Topbar = Topbar;
