/* UI primitives — exported to window. Uses styles.css classes. */

const STATUS = () => window.DATA.status;
const GASES = () => window.DATA.gases;

/* Status badge */
function Badge({ status, large, children }) {
  const meta = STATUS()[status];
  const cls = meta ? meta.cls : 'b-empty';
  return React.createElement('span', { className: `badge ${cls} ${large ? 'badge-lg' : ''}` },
    React.createElement('span', { className: 'dot' }),
    children || (meta ? meta.label : status)
  );
}

/* Cylinder visual — colored by status or gas */
function Cylinder({ w = 26, color, status, gas, style }) {
  let c = color;
  if (!c && status) c = STATUS()[status]?.color;
  if (!c && gas) c = GASES()[gas]?.color;
  c = c || 'var(--brand)';
  const h = w * 2.3;
  return React.createElement('span', {
    className: 'cyl',
    style: { width: w, height: h, '--cyl-color': c, ...style }
  }, React.createElement('span', { className: 'cyl-cap' }));
}

/* Progress ring (donut) */
function Ring({ size = 150, stroke = 14, segments, total, children }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  let offset = 0;
  const sum = total || segments.reduce((a, s) => a + s.value, 0) || 1;
  return React.createElement('div', { className: 'ring-wrap', style: { width: size, height: size } },
    React.createElement('svg', { width: size, height: size, style: { transform: 'rotate(-90deg)' } },
      React.createElement('circle', { cx: size/2, cy: size/2, r, fill: 'none', stroke: 'var(--surface-3)', strokeWidth: stroke }),
      segments.map((s, i) => {
        const len = (s.value / sum) * c;
        const el = React.createElement('circle', {
          key: i, cx: size/2, cy: size/2, r, fill: 'none', stroke: s.color, strokeWidth: stroke,
          strokeDasharray: `${len} ${c - len}`, strokeDashoffset: -offset, strokeLinecap: 'round',
          style: { transition: 'stroke-dasharray .9s ease, stroke-dashoffset .9s ease' }
        });
        offset += len;
        return el;
      })
    ),
    React.createElement('div', { className: 'ring-center' }, children)
  );
}

/* Mini bar chart */
function Bars({ data, labels, color = 'var(--brand)', height = 70, highlight }) {
  const max = Math.max(...data) || 1;
  return React.createElement('div', { style: { display: 'flex', alignItems: 'flex-end', gap: 8, height } },
    data.map((v, i) =>
      React.createElement('div', { key: i, style: { flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, height: '100%' } },
        React.createElement('div', { style: { flex: 1, width: '100%', display: 'flex', alignItems: 'flex-end' } },
          React.createElement('div', {
            title: labels ? `${labels[i]}: ${v.toLocaleString()}` : v,
            style: {
              width: '100%', height: `${(v/max)*100}%`, borderRadius: '6px 6px 3px 3px',
              background: (highlight === i) ? color : `color-mix(in srgb, ${color} 32%, transparent)`,
              transition: 'height .6s ease'
            }
          })
        ),
        labels && React.createElement('span', { style: { fontSize: 10.5, fontWeight: 700, color: 'var(--text-3)' } }, labels[i])
      )
    )
  );
}

/* Sparkline */
function Sparkline({ data, w = 90, h = 34, color = 'var(--brand)' }) {
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => `${(i/(data.length-1))*w},${h - ((v-min)/range)*(h-4) - 2}`).join(' ');
  const id = 'sg' + Math.random().toString(36).slice(2, 7);
  return React.createElement('svg', { width: w, height: h, className: 'kpi-spark' },
    React.createElement('defs', null,
      React.createElement('linearGradient', { id, x1: 0, y1: 0, x2: 0, y2: 1 },
        React.createElement('stop', { offset: '0%', stopColor: color, stopOpacity: .28 }),
        React.createElement('stop', { offset: '100%', stopColor: color, stopOpacity: 0 })
      )
    ),
    React.createElement('polyline', { points: `0,${h} ${pts} ${w},${h}`, fill: `url(#${id})`, stroke: 'none' }),
    React.createElement('polyline', { points: pts, fill: 'none', stroke: color, strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round' })
  );
}

/* KPI card */
function Kpi({ tone = 'brand', icon, label, value, delta, deltaDir, foot, spark, onClick }) {
  return React.createElement('div', { className: `kpi tone-${tone}`, onClick, style: onClick ? { cursor: 'pointer' } : null },
    React.createElement('div', { className: 'kpi-top' },
      React.createElement('div', { className: 'kpi-ico' }, React.createElement(Icon, { name: icon })),
      delta != null && React.createElement('span', { className: `kpi-delta ${deltaDir === 'down' ? 'kpi-down' : 'kpi-up'}` },
        React.createElement(Icon, { name: deltaDir === 'down' ? 'down' : 'up', size: 14 }), delta)
    ),
    React.createElement('div', { className: 'kpi-label' }, label),
    React.createElement('div', { className: 'kpi-value' }, value),
    foot && React.createElement('div', { className: 'kpi-foot' }, foot),
    spark && React.createElement(Sparkline, { data: spark, color: `var(--${tone === 'brand' ? 'brand' : tone})` })
  );
}

/* Gas pill */
function GasPill({ gas, size }) {
  const g = GASES()[gas];
  if (!g) return null;
  return React.createElement('span', {
    style: {
      display: 'inline-flex', alignItems: 'center', gap: 7, height: size === 'lg' ? 30 : 26, padding: '0 11px',
      borderRadius: 8, background: 'var(--surface-3)', fontSize: size === 'lg' ? 13.5 : 12.5, fontWeight: 700
    }
  },
    React.createElement('span', { style: { width: 9, height: 9, borderRadius: 3, background: g.color } }),
    gas
  );
}

/* Toast context */
const ToastCtx = React.createContext(null);
function useToast() { return React.useContext(ToastCtx); }

function ToastHost({ children }) {
  const [toasts, setToasts] = React.useState([]);
  const push = React.useCallback((opts) => {
    const id = Math.random().toString(36).slice(2);
    setToasts(t => [...t, { id, ...opts }]);
    if (window.navigator.vibrate && opts.kind === 'ok') window.navigator.vibrate(40);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), opts.duration || 2600);
  }, []);
  const api = React.useMemo(() => ({
    ok: (msg, sub) => push({ kind: 'ok', msg, sub }),
    err: (msg, sub) => push({ kind: 'err', msg, sub }),
    info: (msg, sub) => push({ kind: 'info', msg, sub }),
  }), [push]);
  const iconFor = { ok: 'check', err: 'x', info: 'bell' };
  return React.createElement(ToastCtx.Provider, { value: api },
    children,
    React.createElement('div', { className: 'toast-wrap' },
      toasts.map(t => React.createElement('div', { key: t.id, className: `toast ${t.kind}` },
        React.createElement('div', { className: 'ti' }, React.createElement(Icon, { name: iconFor[t.kind], size: 20 })),
        React.createElement('div', null,
          React.createElement('div', null, t.msg),
          t.sub && React.createElement('div', { style: { fontSize: 12.5, color: 'var(--text-3)', fontWeight: 500, marginTop: 2 } }, t.sub)
        )
      ))
    )
  );
}

/* Modal */
function Modal({ title, icon, onClose, children, footer, width }) {
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);
  return React.createElement('div', { className: 'modal-back', onClick: onClose },
    React.createElement('div', { className: 'modal', style: width ? { width } : null, onClick: e => e.stopPropagation() },
      React.createElement('div', { className: 'modal-head' },
        icon && React.createElement('div', { className: 'feed-ico', style: { width: 40, height: 40 } }, React.createElement(Icon, { name: icon, size: 20 })),
        React.createElement('h3', null, title),
        React.createElement('button', { className: 'x-btn', onClick: onClose }, React.createElement(Icon, { name: 'x', size: 18 }))
      ),
      React.createElement('div', { className: 'modal-body' }, children),
      footer && React.createElement('div', { className: 'modal-foot' }, footer)
    )
  );
}

/* Branch pill strip */
function BranchStrip({ value, onChange }) {
  const branches = window.DATA.branches;
  return React.createElement('div', { className: 'branch-strip' },
    React.createElement('button', { className: `chip ${value === 'ALL' ? 'on' : ''}`, onClick: () => onChange('ALL') },
      React.createElement(Icon, { name: 'layers', size: 15 }), 'All branches'),
    branches.map(b => React.createElement('button', { key: b.id, className: `chip ${value === b.id ? 'on' : ''}`, onClick: () => onChange(b.id) },
      b.hq && React.createElement(Icon, { name: 'factory', size: 15 }), b.label))
  );
}

function fmtINR(n) {
  if (n >= 10000000) return '₹' + (n/10000000).toFixed(2) + ' Cr';
  if (n >= 100000) return '₹' + (n/100000).toFixed(2) + ' L';
  if (n >= 1000) return '₹' + (n/1000).toFixed(0) + 'k';
  return '₹' + n;
}
function fmtINRfull(n) { return '₹' + n.toLocaleString('en-IN'); }

Object.assign(window, {
  Badge, Cylinder, Ring, Bars, Sparkline, Kpi, GasPill,
  ToastHost, useToast, Modal, BranchStrip, fmtINR, fmtINRfull,
});
