// App shell: Login, Sidebar, Topbar, Cmd-K

const NAV_SECTIONS = [
  { id: 'home',       label: 'Dashboard',     icon: 'home',      group: 'main' },

  { id: 'hrm',        label: 'People',        icon: 'users',     group: 'hr',   count: 28 },

  { id: 'crm',        label: 'CRM',           icon: 'card',      group: 'rev',  count: 11 },
  { id: 'customers',  label: 'Customers',     icon: 'store',     group: 'rev' },
  { id: 'contracts',  label: 'Contracts',     icon: 'doc',       group: 'rev',  count: 19 },

  { id: 'finance',    label: 'Finance',       icon: 'chart',     group: 'fin' },
  { id: 'vendors',    label: 'Vendors',       icon: 'briefcase', group: 'fin' },
  { id: 'fin-invoices', label: 'Invoices',     icon: 'doc',       group: 'fin' },
  { id: 'fin-bills',  label: 'Bills',          icon: 'card',      group: 'fin' },
  { id: 'fin-banking', label: 'Banking',       icon: 'store',     group: 'fin' },
  { id: 'fin-ledger', label: 'General ledger', icon: 'layers',    group: 'fin' },
  { id: 'fin-reports', label: 'Reports',       icon: 'briefcase', group: 'fin' },

  { id: 'innovation', label: 'Innovation',    icon: 'spark',     group: 'ops',  count: 12 },
  { id: 'licenses',   label: 'Software',       icon: 'key',       group: 'ops',  count: 16 },
  { id: 'files',      label: 'Files',         icon: 'folder',    group: 'ops' },

  { id: 'settings',   label: 'Settings',      icon: 'settings',  group: 'sys' },
];

function HitcentsMark({ size = 32 }) {
  // Inline stylized H mark — abstract, references the slash through it
  return (
    <svg width={size} height={size} viewBox="0 0 40 40" aria-hidden="true">
      <rect x="0" y="0" width="40" height="40" rx="9" fill="#E0552B"/>
      <path d="M11 8 V32 H15 V22 H25 V32 H29 V8 H25 V18 H15 V8 Z" fill="#fff"/>
      <path d="M6 23 L34 14 L34 17 L6 26 Z" fill="#E0552B"/>
    </svg>
  );
}

function Sidebar({ active, onNavigate, collapsed, user, onSignOut }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const groups = [
    { id: 'main',   label: 'Workspace' },
    { id: 'hr',     label: 'HR' },
    { id: 'rev',    label: 'Revenue' },
    { id: 'fin',    label: 'Finance' },
    { id: 'ops',    label: 'Operations' },
    { id: 'sys',    label: 'System' },
  ];

  useEffect(() => {
    if (!menuOpen) return;
    const close = () => setMenuOpen(false);
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [menuOpen]);

  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <HitcentsMark size={32} />
        <div className="sidebar-brand-text">
          <strong>HITCENTS</strong>
          <span>Operations</span>
        </div>
      </div>

      <nav className="sidebar-nav">
        {groups.map(g => (
          <React.Fragment key={g.id}>
            <div className="sidebar-section-label">{g.label}</div>
            {NAV_SECTIONS.filter(n => n.group === g.id).map(item => (
              <div
                key={item.id}
                className={`nav-item ${active === item.id ? 'active' : ''} ${item.sub ? 'nav-sub' : ''}`}
                onClick={() => onNavigate(item.id)}
                title={item.label}>
                <Icon name={item.icon} size={16} stroke={1.7} />
                <span>{item.label}</span>
                {item.count != null && <span className="nav-count">{item.count}</span>}
              </div>
            ))}
          </React.Fragment>
        ))}
      </nav>

      <div className="sidebar-foot-wrap">
        {menuOpen && (
          <div className="user-menu" onClick={e => e.stopPropagation()}>
            <button className="user-menu-item" onClick={() => { setMenuOpen(false); pickAvatarImage(user.id); }}>
              <Icon name="upload" size={15} /> Upload profile picture
            </button>
            <button className="user-menu-item" onClick={() => { setMenuOpen(false); onNavigate('settings'); }}>
              <Icon name="settings" size={15} /> Account settings
            </button>
            <div className="user-menu-sep" />
            <button className="user-menu-item danger" onClick={() => { setMenuOpen(false); onSignOut && onSignOut(); }}>
              <Icon name="lock" size={15} /> Log out
            </button>
          </div>
        )}
        <button className={`sidebar-foot ${menuOpen ? 'open' : ''}`}
                onClick={(e) => { e.stopPropagation(); setMenuOpen(o => !o); }}
                title="Account">
          <Avatar person={user} size={32} />
          <div className="who">
            <strong>{user?.name || 'Sign in'}</strong>
            <span>{user?.title || '—'}</span>
          </div>
          <Icon name="chev_u" size={14} className="sidebar-foot-caret" />
        </button>
      </div>
    </aside>
  );
}

function Topbar({ section, user, role, onRoleClick, onSearch, onCmdK, onChatToggle, chatUnread, onAIToggle, onCreate }) {
  const sectionName = NAV_SECTIONS.find(n => n.id === section)?.label || '';
  const group = (NAV_SECTIONS.find(n => n.id === section) || {}).group || null;
  return (
    <header className="topbar">
      <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>
        <span style={{ color: 'var(--text)' }}>Hitcents</span>
        <span style={{ margin: '0 8px', color: 'var(--text-dim)' }}>/</span>
        <span style={{ color: 'var(--text)', fontWeight: 500 }}>{sectionName}</span>
      </div>

      <div className="search" onClick={onCmdK} style={{ marginLeft: 24 }}>
        <Icon name="search" size={14} />
        <span style={{ fontSize: 13 }}>Search anything…</span>
        <span style={{ marginLeft: 'auto', display: 'flex', gap: 4 }}>
          <Kbd>⌘</Kbd><Kbd>K</Kbd>
        </span>
      </div>

      <div className="right">
        <Button variant="primary" icon="plus" onClick={() => onCreate(group)}>Create</Button>
        <button className="topbar-ai" title="Ask Cents — your in-house AI" onClick={onAIToggle}>
          <CentsMark size={14} />
          <span>Ask Cents</span>
          <Kbd>⌘J</Kbd>
        </button>
        <button className="icon-btn" title="Chat" onClick={onChatToggle}>
          <Icon name="chat" size={16} />
          {chatUnread > 0 && <span className="dot" />}
        </button>
      </div>
    </header>
  );
}

function Login({ onSignin, onUseDemo }) {
  const [email, setEmail] = useState('maren@hitcents.com');
  const [pwd, setPwd] = useState('••••••••••••');
  const [remember, setRemember] = useState(true);

  return (
    <div className="login-shell">
      <div className="login-art">
        <div style={{ position: 'relative', zIndex: 1 }}>
          <div className="row" style={{ gap: 12 }}>
            <HitcentsMark size={42} />
            <div>
              <div style={{ fontWeight: 700, fontSize: 18, letterSpacing: '0.04em' }}>HITCENTS</div>
              <div style={{ fontSize: 11, color: 'var(--text-on-dark-dim)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>Internal Operations</div>
            </div>
          </div>
        </div>

        <div style={{ position: 'relative', zIndex: 1 }}>
          <h1 style={{ fontSize: 40, lineHeight: 1.1, margin: '0 0 14px', letterSpacing: '-0.02em', fontWeight: 600, maxWidth: 440 }}>
            One workspace<br/>for the entire company.
          </h1>
          <p style={{ color: 'var(--text-on-dark-dim)', maxWidth: 420, fontSize: 14.5, lineHeight: 1.55 }}>
            People, projects, customers, support, ideas, and the marketing motion behind them — all in one place. Built for Hitcents.
          </p>

          <div style={{ display: 'flex', gap: 24, marginTop: 32, flexWrap: 'wrap' }}>
            {[
              { k: '28', l: 'Employees' },
              { k: '8', l: 'Active projects' },
              { k: '$1.06M', l: 'Open pipeline' },
              { k: '99.94%', l: 'SLA this month' },
            ].map(s => (
              <div key={s.l}>
                <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: '-0.02em' }}>{s.k}</div>
                <div style={{ fontSize: 11.5, color: 'var(--text-on-dark-dim)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.l}</div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ position: 'relative', zIndex: 1, fontSize: 12, color: 'var(--text-on-dark-dim)' }}>
          © 2026 Hitcents · Single sign-on via Okta · v4.2.1
        </div>

        <div className="blob" />
      </div>

      <div className="login-form">
        <div className="login-form-inner">
          <h2 style={{ fontSize: 22, margin: '0 0 6px', fontWeight: 600, letterSpacing: '-0.015em' }}>Welcome back</h2>
          <div className="muted" style={{ marginBottom: 24, fontSize: 13.5 }}>Sign in to your Hitcents account.</div>

          <div className="field">
            <label>Work email</label>
            <input value={email} onChange={e => setEmail(e.target.value)} type="email" />
          </div>
          <div className="field">
            <label style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span>Password</span>
              <a className="muted" style={{ fontSize: 11 }}>Forgot?</a>
            </label>
            <input value={pwd} onChange={e => setPwd(e.target.value)} type="password" />
          </div>

          <label className="row gap-2" style={{ marginBottom: 18, fontSize: 13, color: 'var(--text-muted)' }}>
            <input type="checkbox" checked={remember} onChange={e => setRemember(e.target.checked)} />
            Remember this device for 30 days
          </label>

          <Button variant="primary" size="lg" className="" style={{ width: '100%', justifyContent: 'center' }} onClick={() => onSignin(email)}>
            Sign in
          </Button>
        </div>
      </div>
    </div>
  );
}

function CmdK({ open, onClose, onNavigate, onOpenObject }) {
  const [q, setQ] = useState('');
  const [active, setActive] = useState(0);
  const inputRef = useRef();

  useEffect(() => {
    if (open && inputRef.current) inputRef.current.focus();
    if (open) { setQ(''); setActive(0); }
  }, [open]);

  const items = useMemo(() => {
    const all = [];
    NAV_SECTIONS.forEach(s => all.push({ kind: 'Pages', label: `Go to ${s.label}`, target: { type: 'nav', id: s.id }, icon: s.icon }));
    window.HitcentsData.EMPLOYEES.forEach(e => all.push({ kind: 'People', label: e.name, sub: e.title, target: { type: 'employee', id: e.id }, icon: 'users' }));
    window.HitcentsData.CUSTOMERS.forEach(c => all.push({ kind: 'Customers', label: c.name, sub: c.industry, target: { type: 'customer', id: c.id }, icon: 'store' }));

    if (!q.trim()) return all.slice(0, 24);
    const ql = q.toLowerCase();
    return all.filter(it => it.label.toLowerCase().includes(ql) || (it.sub && it.sub.toLowerCase().includes(ql))).slice(0, 40);
  }, [q]);

  const grouped = useMemo(() => {
    const map = {};
    items.forEach(it => { (map[it.kind] = map[it.kind] || []).push(it); });
    return map;
  }, [items]);

  useEffect(() => {
    if (!open) return;
    function onKey(e) {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(items.length - 1, a + 1)); }
      else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(a => Math.max(0, a - 1)); }
      else if (e.key === 'Enter') {
        const it = items[active];
        if (it) { handleSelect(it); }
      }
    }
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, active, items, onClose]);

  function handleSelect(it) {
    if (it.target.type === 'nav') onNavigate(it.target.id);
    else if (it.target.type === 'employee') { onNavigate('hrm'); onOpenObject(it.target); }
    else if (it.target.type === 'customer') { onNavigate('customers'); onOpenObject(it.target); }
    onClose();
  }

  if (!open) return null;
  let idx = -1;
  return (
    <div className="cmdk-scrim" onClick={onClose}>
      <div className="cmdk" onClick={e => e.stopPropagation()}>
        <div className="cmdk-input">
          <Icon name="search" size={18} />
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} placeholder="Search pages, people, customers…" />
          <Kbd>esc</Kbd>
        </div>
        <div className="cmdk-list">
          {Object.entries(grouped).map(([group, gItems]) => (
            <div key={group}>
              <div className="cmdk-group-label">{group}</div>
              {gItems.map(it => {
                idx++;
                return (
                  <div key={it.label + idx} className={`cmdk-item ${idx === active ? 'active' : ''}`}
                       onMouseEnter={() => setActive(idx)}
                       onClick={() => handleSelect(it)}>
                    <Icon name={it.icon} size={14} style={{ color: 'var(--text-muted)' }} />
                    <div style={{ minWidth: 0 }}>
                      <div>{it.label}</div>
                      {it.sub && <div className="dim" style={{ fontSize: 11.5 }}>{it.sub}</div>}
                    </div>
                    <span className="meta">↵</span>
                  </div>
                );
              })}
            </div>
          ))}
          {items.length === 0 && (
            <div style={{ padding: '40px 20px', textAlign: 'center', color: 'var(--text-muted)' }}>No results for "{q}"</div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Sidebar, Topbar, Login, CmdK, NAV_SECTIONS, HitcentsMark });
