/* ELUCENS app — shell: monogram, sidebar, topbar */
const { Icon } = window;

function Mono({ size = 21, tile = false, tileSize, bg = '#0A312E', radius = 10 }) {
  const m = <span className="mono" style={{ fontSize: size, color: 'var(--on-dark)' }}>E<span className="dot"></span></span>;
  if (!tile) return m;
  const ts = tileSize || size * 1.8;
  return <span className="tile" style={{ width: ts, height: ts, background: bg, borderRadius: radius }}>{m}</span>;
}

function Wordmark({ size = 23, dark = true }) {
  return <span className={'wm' + (dark ? ' wm--dark' : '')} style={{ fontSize: size }}>Elucens<span className="dot"></span></span>;
}

function Sidebar({ view, setView, t, lang, navOpen, onClose }) {
  const nav = (id) => { setView(id); if (onClose) onClose(); };
  const item = (id, icon, label, opts = {}) => (
    <button className={'nav__item' + (view === id ? ' on' : '')} onClick={() => nav(id)}>
      <Icon name={icon} size={18} className="nav__ic" />
      <span>{label}</span>
      {opts.badge != null && opts.badge > 0 && <span className="badge">{opts.badge}</span>}
      {opts.live && <span className="dotlive"></span>}
      {opts.soon && <span className="dotlive" style={{ background: 'var(--on-dark-3)', boxShadow: 'none' }}></span>}
    </button>
  );
  return (
    <aside className={'side' + (navOpen ? ' is-open' : '')}>
      <div className="side__brand" onClick={() => nav('overview')} style={{ cursor: 'pointer' }} title="Naar overzicht">
        <Mono size={22} tile tileSize={40} radius={11} />
        <Wordmark size={24} />
      </div>

      <button className={'ask-cta' + (view === 'ask' ? ' on' : '')} onClick={() => nav('ask')}>
        <Icon name="spark" size={19} />
        <span>{t.ask}</span>
        <Icon name="arrow" size={17} className="ar" />
      </button>

      <nav className="nav">
        <div className="nav__grp">{t.grpMain}</div>
        {item('overview', 'grid', t.overview)}
        {item('actions', 'inbox', t.actions, { badge: ACTIONS.length })}
        {hasFeature('gesprekken') && item('calls', 'phone', t.calls, { badge: CALLS.reduce((n, c) => n + c.points.filter(p => p.s === 'open').length, 0) })}
        {item('result', 'bars', t.result)}

        <div className="nav__grp">{t.grpPillars}</div>
        {item('email', 'mail', 'E-mailtriage', { badge: MAIL_CATS.reduce((a, c) => a + (c.n || 0), 0) })}
        {item('quotes', 'file', 'Offertes', { live: true })}
        {item('invoicing', 'receipt', 'Facturatie', { live: true })}
        {item('crm', 'users', 'CRM', { live: true })}
        {item('forecast', 'trendUp', 'Voorraadprognose', { soon: true })}

        <div className="nav__grp">{t.grpData}</div>
        {item('integrations', 'plug', t.integrations)}
        {item('settings', 'settings', t.settings)}
      </nav>

      <div className="side__foot">
        <div className="acct" onClick={() => { window.location.href = '/app/logout'; }} title="Account & afmelden">
          <span className="acct__av">{USER.initials}</span>
          <span className="acct__meta">
            <span className="acct__name">{USER.name}</span>
            <span className="acct__role">{USER.role} · {TENANT.short}</span>
          </span>
          <Icon name="logout" size={16} style={{ color: 'var(--on-dark-3)', flex: '0 0 auto' }} />
        </div>
      </div>
    </aside>
  );
}

const CRUMBS = {
  overview: ['Overzicht'], ask: ['Vraag Elucens'], integrations: ['Data', 'Integraties'], actions: ['Acties'], result: ['Resultaat'], calls: ['Gesprekken'],
  email: ['Jouw pakket', 'E-mailtriage'], quotes: ['Jouw pakket', 'Offerte-automatisering'],
  invoicing: ['Jouw pakket', 'Facturatiekoppeling'], crm: ['Jouw pakket', 'CRM'],
  forecast: ['Jouw pakket', 'Voorraadprognose'], settings: ['Instellingen'],
};

// Real notifications come from the backend (bootstrap.notifs); empty until wired.
const NOTIFS = (typeof window !== 'undefined' && window.__ELUCENS_BOOTSTRAP__ && window.__ELUCENS_BOOTSTRAP__.notifs) || [];

function Topbar({ view, t, lang, setLang, theme, setTheme, onSearch, onMenu }) {
  const crumbs = CRUMBS[view] || ['Overzicht'];
  const [notifOpen, setNotifOpen] = React.useState(false);
  const [seen, setSeen] = React.useState(false);
  const unread = seen ? 0 : NOTIFS.filter(n => n.unread).length;
  const isDark = theme === 'dark';

  return (
    <header className="topbar">
      <button className="topbar__burger" onClick={onMenu} title="Menu"><Icon name="menu" size={20} /></button>
      <div className="crumb">
        <span>{TENANT.short}</span>
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            <Icon name="chevR" size={14} className="sep" />
            {i === crumbs.length - 1 ? <b>{c}</b> : <span>{c}</span>}
          </React.Fragment>
        ))}
      </div>

      <button className="search" onClick={onSearch}>
        <Icon name="search" size={17} />
        <span className="search__ph">{t.search}</span>
      </button>

      <div className="lang-toggle" style={{ display: 'inline-flex', gap: 2, background: 'var(--paper-3)', borderRadius: 999, padding: 3 }}>
        {['nl', 'en'].map(l => (
          <button key={l} onClick={() => setLang(l)} style={{
            fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, letterSpacing: '.04em',
            padding: '6px 12px', border: 0, borderRadius: 999, cursor: 'pointer', textTransform: 'uppercase',
            background: lang === l ? 'var(--paper-2)' : 'transparent',
            color: lang === l ? 'var(--ink)' : 'var(--ink-3)',
            boxShadow: lang === l ? '0 1px 3px rgba(0,0,0,.1)' : 'none',
          }}>{l}</button>
        ))}
      </div>

      <button className="iconbtn" onClick={() => setTheme(isDark ? 'light' : 'dark')} title={isDark ? 'Lichte modus' : 'Donkere modus'}>
        <Icon name={isDark ? 'sun' : 'moon'} size={18} />
      </button>

      <div className="menu-wrap">
        <button className="iconbtn" onClick={() => { setNotifOpen(o => !o); setSeen(true); }} title="Meldingen">
          <Icon name="bell" size={18} />
          {unread > 0 && <span className="ndot"></span>}
        </button>
        {notifOpen && (
          <React.Fragment>
            <div className="menu-overlay" onClick={() => setNotifOpen(false)}></div>
            <div className="menu">
              <div className="menu__h">
                <b>Meldingen</b>
                <button className="menu__clear" onClick={() => setNotifOpen(false)}><Icon name="check2" size={13} />Alles gelezen</button>
              </div>
              <div className="menu__list">
                {NOTIFS.length === 0 && (
                  <div className="notif" style={{ color: 'var(--ink-3)', fontSize: 14, justifyContent: 'center', padding: '24px 12px' }}>Geen nieuwe meldingen.</div>
                )}
                {NOTIFS.map((n, i) => (
                  <div className="notif" key={i}>
                    <span className={'fitem__ic' + (n.teal ? ' teal' : '')}><Icon name={n.ic} size={16} /></span>
                    <div className="fitem__b">
                      <div className="fitem__t">{n.t}</div>
                      <div className="fitem__m">{n.m}</div>
                    </div>
                    {n.unread && !seen && <span className="notif__dot"></span>}
                  </div>
                ))}
              </div>
            </div>
          </React.Fragment>
        )}
      </div>
    </header>
  );
}

Object.assign(window, { Mono, Wordmark, Sidebar, Topbar });
