const NAV = [
  ['dashboard', 'Dashboard', 'home', 'Overview'],
  ['customers', 'Database Customer', 'users', 'CRM'],
  ['detail', 'Customer Detail', 'user', 'CRM'],
  ['communications', 'Histori Komunikasi', 'chat', 'CRM'],
  ['pipeline', 'Follow Up Pipeline', 'pipeline', 'Sales'],
  ['activity', 'Activity Tracking', 'activity', 'Sales'],
  ['segments', 'Customer Segmentation', 'segment', 'Insights'],
  ['reminders', 'Reminder & Notifikasi', 'bell', 'Productivity'],
  ['email', 'Email Integration', 'mail', 'Productivity'],
  ['tickets', 'Customer Support', 'ticket', 'Service'],
  ['sales', 'Sales Performance', 'chart', 'Insights'],
];

const NAV_GROUPS = ['Overview', 'CRM', 'Sales', 'Insights', 'Productivity', 'Service'];

function Sidebar({ ctx }) {
  return (
    <aside className="sidebar">
      <button className="brand" onClick={() => ctx.go('dashboard')}>
        <span className="brand-mark"><Icon name="sparkle" size={20} /></span>
        <span><b>Relate</b><small>Customer Platform</small></span>
      </button>
      <nav className="nav-list">
        {NAV_GROUPS.map(group => (
          <div key={group} className="nav-group">
            <span className="nav-group-label">{group}</span>
            {NAV.filter(n => n[3] === group).map(([id, label, icon]) => (
              <button key={id} className={`nav-item ${ctx.page === id ? 'active' : ''}`} onClick={() => ctx.go(id)}>
                <Icon name={icon} size={16} /> {label}
              </button>
            ))}
          </div>
        ))}
      </nav>
      <div className="sidebar-card">
        <span className="pulse" />
        <b>Trial Premium</b>
        <p>22 hari tersisa. Upgrade untuk akses unlimited workspace.</p>
        <button className="btn-mini">Upgrade →</button>
      </div>
    </aside>
  );
}

function Topbar({ ctx }) {
  const current = NAV.find(x => x[0] === ctx.page);
  return (
    <header className="topbar">
      <div>
        <span className="eyebrow">{current?.[3] || 'Relate'} · Workspace Jakarta</span>
        <h1>{current?.[1] || 'Relate CRM'}</h1>
      </div>
      <div className="top-actions">
        <button className="searchbar"><Icon name="search" size={15} /> Cari customer, deal, atau ticket…<kbd>⌘K</kbd></button>
        <button className="icon-btn" title="Tambah"><Icon name="plus" size={17} /></button>
        <button className="icon-btn" title="Notifikasi"><Icon name="bell" size={17} /><span className="dot-red" /></button>
        <button className="avatar">RW</button>
      </div>
    </header>
  );
}

function Section({ eyebrow, title, action, children }) {
  return (
    <section className="section">
      <div className="section-head">
        <div>{eyebrow && <span className="eyebrow">{eyebrow}</span>}<h2>{title}</h2></div>
        {action}
      </div>
      {children}
    </section>
  );
}

function Stat({ label, value, delta, tone = 'indigo', icon }) {
  const pos = (delta || '').startsWith('+');
  return (
    <div className={`stat-card ${tone}`}>
      <div className="stat-head">
        <span>{label}</span>
        {icon && <span className="stat-icon"><Icon name={icon} size={15} /></span>}
      </div>
      <b>{value}</b>
      {delta && <small className={pos ? 'pos' : 'neg'}>{delta} vs bulan lalu</small>}
    </div>
  );
}

function Avatar({ name = '?', tone = 'indigo', size }) {
  const init = name.split(' ').map(w => w[0]).slice(0, 2).join('').toUpperCase();
  const style = size ? { width: size, height: size, fontSize: size * 0.42 } : null;
  return <span className={`avatar-mini ${tone}`} style={style}>{init}</span>;
}

function StatusPill({ tone, children }) {
  return <span className={`status-pill ${tone}`}>{children}</span>;
}

function Spark({ data = [], color = '#2563eb', height = 36 }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => `${(i / (data.length - 1)) * 100},${100 - ((v - min) / range) * 100}`).join(' ');
  return (
    <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ width: '100%', height }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="2.5" />
    </svg>
  );
}

function BarChart({ data = [], color = '#4f46e5', height = 160 }) {
  const max = Math.max(...data.map(d => d.v));
  return (
    <div className="bar-chart" style={{ height }}>
      {data.map((d, i) => (
        <div key={i} className="bar-col">
          <div className="bar-fill" style={{ height: (d.v / max) * 100 + '%', background: color }} title={d.m + ': ' + d.v} />
          <span>{d.m}</span>
        </div>
      ))}
    </div>
  );
}

function ChannelIcon({ ch }) {
  const map = { email: 'mail', wa: 'wa', call: 'phone', meeting: 'meeting', note: 'note' };
  return <Icon name={map[ch] || 'chat'} size={15} />;
}

Object.assign(window, {
  NAV, NAV_GROUPS, Sidebar, Topbar, Section, Stat, Avatar, StatusPill, Spark, BarChart, ChannelIcon,
});
