// Shared UI primitives for Regula

// ───────────────────────────── Icons (minimal, 1.5px)
const Icon = ({ name, size = 14 }) => {
  const paths = {
    home: <><path d="M3 10.5L9 3l6 7.5M4.5 9v6.5h9V9" /></>,
    building: <><rect x="3" y="2.5" width="12" height="13" /><path d="M6 6h2M6 9h2M6 12h2M10 6h2M10 9h2M10 12h2" /></>,
    chat: <><path d="M2.5 4.5h13v8h-5l-3 2.5V12.5H2.5z" /></>,
    book: <><path d="M3 3v12h4a2 2 0 012 2V5a2 2 0 00-2-2H3zM15 3v12h-4a2 2 0 00-2 2V5a2 2 0 012-2h4z" /></>,
    search: <><circle cx="8" cy="8" r="4.5" /><path d="M11.5 11.5L14.5 14.5" /></>,
    settings: <><circle cx="9" cy="9" r="2" /><path d="M9 2v2M9 14v2M2 9h2M14 9h2M4 4l1.5 1.5M12.5 12.5L14 14M4 14l1.5-1.5M12.5 5.5L14 4" /></>,
    plus: <><path d="M9 3v12M3 9h12" /></>,
    arrow: <><path d="M6 3l5 6-5 6" /></>,
    up: <><path d="M4 10l5-5 5 5" /></>,
    down: <><path d="M4 6l5 5 5-5" /></>,
    clock: <><circle cx="9" cy="9" r="6" /><path d="M9 5v4l2.5 2" /></>,
    file: <><path d="M4 2.5h6l3 3v10H4z" /><path d="M10 2.5v3h3" /></>,
    upload: <><path d="M9 12V3M5 7l4-4 4 4M3 13v2.5h12V13" /></>,
    send: <><path d="M3 9l12-6-5 12-2-5-5-1z" /></>,
    sparkle: <><path d="M9 2l1.5 4L14.5 7.5 10.5 9 9 13l-1.5-4L3.5 7.5 7.5 6z" /></>,
    download: <><path d="M9 3v9M5 8l4 4 4-4M3 14h12" /></>,
    filter: <><path d="M3 4h12l-4.5 6v4l-3 1.5V10z" /></>,
    more: <><circle cx="4" cy="9" r="0.75" fill="currentColor" /><circle cx="9" cy="9" r="0.75" fill="currentColor" /><circle cx="14" cy="9" r="0.75" fill="currentColor" /></>,
    close: <><path d="M4 4l10 10M14 4L4 14" /></>,
    bell: <><path d="M9 2.5a4 4 0 00-4 4v3l-1.5 2.5h11L13 9.5v-3a4 4 0 00-4-4zM7.5 14a1.5 1.5 0 003 0" /></>,
    check: <><path d="M4 9l3 3 7-7" /></>,
    edit: <><path d="M3 12.5V15h2.5l8-8-2.5-2.5-8 8z" /></>,
    expand: <><path d="M3 3h5M3 3v5M15 15h-5M15 15v-5" /></>,
    drag: <><circle cx="6" cy="5" r="0.8" fill="currentColor" /><circle cx="6" cy="9" r="0.8" fill="currentColor" /><circle cx="6" cy="13" r="0.8" fill="currentColor" /><circle cx="12" cy="5" r="0.8" fill="currentColor" /><circle cx="12" cy="9" r="0.8" fill="currentColor" /><circle cx="12" cy="13" r="0.8" fill="currentColor" /></>
  };
  return (
    <svg width={size} height={size} viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round" style={{ flex: 'none' }}>
      {paths[name]}
    </svg>
  );
};

// ───────────────────────────── Sparkline
const Sparkline = ({ data, w = 84, h = 28, color = 'var(--ink)', fill = false }) => {
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const step = w / (data.length - 1);
  const pts = data.map((v, i) => [i * step, h - ((v - min) / range) * (h - 4) - 2]);
  const d = pts.map((p, i) => (i === 0 ? 'M' : 'L') + p[0].toFixed(1) + ',' + p[1].toFixed(1)).join(' ');
  const areaD = d + ` L${w},${h} L0,${h} Z`;
  return (
    <svg width={w} height={h} style={{ overflow: 'visible' }}>
      {fill && <path d={areaD} fill={color} opacity="0.08" />}
      <path d={d} stroke={color} strokeWidth="1.25" fill="none" />
      <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="2" fill={color} />
    </svg>
  );
};

// ───────────────────────────── Delta
const Delta = ({ value, abs, invert = false }) => {
  const positive = invert ? value < 0 : value > 0;
  const negative = invert ? value > 0 : value < 0;
  const cls = positive ? 'up' : negative ? 'down' : 'flat';
  const arrow = positive ? '↑' : negative ? '↓' : '·';
  return (
    <span className={`delta ${cls}`}>
      <span>{arrow}</span>
      <span>{value > 0 ? '+' : ''}{value.toFixed(1)}%</span>
      {abs && <span style={{ opacity: 0.7, marginLeft: 3 }}>{abs}</span>}
    </span>
  );
};

// ───────────────────────────── Sidebar
const Sidebar = ({ page, setPage, activeCompanyId, setActiveCompanyId }) => {
  const { companies } = window.REGULA_DATA;
  const sections = [
    { id: 'dashboard', label: 'Cockpit', icon: 'home' },
    { id: 'detail', label: 'Società', icon: 'building', count: companies.length },
    { id: 'tesoreria', label: 'Tesoreria', icon: 'clock' },
    { id: 'forecasting', label: 'Forecasting', icon: 'up' },
    { id: 'investimenti', label: 'Investimenti', icon: 'book' },
    { id: 'allocazione', label: 'Allocazione Capitali', icon: 'arrow' },
    { id: 'assistant', label: 'AI Assistant', icon: 'sparkle' },
    { id: 'kb', label: 'Knowledge Base', icon: 'file', count: 124 }
  ];
  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark">R</div>
        <div>
          <div className="brand-name">Regula</div>
          <div className="brand-sub">Patrimonio</div>
        </div>
      </div>

      <div className="nav-group">
        {sections.map(s => (
          <div key={s.id} className={`nav-item ${page === s.id ? 'active' : ''}`} onClick={() => setPage(s.id)}>
            <span className="nav-icon"><Icon name={s.icon} /></span>
            <span>{s.label}</span>
            {s.count != null && <span className="nav-count">{s.count}</span>}
          </div>
        ))}
      </div>

      <div className="nav-group">
        <div className="nav-label">Società</div>
        {companies.map(c => (
          <div
            key={c.id}
            className={`side-company ${activeCompanyId === c.id && page === 'detail' ? 'active' : ''}`}
            onClick={() => { setActiveCompanyId(c.id); setPage('detail'); }}
          >
            <div className="side-company-dot" style={{ background: c.color }} />
            <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</span>
          </div>
        ))}
      </div>

      <div className="nav-group">
        <div className="nav-label">Sistema</div>
        <div className="nav-item">
          <span className="nav-icon"><Icon name="bell" /></span>
          <span>Alert</span>
          <span className="nav-count" style={{ color: 'var(--red)' }}>2</span>
        </div>
        <div className="nav-item">
          <span className="nav-icon"><Icon name="settings" /></span>
          <span>Impostazioni</span>
        </div>
      </div>

      <div className="sidebar-footer">
        <div className="user-chip">
          <div className="avatar">LC</div>
          <div style={{ flex: 1, overflow: 'hidden' }}>
            <div style={{ fontSize: 12, fontWeight: 500 }}>Lorenzo Castelli</div>
            <div style={{ fontSize: 10, color: 'var(--muted)', fontFamily: 'var(--f-mono)' }}>Group Patrimony Mgr</div>
          </div>
        </div>
      </div>
    </aside>
  );
};

// ───────────────────────────── Horizon switch (global)
const HorizonSwitch = ({ horizon, setHorizon }) => {
  const opts = [
    { id: 'operativo', label: 'Operativo', sub: 'settimana · mese' },
    { id: 'tattico', label: 'Tattico', sub: 'trimestre · anno' },
    { id: 'strategico', label: 'Strategico', sub: '3–5 anni' }
  ];
  return (
    <div style={{ display: 'inline-flex', background: 'var(--surface-2)', borderRadius: 'var(--r-sm)', padding: 2, gap: 2 }}>
      {opts.map(o => (
        <button key={o.id} onClick={() => setHorizon(o.id)}
          style={{
            padding: '4px 10px', borderRadius: 3,
            background: horizon === o.id ? 'var(--surface)' : 'transparent',
            color: horizon === o.id ? 'var(--ink)' : 'var(--muted)',
            boxShadow: horizon === o.id ? 'var(--shadow-sm)' : 'none',
            fontFamily: 'var(--f-sans)',
            display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1.1
          }}>
          <span style={{ fontSize: 11, fontWeight: 500 }}>{o.label}</span>
          <span style={{ fontFamily: 'var(--f-mono)', fontSize: 9, opacity: 0.7, letterSpacing: '0.02em' }}>{o.sub}</span>
        </button>
      ))}
    </div>
  );
};

// ───────────────────────────── Topbar
const Topbar = ({ crumbs, meta, horizon, setHorizon }) => (
  <div className="topbar">
    <div className="breadcrumb">
      {crumbs.map((c, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span className="sep">/</span>}
          <span className={i === crumbs.length - 1 ? 'current' : ''}>{c}</span>
        </React.Fragment>
      ))}
    </div>
    <div className="topbar-spacer" />
    {horizon !== undefined && <HorizonSwitch horizon={horizon} setHorizon={setHorizon} />}
    {meta}
    <div className="btn" style={{ gap: 8 }}>
      <Icon name="search" size={12} />
      <span style={{ color: 'var(--muted)' }}>Cerca</span>
      <span className="kbd">⌘K</span>
    </div>
  </div>
);

// ───────────────────────────── Integrations footer
const IntegrationsBar = () => {
  const items = window.REGULA_EXT?.integrations || [];
  return (
    <div style={{ borderTop: '1px solid var(--border)', padding: '10px 24px', background: 'var(--bg)', display: 'flex', alignItems: 'center', gap: 16, fontSize: 11 }}>
      <span style={{ fontFamily: 'var(--f-mono)', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--muted-2)' }}>Integrazioni</span>
      {items.map((it, i) => (
        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <div style={{
            width: 18, height: 18, borderRadius: 3,
            background: it.status === 'ok' ? 'var(--surface-2)' : 'var(--amber-soft)',
            color: it.status === 'ok' ? 'var(--ink-2)' : 'var(--amber)',
            display: 'grid', placeItems: 'center',
            fontFamily: 'var(--f-mono)', fontSize: 8, fontWeight: 600,
            border: '1px solid var(--border)'
          }}>{it.mark}</div>
          <span style={{ fontSize: 11 }}>{it.name}</span>
          <span className={`status-dot ${it.status === 'ok' ? 'green' : 'amber'}`} style={{ width: 5, height: 5 }} />
          <span style={{ fontFamily: 'var(--f-mono)', fontSize: 9, color: 'var(--muted)' }}>{it.lastSync}</span>
        </div>
      ))}
      <div style={{ flex: 1 }} />
      <button className="btn" style={{ fontSize: 10, padding: '3px 8px' }}>Settings</button>
    </div>
  );
};

Object.assign(window, { Icon, Sparkline, Delta, Sidebar, Topbar, HorizonSwitch, IntegrationsBar });
