// ── OM Group Premium KPI Card System ─────────────────────────────────────────
// Provides: LucideIcon renderer, getIconBg helper, KPI_ICON_MAP lookup
// Loaded before dashboard.jsx and group-dashboard.jsx
// All exports attached to window for cross-script access
// ─────────────────────────────────────────────────────────────────────────────

// ── Lucide Outline Icon Renderer ──────────────────────────────────────────────
// Reads icon data from window.lucide (UMD build) and renders a clean inline SVG.
// Falls back to null gracefully if the icon or library isn't loaded.
function LucideIcon({ name, size, strokeWidth, color }) {
  if (!name || !window.lucide) return null;
  const data = window.lucide[name];
  if (!data || !Array.isArray(data) || data.length === 0) return null;
  const sz = size || 22;
  const sw = strokeWidth || 2;
  const cl = color || 'currentColor';
  // Lucide UMD exports icons as a flat array of [tag, attrs] tuples
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width={sz}
      height={sz}
      viewBox="0 0 24 24"
      fill="none"
      stroke={cl}
      strokeWidth={sw}
      strokeLinecap="round"
      strokeLinejoin="round"
      style={{ display: 'block', flexShrink: 0 }}
    >
      {data.map((child, i) => {
        if (!Array.isArray(child)) return null;
        const [tag, attrs = {}] = child;
        return React.createElement(tag, { key: i, ...attrs });
      })}
    </svg>
  );
}

// ── Icon Background Tint ──────────────────────────────────────────────────────
// Returns a semi-transparent rgba matching the KPI's accent color at 7-8% opacity.
function getIconBg(color) {
  const map = {
    'var(--or)':   'rgba(249,115,22,0.08)',
    'var(--or2)':  'rgba(234,88,12,0.08)',
    'var(--ok)':   'rgba(22,163,74,0.08)',
    'var(--err)':  'rgba(220,38,38,0.08)',
    'var(--info)': 'rgba(37,99,235,0.08)',
    'var(--warn)': 'rgba(217,119,6,0.08)',
    'var(--txt)':  'rgba(249,115,22,0.06)',
    'var(--txt2)': 'rgba(107,112,104,0.08)',
  };
  if (map[color]) return map[color];
  if (color && color.startsWith('#') && color.length === 7) {
    const r = parseInt(color.slice(1,3),16);
    const g = parseInt(color.slice(3,5),16);
    const b = parseInt(color.slice(5,7),16);
    return `rgba(${r},${g},${b},0.08)`;
  }
  return 'rgba(249,115,22,0.07)';
}

// ── KPI Label → Lucide Icon Map ───────────────────────────────────────────────
// Every KPI card label maps to an exact Lucide PascalCase icon name.
// Icons are outline only, 22px, 2px stroke — per OM Group design spec.
const KPI_ICON_MAP = {
  // ── Financial Performance ─────────────────────────────────────────────────
  'Total Revenue':              'BadgeIndianRupee',
  'Revenue':                    'Landmark',
  'Purchase Cost':              'WalletCards',
  'Gross Profit':               'TrendingUp',
  'Net Profit':                  'PiggyBank',
  'Profit Margin':              'Percent',
  'Profit Per Ton':             'Coins',
  'Profit / Ton':               'Coins',
  'Avg Rev / Sale Order':       'ReceiptText',
  'Avg Revenue / Sale Order':   'ReceiptText',
  'Revenue per Trip':           'TrendingUpDown',
  // ── Operational Overview ─────────────────────────────────────────────────
  'Purchased':                  'PackageOpen',
  'Sold':                       'Truck',
  'Diesel Cost':                'Fuel',
  'Trip Efficiency':            'Activity',
  'Total Trips':                'Route',
  'Vehicle Utilization':        'Gauge',
  // ── Inventory & Transfers ────────────────────────────────────────────────
  'Total Inventory Value':      'Warehouse',
  'Dead Stock Value':           'ArchiveX',
  'Internal Transfers':         'ArrowLeftRight',
  'Settlement Efficiency':      'ShieldCheck',
  // ── Inventory Intelligence ───────────────────────────────────────────────
  'Inventory Turnover Ratio':   'RefreshCcw',
  'Days Inventory Outstanding': 'CalendarClock',
  'Aging Stock ≥60 Days':       'Hourglass',
  'Dead Stock ≥90 Days':        'CircleOff',
  // ── Customer Intelligence ────────────────────────────────────────────────
  'Unique Customers':           'Users',
  'Top 3 Concentration':        'Target',
  'Repeat Customers':           'UserRoundCheck',
  'Avg Revenue / Customer':     'Handshake',
  // ── Transport Intelligence ───────────────────────────────────────────────
  'Unique Vehicles':            'CarFront',
  'Transport Value':            'Container',
  'Top Transporter':            'Award',
  // ── Material Intelligence ────────────────────────────────────────────────
  'Material Qty Balance':       'Scale',
  'Material Purchased':         'PackagePlus',
  'Material Sold':              'PackageCheck',
  'Qty Variance':               'Activity',
  'Top Material':               'Star',
  'Material Turnover Rate':     'Repeat',
  'Unique Materials':           'Layers3',
  'Material Revenue':           'Boxes',
  'Top Moving Material':        'Gem',
  // ── Vendor Intelligence ──────────────────────────────────────────────────
  'Unique Vendors':             'Building2',
  'Total Purchase Value':       'FileSpreadsheet',
  'Avg / Vendor':               'Calculator',
  'Top Vendor':                 'Medal',
  // ── Crusher Intelligence ─────────────────────────────────────────────────
  'Active Crushers':            'Mountain',
  'Total Source Value':         'Factory',
  'Top Crusher Trips':          'Pickaxe',
  'Top Crusher Share':          'PieChart',
  // ── Business Intelligence — Operational ──────────────────────────────────
  'Active Vehicles':            'BusFront',
  'Transporters':               'UserCog',
  'Avg Trip Size':              'Ruler',
  'Top Vehicle':                'Truck',
};

// ── Reusable KPICard Component ────────────────────────────────────────────────
// Future-proof: any new KPI card using this component inherits the full
// design system automatically — icon, typography, hover, spacing, shadow.
function KPICard({ icon, label, value, sub, color, onClick, span, tooltip }) {
  const accentColor = color || 'var(--or)';
  const resolvedIcon = icon || KPI_ICON_MAP[label];
  const bgTint = getIconBg(accentColor);
  return (
    <div
      className="kpi"
      onClick={onClick}
      title={tooltip || (onClick ? `View ${label} details` : undefined)}
      style={{
        cursor: onClick ? 'pointer' : 'default',
        ...(span ? { gridColumn: `span ${span}` } : {}),
      }}
    >
      {resolvedIcon && (
        <div className="kpi-ic-wrap" style={{ background: bgTint }}>
          <LucideIcon name={resolvedIcon} size={22} strokeWidth={2} color={accentColor} />
        </div>
      )}
      <div className="kpi-lbl">{label}</div>
      <div className="kpi-val" style={{ color: accentColor }}>{value}</div>
      {sub && <div className="kpi-sub">{sub}</div>}
    </div>
  );
}

// ── Export to window ──────────────────────────────────────────────────────────
window.LucideIcon   = LucideIcon;
window.getIconBg    = getIconBg;
window.KPI_ICON_MAP = KPI_ICON_MAP;
window.KPICard      = KPICard;
