// App shell: sidebar, org switcher dropdown, topbar, mobile bottom nav.
// Export to window.Screens.Shell.
const { useState: useStateSh, useRef: useRefSh, useEffect: useEffectSh } = React;

const NAV = [
  { id: 'dashboard', label: 'Дашборд', icon: 'Dashboard', tint: 'lavender' },
  { id: 'sources',   label: 'Источники', icon: 'Plug', tint: 'mint' },
  { id: 'ideas',     label: 'Идеи', icon: 'Lightbulb', tint: 'lemon' },
  { id: 'generate',  label: 'Генерация', icon: 'Sparkles', tint: 'violet' },
  { id: 'posts',     label: 'Посты', icon: 'Grid', tint: 'sky' },
  { id: 'analytics', label: 'Аналитика', icon: 'BarChart', tint: 'peach' },
  { id: 'brand',     label: 'Брендбук', icon: 'Palette', tint: 'rose' },
  { id: 'settings',  label: 'Настройки', icon: 'Settings', tint: 'ink' },
];

const NAV_TINT_BG = {
  lavender: 'bg-lavender-soft text-lavender-ink',
  mint:     'bg-mint-soft text-mint-ink',
  lemon:    'bg-lemon-soft text-lemon-ink',
  violet:   'bg-violet-soft text-violet-ink',
  sky:      'bg-sky-soft text-sky-ink',
  peach:    'bg-peach-soft text-peach-ink',
  rose:     'bg-rose-soft text-rose-ink',
  ink:      'bg-ink-100 text-ink-700',
};

function Shell({ user, orgs, currentOrgId, route, onRouteChange, onSwitchOrg, onCreateOrg, onLogout, children, topbar }) {
  const I = window.Icons;
  const { Avatar, IconButton } = window.UI;
  const currentOrg = orgs.find(o => o.id === currentOrgId) || orgs[0];

  const [orgOpen, setOrgOpen] = useStateSh(false);
  const [mobileMenu, setMobileMenu] = useStateSh(false);
  const orgRef = useRefSh(null);

  useEffectSh(() => {
    const onDoc = (e) => { if (orgRef.current && !orgRef.current.contains(e.target)) setOrgOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  return (
    <div className="min-h-screen flex">
      {/* Sidebar */}
      <aside className="hidden lg:flex w-[260px] shrink-0 border-r border-ink-200 bg-paper flex-col">
        {/* Org switcher */}
        <div className="px-3 pt-3 relative" ref={orgRef}>
          <button
            onClick={() => setOrgOpen(v => !v)}
            className={'w-full flex items-center gap-3 p-2.5 rounded-xl transition-colors ' + (orgOpen ? 'bg-white border border-ink-200 shadow-soft' : 'hover:bg-ink-100 border border-transparent')}
          >
            <Avatar initial={currentOrg.initial} color={currentOrg.accent} size={36}/>
            <div className="flex-1 min-w-0 text-left">
              <div className="text-[13.5px] font-semibold truncate">{currentOrg.name}</div>
              <div className="text-[11.5px] text-ink-500 truncate">{currentOrg.role}</div>
            </div>
            <I.Chevron size={16} className={'text-ink-500 transition-transform ' + (orgOpen ? 'rotate-180' : '')}/>
          </button>

          {orgOpen && (
            <div className="absolute z-40 left-3 right-3 mt-2 bg-white border border-ink-200 rounded-2xl shadow-pop p-2 slide-up">
              <div className="px-2 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-ink-500">Организации</div>
              <div className="space-y-0.5">
                {orgs.map((o) => (
                  <button
                    key={o.id}
                    onClick={() => { onSwitchOrg(o.id); setOrgOpen(false); }}
                    className={'w-full flex items-center gap-3 p-2 rounded-lg ' + (o.id === currentOrgId ? 'bg-ink-100' : 'hover:bg-ink-50')}
                  >
                    <Avatar initial={o.initial} color={o.accent} size={28}/>
                    <div className="flex-1 min-w-0 text-left">
                      <div className="text-[13px] font-semibold truncate">{o.name}</div>
                      <div className="text-[11px] text-ink-500 truncate">{o.role}</div>
                    </div>
                    {o.id === currentOrgId && <I.Check size={14} className="text-ink-900"/>}
                  </button>
                ))}
              </div>
              <div className="h-px bg-ink-200 my-2"/>
              <button
                onClick={() => { onCreateOrg(); setOrgOpen(false); }}
                className="w-full flex items-center gap-3 p-2 rounded-lg hover:bg-ink-50 text-left"
              >
                <div className="h-7 w-7 rounded-md bg-ink-100 flex items-center justify-center text-ink-700"><I.Plus size={14}/></div>
                <span className="text-[13px] font-semibold">Создать организацию</span>
              </button>
            </div>
          )}
        </div>

        {/* Nav */}
        <nav className="px-3 mt-4 flex-1 space-y-0.5">
          {NAV.map((item) => {
            const Icon = I[item.icon];
            const active = route === item.id;
            return (
              <button
                key={item.id}
                onClick={() => onRouteChange(item.id)}
                className={'group w-full flex items-center gap-2.5 px-2 h-9 rounded-lg text-[13.5px] transition-colors ' + (active ? 'bg-white border border-ink-200 shadow-soft text-ink-900 font-semibold' : 'text-ink-700 hover:bg-ink-100 font-medium')}
              >
                <span className={'h-7 w-7 rounded-md flex items-center justify-center shrink-0 wiggle ' + NAV_TINT_BG[item.tint]}>
                  <Icon size={14}/>
                </span>
                <span className="flex-1 text-left">{item.label}</span>
                {item.id === 'ideas' && <span className="text-[10.5px] font-semibold bg-violet text-white rounded-full px-1.5 py-0.5">3</span>}
              </button>
            );
          })}
        </nav>

        {/* User */}
        <div className="p-3 border-t border-ink-200 mt-3">
          <div className="flex items-center gap-3 p-2 rounded-xl hover:bg-ink-100 cursor-pointer group">
            <Avatar initial={(user.name || user.email || 'U')[0].toUpperCase()} color="#0F0F0F" size={32}/>
            <div className="flex-1 min-w-0">
              <div className="text-[12.5px] font-semibold truncate">{user.name || 'Пользователь'}</div>
              <div className="text-[11px] text-ink-500 truncate">{user.email}</div>
            </div>
            <button onClick={onLogout} title="Выйти" className="h-7 w-7 rounded-md flex items-center justify-center text-ink-500 hover:bg-ink-200 hover:text-ink-900">
              <I.Logout size={14}/>
            </button>
          </div>
        </div>
      </aside>

      {/* Main column */}
      <div className="flex-1 min-w-0 flex flex-col">
        {/* Top bar */}
        <header className="sticky top-0 z-30 bg-paper/90 backdrop-blur border-b border-ink-200 h-14 px-4 sm:px-6 flex items-center gap-3">
          {/* mobile menu trigger */}
          <button onClick={() => setMobileMenu(true)} className="lg:hidden h-9 w-9 rounded-full hover:bg-ink-100 flex items-center justify-center">
            <I.Menu size={18}/>
          </button>
          <div className="hidden lg:flex items-center gap-2 text-[13.5px] text-ink-500 min-w-0">
            <span className="truncate">{currentOrg.name}</span>
            <I.ChevronRight size={14}/>
            <span className="text-ink-900 font-semibold truncate">{NAV.find(n => n.id === route)?.label || ''}</span>
          </div>
          <div className="lg:hidden flex items-center gap-2 min-w-0">
            <Avatar initial={currentOrg.initial} color={currentOrg.accent} size={26}/>
            <div className="font-semibold text-[14px] truncate">{NAV.find(n => n.id === route)?.label || ''}</div>
          </div>
          <div className="flex-1"/>
          <div className="flex items-center gap-1.5">
            <ThemeSwitcher/>
            <div className="hidden sm:block w-px h-5 bg-ink-200 mx-1"/>
            {topbar}
            <IconButton size="sm" title="Уведомления"><I.Bell size={16}/></IconButton>
          </div>
        </header>

        {/* Page content */}
        <main className="flex-1 overflow-y-auto thin-scroll pb-24 lg:pb-10">
          <div key={route} className="fade-in">
            {children}
          </div>
        </main>
      </div>

      {/* Mobile drawer */}
      {mobileMenu && (
        <div className="lg:hidden fixed inset-0 z-50 flex" onClick={() => setMobileMenu(false)}>
          <div className="absolute inset-0 bg-ink-900/30 fade-in"/>
          <div className="relative w-[280px] bg-paper h-full slide-up p-3 border-r border-ink-200" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center gap-3 p-2.5 rounded-xl bg-white border border-ink-200">
              <Avatar initial={currentOrg.initial} color={currentOrg.accent} size={36}/>
              <div className="flex-1 min-w-0">
                <div className="text-[13.5px] font-semibold truncate">{currentOrg.name}</div>
                <div className="text-[11.5px] text-ink-500 truncate">{currentOrg.role}</div>
              </div>
              <IconButton size="sm" onClick={() => setMobileMenu(false)}><I.X size={16}/></IconButton>
            </div>
            <div className="mt-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-ink-500 px-2 mt-3 mb-1">Орг-ции</div>
            <div className="space-y-0.5">
              {orgs.map((o) => (
                <button key={o.id} onClick={() => { onSwitchOrg(o.id); setMobileMenu(false); }} className={'w-full flex items-center gap-2 p-2 rounded-lg ' + (o.id === currentOrgId ? 'bg-ink-100' : 'hover:bg-ink-50')}>
                  <Avatar initial={o.initial} color={o.accent} size={24}/>
                  <span className="text-[13px] font-medium truncate flex-1 text-left">{o.name}</span>
                  {o.id === currentOrgId && <I.Check size={13}/>}
                </button>
              ))}
              <button onClick={() => { onCreateOrg(); setMobileMenu(false); }} className="w-full flex items-center gap-2 p-2 rounded-lg hover:bg-ink-50 text-ink-700">
                <I.Plus size={14}/> <span className="text-[13px]">Создать организацию</span>
              </button>
            </div>
            <div className="mt-4 text-[11px] font-semibold uppercase tracking-[0.14em] text-ink-500 px-2 mb-1">Навигация</div>
            <nav className="space-y-0.5">
              {NAV.map((item) => {
                const Icon = I[item.icon];
                const active = route === item.id;
                return (
                  <button key={item.id} onClick={() => { onRouteChange(item.id); setMobileMenu(false); }}
                    className={'w-full flex items-center gap-2.5 px-2 h-10 rounded-lg text-[14px] ' + (active ? 'bg-white border border-ink-200 font-semibold' : 'hover:bg-ink-100 font-medium')}>
                    <span className={'h-7 w-7 rounded-md flex items-center justify-center ' + NAV_TINT_BG[item.tint]}><Icon size={14}/></span>
                    {item.label}
                  </button>
                );
              })}
            </nav>
          </div>
        </div>
      )}

      {/* Mobile bottom nav */}
      <nav className="lg:hidden fixed bottom-3 left-3 right-3 z-30 bg-ink-900 text-white rounded-full shadow-pop px-2 py-1.5 flex items-center justify-between">
        {[
          { id: 'dashboard', icon: 'Dashboard' },
          { id: 'ideas', icon: 'Lightbulb' },
          { id: 'generate', icon: 'Sparkles', big: true },
          { id: 'posts', icon: 'Grid' },
          { id: 'brand', icon: 'Palette' },
        ].map((item) => {
          const Icon = I[item.icon];
          const active = route === item.id;
          if (item.big) {
            return (
              <button key={item.id} onClick={() => onRouteChange(item.id)} className="h-12 w-12 rounded-full bg-white text-ink-900 flex items-center justify-center -translate-y-2 shadow-soft">
                <Icon size={18}/>
              </button>
            );
          }
          return (
            <button key={item.id} onClick={() => onRouteChange(item.id)} className={'h-10 w-10 rounded-full flex items-center justify-center ' + (active ? 'bg-white/15' : '')}>
              <Icon size={18} className={active ? 'text-white' : 'text-white/70'}/>
            </button>
          );
        })}
      </nav>
    </div>
  );
}

function ThemeSwitcher() {
  const I = window.Icons;
  const [theme, setTheme] = useStateSh(() => {
    try { return localStorage.getItem('omneee.theme') || 'light'; } catch (e) { return 'light'; }
  });
  const [hover, setHover] = useStateSh(null);

  useEffectSh(() => {
    const html = document.documentElement;
    if (theme === 'light') html.removeAttribute('data-theme');
    else html.setAttribute('data-theme', theme);
    try { localStorage.setItem('omneee.theme', theme); } catch (e) {}
  }, [theme]);

  const opts = [
    { v: 'light', Icon: I.Sun,      label: 'Светлая' },
    { v: 'dark',  Icon: I.Moon,     label: 'Тёмная' },
    { v: 'mono',  Icon: I.Contrast, label: 'Минимал' },
  ];

  return (
    <div className="relative inline-flex items-center gap-0.5 rounded-full bg-ink-100 p-0.5">
      {opts.map((o) => {
        const Icon = o.Icon;
        const active = theme === o.v;
        return (
          <button
            key={o.v}
            onClick={() => setTheme(o.v)}
            onMouseEnter={() => setHover(o.v)}
            onMouseLeave={() => setHover(null)}
            title={o.label}
            className={'relative h-7 w-7 rounded-full flex items-center justify-center transition-all ' + (active ? 'bg-white text-ink-900 shadow-soft' : 'text-ink-500 hover:text-ink-900')}
          >
            <Icon size={13}/>
            {hover === o.v && !active && (
              <span className="absolute top-full mt-1.5 left-1/2 -translate-x-1/2 text-[10.5px] font-medium text-ink-700 bg-white border border-ink-200 rounded-md px-1.5 py-0.5 whitespace-nowrap shadow-soft">{o.label}</span>
            )}
          </button>
        );
      })}
    </div>
  );
}

window.Screens = window.Screens || {};
window.Screens.Shell = Shell;
window.ThemeSwitcher = ThemeSwitcher;
