/* ============================================================
   KODILA — App shell + routing + tema
   ============================================================ */

const NAV = [
  { route: 'dashboard', label: 'Nadzorna plošča', icon: 'grid' },
  { route: 'sifranti',  label: 'Šifranti',        icon: 'book', permission: 'sifranti' },
  { route: 'dokumenti', label: 'Dokumenti',       icon: 'file', permission: 'dokumenti' },
  { route: 'admin', label: 'Admin panel',         icon: 'settings', permission: 'admin' },
];

function csrfToken() {
  const meta = document.querySelector('meta[name="csrf-token"]');
  return meta ? meta.content : '';
}

function setCsrfToken(token) {
  if (!token) return;
  const meta = document.querySelector('meta[name="csrf-token"]');
  if (meta) meta.content = token;
}

async function api(path, options) {
  const opts = options || {};
  const headers = Object.assign({ 'Content-Type': 'application/json', 'X-CSRF-Token': csrfToken() }, opts.headers || {});
  const res = await fetch(path, Object.assign({}, opts, { headers, credentials: 'same-origin' }));
  const data = await res.json().catch(() => ({}));
  return { ok: res.ok, status: res.status, data };
}

function useTheme() {
  const [theme, setTheme] = useState(() => localStorage.getItem('kodila_theme') || 'light');
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('kodila_theme', theme);
  }, [theme]);
  return [theme, () => setTheme(t => t === 'dark' ? 'light' : 'dark')];
}

function visibleApps(user) {
  return APPS.filter(a => !a.roles || a.roles.includes(user.role));
}

function visibleNav(user, permissions) {
  return NAV.filter(n => !n.permission || permissions[n.permission]);
}

function TopBar({ route, onNav, user, permissions, theme, toggleTheme, onLogout }) {
  const toast = useToast();
  const moreApps = visibleApps(user).filter(a => !['sifranti', 'dokumenti'].includes(a.id));
  return (
    <header className="topbar">
      <div className="brand-mark" style={{ cursor: 'pointer' }} onClick={() => onNav('dashboard')}>
        <div className="brand-logo">K</div>
        <div>
          <div className="brand-name">KODILA</div>
          <div className="brand-sub">Intranet</div>
        </div>
      </div>

      <nav className="topnav">
        {visibleNav(user, permissions).map(n => (
          <a key={n.route} href="#" className={route === n.route ? 'active' : ''}
            onClick={(e) => { e.preventDefault(); onNav(n.route); }}>
            <span dangerouslySetInnerHTML={{ __html: I(n.icon, 17) }} />{n.label}
          </a>
        ))}
        {permissions.aplikacije && (
          <Dropdown align="left" width={300}
            trigger={(open) => (
              <a href="#" className={open ? 'active' : ''} onClick={e => e.preventDefault()}>
                <span dangerouslySetInnerHTML={{ __html: I('grid', 17) }} />Aplikacije
                <span dangerouslySetInnerHTML={{ __html: I('chevdown', 14) }} />
              </a>
            )}>
            <div className="dd-label">Vsi moduli</div>
            {moreApps.length === 0
              ? <div className="muted" style={{ padding: '10px 12px', fontSize: 12.5 }}>Trenutno ni dodatnih modulov.</div>
              : moreApps.map(a => (
                <button className="dd-item" key={a.id}
                  onClick={() => a.live ? onNav(a.route) : toast(a.name + ' — v pripravi', 'clock')}>
                  <span className="kpi-ico" style={{ ...tintStyle(a.tint), width: 28, height: 28 }}
                    dangerouslySetInnerHTML={{ __html: I(a.icon, 15) }} />
                  <span style={{ flex: 1 }}>{a.name}</span>
                  {!a.live && <span className="badge" style={{ height: 18, fontSize: 11 }}>kmalu</span>}
                </button>
              ))}
          </Dropdown>
        )}
      </nav>

      <div className="topbar-right">
        <div className="topsearch">
          <span dangerouslySetInnerHTML={{ __html: I('search', 15) }} />
          <input placeholder="Hitro iskanje…" onFocus={() => {}} />
          <kbd>⌘K</kbd>
        </div>
        <button className="btn btn-icon btn-ghost" onClick={toggleTheme} title="Svetla / temna tema"
          dangerouslySetInnerHTML={{ __html: I(theme === 'dark' ? 'sun' : 'moon', 18) }} />
        <button className="btn btn-icon btn-ghost" title="Obvestila" onClick={() => toast('3 nova obvestila', 'bell')}
          style={{ position: 'relative' }}>
          <span dangerouslySetInnerHTML={{ __html: I('bell', 18) }} />
          <span style={{ position: 'absolute', top: 7, right: 8, width: 7, height: 7, borderRadius: '50%', background: 'var(--danger)', border: '2px solid var(--surface)' }}></span>
        </button>

        <Dropdown align="right" width={210}
          trigger={() => (
            <button className="btn btn-ghost" style={{ gap: 9, paddingLeft: 6 }}>
              <span className="avatar">{user.fullName.split(' ').map(s => s[0]).join('')}</span>
              <span style={{ textAlign: 'left', lineHeight: 1.2 }}>
                <span style={{ display: 'block', fontWeight: 600, fontSize: 13 }}>{user.fullName}</span>
                <span style={{ display: 'block', fontSize: 11.5, color: 'var(--text-faint)' }}>{user.role === 'administrator' ? 'Administrator' : 'Zaposleni'}</span>
              </span>
              <span dangerouslySetInnerHTML={{ __html: I('chevdown', 14) }} />
            </button>
          )}>
          <div className="dd-label">{user.email}</div>
          <button className="dd-item" onClick={() => toast('Profil — kmalu')}>
            <span dangerouslySetInnerHTML={{ __html: I('users', 16) }} /> Moj profil
          </button>
          <button className="dd-item" onClick={() => toast('Nastavitve — kmalu')}>
            <span dangerouslySetInnerHTML={{ __html: I('settings', 16) }} /> Nastavitve
          </button>
          <div className="dd-sep"></div>
          <button className="dd-item" onClick={onLogout} style={{ color: 'var(--danger)' }}>
            <span dangerouslySetInnerHTML={{ __html: I('logout', 16) }} /> Odjava
          </button>
        </Dropdown>
      </div>
    </header>
  );
}

function App() {
  const [theme, toggleTheme] = useTheme();
  const [user, setUser] = useState(null);
  const [booting, setBooting] = useState(true);
  const [route, setRoute] = useState(() => localStorage.getItem('kodila_route') || 'dashboard');
  const [permissions, setPermissions] = useState({});

  const checkSession = React.useCallback(async () => {
    const { ok, data } = await api('/api/auth/me');
    window.__KODILA_USER__ = ok ? data.user : null;
    window.__KODILA_PERMISSIONS__ = ok ? data.permissions : {};
    setUser(ok ? data.user : null);
    setPermissions(ok ? data.permissions : {});
    if (ok) setCsrfToken(data.csrfToken);
    return ok;
  }, []);

  useEffect(() => {
    checkSession().finally(() => setBooting(false));
  }, [checkSession]);

  useEffect(() => {
    const onFocus = () => { checkSession(); };
    const interval = setInterval(checkSession, 5 * 60 * 1000);
    window.addEventListener('focus', onFocus);
    return () => { clearInterval(interval); window.removeEventListener('focus', onFocus); };
  }, [checkSession]);

  const nav = (r) => { setRoute(r); localStorage.setItem('kodila_route', r); window.scrollTo(0, 0); };
  const login = async (u, newCsrfToken) => { window.__KODILA_USER__ = u; setUser(u); setCsrfToken(newCsrfToken); await checkSession(); nav('dashboard'); };
  const logout = async () => {
    const { data } = await api('/api/auth/logout', { method: 'POST' });
    window.__KODILA_USER__ = null;
    window.__KODILA_PERMISSIONS__ = {};
    setUser(null);
    setPermissions({});
    setCsrfToken(data.csrfToken);
  };

  if (booting) {
    return <div style={{ minHeight: '100vh', background: 'var(--bg)' }} />;
  }

  if (!user) return <Login onLogin={login} theme={theme} toggleTheme={toggleTheme} />;

  const apps = visibleApps(user);
  const safeRoute =
    (route === 'admin' && !permissions.admin) ? 'dashboard' :
    (route === 'sifranti' && !permissions.sifranti) ? 'dashboard' :
    (route === 'dokumenti' && !permissions.dokumenti) ? 'dashboard' :
    route;

  return (
    <div className="shell">
      <TopBar route={safeRoute} onNav={nav} user={user} permissions={permissions} theme={theme} toggleTheme={toggleTheme} onLogout={logout} />
      <div className="content">
        {safeRoute === 'dashboard' && <Dashboard user={user} onOpen={nav} apps={apps} />}
        {safeRoute === 'sifranti' && permissions.sifranti && <Sifranti currentUser={user} />}
        {safeRoute === 'dokumenti' && permissions.dokumenti && <Dokumenti />}
        {safeRoute === 'admin' && permissions.admin && <AdminPanel currentUser={user} />}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <ToastProvider><App /></ToastProvider>
);
