// aerOS — admin app shell: sidebar + topbar + theme/lang hook. Exports to window.
const { useState: _hS, useEffect: _hE, useCallback: _hC } = React;

/* persisted theme + language (single localStorage key) */
function useUI(storeKey = 'aeros-ui') {
  const [ui, setUi] = _hS(() => {
    try { return { theme: 'light', lang: 'tr', ...JSON.parse(localStorage.getItem(storeKey) || '{}') }; }
    catch { return { theme: 'light', lang: 'tr' }; }
  });
  _hE(() => {
    document.documentElement.setAttribute('data-theme', ui.theme);
    document.documentElement.setAttribute('lang', ui.lang);
    try { localStorage.setItem(storeKey, JSON.stringify(ui)); } catch {}
  }, [ui, storeKey]);
  const setTheme = t => setUi(s => ({ ...s, theme: t }));
  const setLang = l => setUi(s => ({ ...s, lang: l }));
  return { theme: ui.theme, lang: ui.lang, setTheme, setLang, toggleTheme: () => setUi(s => ({ ...s, theme: s.theme === 'light' ? 'dark' : 'light' })) };
}

/* compact lang + theme controls for topbars */
function LangThemeControls({ ui, langs = [['tr', 'TR'], ['en', 'EN']] }) {
  const [open, setOpen] = _hS(false);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
      <div style={{ position: 'relative' }}>
        <button onClick={() => setOpen(o => !o)} onBlur={() => setTimeout(() => setOpen(false), 150)}
          style={{ display: 'inline-flex', alignItems: 'center', gap: 6, height: 34, padding: '0 10px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', background: 'var(--bg-0)', color: 'var(--fg-2)', cursor: 'pointer', fontSize: 12.5, fontWeight: 600, fontFamily: 'inherit' }}>
          {Icon.globe({ size: 16 })}{(langs.find(l => l[0] === ui.lang) || langs[0])[1]}{Icon.chevDown({ size: 13 })}
        </button>
        {open && (
          <div style={{ position: 'absolute', top: 40, right: 0, background: 'var(--bg-0)', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', boxShadow: 'var(--shadow-lg)', padding: 5, zIndex: 100, minWidth: 120 }}>
            {langs.map(([code, label]) => (
              <button key={code} onMouseDown={() => { ui.setLang(code); setOpen(false); }}
                style={{ display: 'flex', width: '100%', alignItems: 'center', justifyContent: 'space-between', padding: '8px 10px', borderRadius: 6, border: 'none', background: ui.lang === code ? 'var(--brand-soft)' : 'transparent', color: ui.lang === code ? 'var(--brand)' : 'var(--fg-1)', fontSize: 13, fontWeight: ui.lang === code ? 600 : 500, cursor: 'pointer', fontFamily: 'inherit' }}>
                {label}{ui.lang === code && Icon.check({ size: 14 })}
              </button>
            ))}
          </div>
        )}
      </div>
      <IconButton icon={ui.theme === 'light' ? Icon.moon : Icon.sun} title="Tema" onClick={ui.toggleTheme} />
    </div>
  );
}

/* AppShell: responsive sidebar + topbar.
   props: brand {name, sub, logo, color}, nav [{section, items:[{id,label,icon,badge}]}],
   active, onNav, topRight, title, ui, banner */
function AppShell({ brand, nav, active, onNav, topRight, title, subtitle, children, banner, footer }) {
  const [mobileOpen, setMobileOpen] = _hS(false);
  const [narrow, setNarrow] = _hS(typeof window !== 'undefined' && window.innerWidth < 980);
  _hE(() => {
    const onR = () => setNarrow(window.innerWidth < 980);
    window.addEventListener('resize', onR); return () => window.removeEventListener('resize', onR);
  }, []);
  const SIDEBAR_W = 250;

  const Sidebar = (
    <aside style={{ width: SIDEBAR_W, flexShrink: 0, height: '100%', background: 'var(--bg-0)', borderRight: '1px solid var(--border)', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '16px 18px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 11 }}>
        <div style={{ width: 38, height: 38, borderRadius: 10, background: brand.color || 'var(--brand)', color: brand.onColor || 'var(--on-brand)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontWeight: 700, fontSize: 16, overflow: 'hidden' }}>
          {brand.logo ? brand.logo : (brand.name || 'A')[0]}
        </div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--fg-1)', lineHeight: 1.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{brand.name}</div>
          {brand.sub && <div style={{ fontSize: 11, color: 'var(--fg-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{brand.sub}</div>}
        </div>
      </div>
      <nav style={{ flex: 1, overflowY: 'auto', padding: '12px 10px', display: 'flex', flexDirection: 'column', gap: 4 }}>
        {nav.map((grp, gi) => (
          <div key={gi} style={{ marginBottom: 6 }}>
            {grp.section && <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--fg-3)', letterSpacing: '0.06em', textTransform: 'uppercase', padding: '8px 10px 5px' }}>{grp.section}</div>}
            {grp.items.map(it => {
              const on = active === it.id;
              return (
                <button key={it.id} onClick={() => { onNav(it.id); setMobileOpen(false); }}
                  style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '8px 10px', borderRadius: 'var(--r-sm)', border: 'none', background: on ? 'var(--brand-soft)' : 'transparent', color: on ? 'var(--brand)' : 'var(--fg-2)', fontSize: 13.5, fontWeight: on ? 600 : 500, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', transition: 'background 100ms', marginBottom: 1 }}
                  onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--bg-2)'; }}
                  onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent'; }}>
                  <span style={{ display: 'flex', flexShrink: 0 }}>{typeof it.icon === 'function' ? it.icon({ size: 18 }) : it.icon}</span>
                  <span style={{ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.label}</span>
                  {it.badge != null && <span className="tnum" style={{ fontSize: 11, fontWeight: 700, color: on ? 'var(--brand)' : 'var(--fg-3)', background: on ? 'var(--bg-0)' : 'var(--bg-2)', borderRadius: 9, padding: '1px 7px', minWidth: 20, textAlign: 'center' }}>{it.badge}</span>}
                </button>
              );
            })}
          </div>
        ))}
      </nav>
      {footer && <div style={{ padding: 12, borderTop: '1px solid var(--border)' }}>{footer}</div>}
    </aside>
  );

  return (
    <div style={{ display: 'flex', height: '100vh', overflow: 'hidden', background: 'var(--bg-2)' }}>
      {!narrow && Sidebar}
      {narrow && mobileOpen && (
        <div onMouseDown={e => { if (e.target === e.currentTarget) setMobileOpen(false); }} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.5)', zIndex: 500, display: 'flex' }}>
          <div style={{ animation: 'ds-sheet-in 220ms ease' }}>{Sidebar}</div>
        </div>
      )}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        <header style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '0 20px', height: 60, background: 'var(--bg-0)', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
          {narrow && <IconButton icon={Icon.menu} title="Menü" onClick={() => setMobileOpen(true)} />}
          <div style={{ minWidth: 0, flex: 1 }}>
            {title && <h1 style={{ fontSize: 18, fontWeight: 700, color: 'var(--fg-1)', lineHeight: 1.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</h1>}
            {subtitle && <div style={{ fontSize: 12.5, color: 'var(--fg-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{subtitle}</div>}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>{topRight}</div>
        </header>
        {banner}
        <main style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden' }}>
          <div style={{ maxWidth: 1320, margin: '0 auto', padding: '24px 20px 64px' }}>{children}</div>
        </main>
      </div>
    </div>
  );
}

Object.assign(window, { useUI, LangThemeControls, AppShell });
