// components.jsx — shared React components for Pinnacle Command Centre
// Exports to window.* for cross-file access (Babel in-browser scripts share via window)

const { useState, useEffect, useRef } = React;

/* ─── Icon ─────────────────────────────────────────────────────────── */
const ICON_PATHS = {
  home:      'M3 9.5L12 3l9 6.5V20a1 1 0 01-1 1H14v-5h-4v5H4a1 1 0 01-1-1V9.5z',
  users:     'M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2M9 11a4 4 0 100-8 4 4 0 000 8zM23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75',
  lead:      'M22 12h-4l-3 9L9 3l-3 9H2',
  wrench:    'M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z',
  car:       'M5 17H3a2 2 0 01-2-2V7a2 2 0 012-2h11l5 5v7a2 2 0 01-2 2h-2M5 17a2 2 0 104 0 2 2 0 00-4 0zM15 17a2 2 0 104 0 2 2 0 00-4 0z',
  globe:     'M12 2a10 10 0 100 20A10 10 0 0012 2zM2 12h20M12 2c-2.8 3-4 6.4-4 10s1.2 7 4 10M12 2c2.8 3 4 6.4 4 10s-1.2 7-4 10',
  money:     'M12 2v20M17 5H9.5a3.5 3.5 0 100 7h5a3.5 3.5 0 110 7H6',
  cal:       'M8 2v4M16 2v4M3 10h18M5 4h14a2 2 0 012 2v14a2 2 0 01-2 2H5a2 2 0 01-2-2V6a2 2 0 012-2z',
  doc:       'M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8zM14 2v6h6M16 13H8M16 17H8M10 9H8',
  chart:     'M18 20V10M12 20V4M6 20v-6',
  settings:  'M12 15a3 3 0 100-6 3 3 0 000 6zM19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83 0 2 2 0 010-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 010-2.83 2 2 0 012.83 0l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 0 2 2 0 010 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z',
  search:    'M21 21l-4.35-4.35M17 11A6 6 0 105 11a6 6 0 0012 0z',
  bell:      'M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 01-3.46 0',
  mail:      'M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2zM22 6l-10 7L2 6',
  signout:   'M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9',
  plus:      'M12 5v14M5 12h14',
  arrowUp:   'M18 15l-6-6-6 6',
  arrowDown: 'M6 9l6 6 6-6',
  check:     'M20 6L9 17l-5-5',
  alert:     'M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0zM12 9v4M12 17h.01',
  invoice:   'M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8zM14 2v6h6M8 13h8M8 17h4',
  download:  'M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3',
  edit:      'M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z',
  eye:       'M1 12S5 4 12 4s11 8 11 8-4 8-11 8S1 12 1 12zM12 15a3 3 0 100-6 3 3 0 000 6z',
  link:      'M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71',
  sun:       'M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41M12 16a4 4 0 100-8 4 4 0 000 8z',
  play:      'M5 3l14 9-14 9V3z',
  close:     'M18 6L6 18M6 6l12 12',
  sort:      'M3 6h18M7 12h10M11 18h2',
  filter:    'M22 3H2l8 9.46V19l4 2v-8.54L22 3z',
  chev:      'M9 18l6-6-6-6',
  drag:      'M9 3h6M9 21h6M3 9v6M21 9v6',
  bot:       'M12 2a2 2 0 012 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 017 7v3a4 4 0 01-4 4H7a4 4 0 01-4-4v-3a7 7 0 017-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 012-2zM9 14a1 1 0 100-2 1 1 0 000 2zM15 14a1 1 0 100-2 1 1 0 000 2z',
};

function Icon({ name, size = 20, color = 'currentColor', style: s }) {
  const d = ICON_PATHS[name];
  if (!d) return null;
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"
      style={s}>
      <path d={d} />
    </svg>
  );
}

/* ─── BrandLogo ─────────────────────────────────────────────────────── */
function BrandLogo({ size = 'md' }) {
  const sz = size === 'sm' ? 36 : size === 'md' ? 52 : 64;
  return (
    <div style={{
      width: sz, height: sz, flexShrink: 0,
      filter: 'drop-shadow(0 0 12px rgba(184,137,62,.6)) drop-shadow(0 2px 6px rgba(120,90,30,.35))'
    }}>
      <img src="pinnacle-p.png" alt="Pinnacle" style={{ width:'100%', height:'100%', objectFit:'contain' }} />
    </div>
  );
}

/* ─── initials + NameAvatar ─────────────────────────────────────────── */
function initials(name) {
  return name.split(' ').filter(Boolean).slice(0,2).map(w => w[0].toUpperCase()).join('');
}

function NameAvatar({ name, size = 32 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: 'var(--gold-gradient)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontWeight: 700, fontSize: Math.round(size * 0.38),
      color: 'var(--gold-700)', flexShrink: 0,
    }}>
      {initials(name)}
    </div>
  );
}

/* ─── KPI ───────────────────────────────────────────────────────────── */
function KPI({ label, value, currency, trend, trendDir = 'up', meta, flag }) {
  const trendClass = trendDir === 'up' ? 'trend-up' : trendDir === 'down' ? 'trend-down' : 'trend-flat';
  const trendArrow = trendDir === 'up' ? '↑' : trendDir === 'down' ? '↓' : '→';
  return (
    <div className={`card kpi${flag === 'ruby' ? ' kpi-ruby' : ''}`}>
      <div className="kpi-inner">
        <div className={`kpi-label${flag === 'ruby' ? ' kpi-label-ruby' : ''}`}>{label}</div>
        <div className="kpi-value">
          {currency && <span className="currency">{currency} </span>}
          {value}
        </div>
        {trend && (
          <div className={`kpi-trend ${trendClass}`}>{trendArrow} {trend}</div>
        )}
        {meta && <div style={{ fontSize:11, color:'var(--muted)', marginTop:6 }}>{meta}</div>}
      </div>
    </div>
  );
}

/* ─── StageBadge ────────────────────────────────────────────────────── */
function StageBadge({ stage }) {
  const map = {
    Lead:'badge-lead', Prospect:'badge-prospect', Demo:'badge-demo',
    Proposal:'badge-proposal', Onboarding:'badge-onboarding',
    Active:'badge-active', Churned:'badge-churned',
  };
  return <span className={`badge ${map[stage] || 'badge-lead'}`}>{stage}</span>;
}

/* ─── InvoiceBadge ──────────────────────────────────────────────────── */
function InvoiceBadge({ status }) {
  const s = String(status || '').toLowerCase();
  // Real DB statuses are lowercase: draft, sent, paid, overdue, cancelled.
  // (Legacy mock used Paid/Unpaid/Overdue — still handled.)
  const map = {
    paid:'badge-paid', sent:'badge-unpaid', draft:'badge-unpaid',
    overdue:'badge-overdue', cancelled:'badge-unpaid', unpaid:'badge-unpaid',
  };
  const label = s ? s.charAt(0).toUpperCase() + s.slice(1) : '—';
  return <span className={`badge ${map[s] || 'badge-unpaid'}`}>{label}</span>;
}

/* ─── PageHead ──────────────────────────────────────────────────────── */
function PageHead({ eyebrow, title, accent, lede, action, actions, live }) {
  // Accept both `action` (singular — used by every page) and `actions` (plural).
  const headActions = actions || action;
  const fmt = () => new Date().toLocaleTimeString('en-ZA', { hour:'2-digit', minute:'2-digit', hour12:false });
  const [time, setTime] = useState(fmt);
  useEffect(() => {
    if (!live) return;
    const t = setInterval(() => setTime(fmt()), 1000);
    return () => clearInterval(t);
  }, [live]);

  return (
    <div className="page-head">
      <div className="page-head-inner">
        <div className="page-head-eyebrow">{eyebrow}</div>
        <h1>
          {title}
          {accent && <> <span className="accent">{accent}</span></>}
        </h1>
        <div className="gold-rule" />
        {lede && <p className="page-head-lede">{lede}</p>}
        {live && (
          <div style={{ marginTop:12 }}>
            <div className="live-clock">{time}</div>
            <div className="live-status">
              <div className="pulse-dot" />
              Live · {time}
            </div>
          </div>
        )}
        {!live && headActions && <div className="page-head-actions">{headActions}</div>}
      </div>
    </div>
  );
}

/* ─── Card ──────────────────────────────────────────────────────────── */
function Card({ title, sub, action, children, flush, style: s }) {
  return (
    <div className="card" style={{ ...(flush ? { padding:0 } : {}), ...s }}>
      {(title || sub || action) && (
        <div className="card-content">
          <div className="card-head">
            <div>
              {sub   && <div className="card-sub">{sub}</div>}
              {title && <div className="card-title">{title}</div>}
            </div>
            {action && <div>{action}</div>}
          </div>
        </div>
      )}
      <div className={flush ? '' : 'card-content'}>
        {children}
      </div>
    </div>
  );
}

/* ─── Exports ───────────────────────────────────────────────────────── */
window.Icon         = Icon;
window.BrandLogo    = BrandLogo;
window.KPI          = KPI;
window.StageBadge   = StageBadge;
window.InvoiceBadge = InvoiceBadge;
window.PageHead     = PageHead;
window.Card         = Card;
window.NameAvatar   = NameAvatar;
window.initials     = initials;
