// UI primitives + small helpers
(function () {
  const { useState, useEffect, useRef, useContext, createContext } = React;

  // ---- Currency ----
  // Reference rate (May 2026): 1 THB ≈ 615 LAK
  // Rate is user-configurable; lives in localStorage 'ciga-rate'.
  const DEFAULT_RATE = 615;
  function loadRate() {
    try {
      const v = parseFloat(localStorage.getItem('ciga-rate'));
      return Number.isFinite(v) && v > 0 ? v : DEFAULT_RATE;
    } catch (e) { return DEFAULT_RATE; }
  }
  const CURRENCY = {
    LAK: { symbol: '₭', label: 'กีบ', code: 'LAK' },
    THB: { symbol: '฿', label: 'บาท', code: 'THB' },
  };
  const CurrencyContext = createContext({
    currency: 'LAK', setCurrency: () => {},
    rate: DEFAULT_RATE, setRate: () => {},
  });
  function useCurrency() { return useContext(CurrencyContext); }

  // Convert LAK amount to display currency.
  function convertLAK(v, currency, rate = DEFAULT_RATE) {
    if (currency === 'THB') return v / rate;
    return v;
  }
  function fmtMoney(v, currency = 'LAK', opts = {}, rate = DEFAULT_RATE) {
    const { compact = false, sign = false, decimals } = opts;
    const c = CURRENCY[currency] || CURRENCY.LAK;
    const conv = convertLAK(v, currency, rate);
    const signStr = sign && conv > 0 ? '+' : (conv < 0 ? '−' : '');
    const abs = Math.abs(conv);
    let body;
    if (compact) {
      body = fmtK(abs, currency === 'THB' ? 1 : 2);
    } else if (decimals != null) {
      body = abs.toLocaleString('en-US', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
    } else {
      body = Math.round(abs).toLocaleString('en-US');
    }
    return signStr + c.symbol + body;
  }
  function moneySymbol(currency = 'LAK') { return (CURRENCY[currency] || CURRENCY.LAK).symbol; }

  // useMoney() — convenience hook returning ready-to-use formatters bound to current context.
  function useMoney() {
    const { currency, rate } = useCurrency();
    return {
      currency,
      rate,
      sym: moneySymbol(currency),
      M: (v, opts) => fmtMoney(v, currency, opts, rate),
      Mk: (v) => fmtMoney(v, currency, { compact: true }, rate),
    };
  }

  function CurrencyToggle() {
    const { currency, setCurrency } = useCurrency();
    return (
      <div className="ccy-toggle" title="เปลี่ยนสกุลเงิน">
        {Object.entries(CURRENCY).map(([id, c]) => (
          <button
            key={id}
            className={`ccy-btn ${currency === id ? 'active' : ''}`}
            onClick={() => setCurrency(id)}>
            <span className="ccy-sym">{c.symbol}</span>
            <span className="ccy-label">{c.label}</span>
          </button>
        ))}
      </div>
    );
  }

  // ---- formatters ----
  function fmtK(v, decimals = 2) {
    const n = Math.abs(v);
    if (n >= 1_000_000_000) return (v / 1_000_000_000).toFixed(decimals) + 'B';
    if (n >= 1_000_000) return (v / 1_000_000).toFixed(decimals) + 'M';
    if (n >= 1_000) return (v / 1_000).toFixed(decimals === 2 ? 1 : decimals) + 'K';
    return Math.round(v).toString();
  }
  function fmtInt(v) { return Math.round(v).toLocaleString('en-US'); }
  function fmtLAK(v, opts = {}) {
    const { compact = false, decimals = 0, sign = false } = opts;
    if (compact) return '₭' + fmtK(v, 2);
    const s = Math.round(v).toLocaleString('en-US');
    return (sign && v > 0 ? '+' : '') + '₭' + s;
  }
  function fmtDate(d, fmt = 'short') {
    const yy = d.getFullYear() + 543; // BE
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const dd = String(d.getDate()).padStart(2, '0');
    if (fmt === 'short') return `${dd}/${mm}/${String(yy).slice(2)}`;
    if (fmt === 'iso') return `${d.getFullYear()}-${mm}-${dd}`;
    if (fmt === 'long') {
      const months = ['ม.ค.','ก.พ.','มี.ค.','เม.ย.','พ.ค.','มิ.ย.','ก.ค.','ส.ค.','ก.ย.','ต.ค.','พ.ย.','ธ.ค.'];
      return `${dd} ${months[d.getMonth()]} ${String(yy).slice(2)}`;
    }
    return d.toString();
  }
  function fmtTime(d) {
    return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
  }

  // ---- glass card ----
  function Card({ children, className = '', style = {}, glow = false, ...rest }) {
    return (
      <div className={`glass-card ${glow ? 'glass-glow' : ''} ${className}`} style={style} {...rest}>
        {children}
      </div>
    );
  }

  // ---- pill ----
  function Pill({ children, color, active, onClick, mono }) {
    return (
      <button onClick={onClick} className={`pill ${active ? 'pill-active' : ''} ${mono ? 'pill-mono' : ''}`}
        style={color ? { '--pill-color': color } : {}}>
        {children}
      </button>
    );
  }

  // ---- icons ----
  function Icon({ name, size = 16, stroke = 1.5 }) {
    const props = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: stroke, strokeLinecap: 'round', strokeLinejoin: 'round' };
    switch (name) {
      case 'dashboard': return <svg {...props}><rect x="3" y="3" width="7" height="9" rx="1"/><rect x="14" y="3" width="7" height="5" rx="1"/><rect x="14" y="12" width="7" height="9" rx="1"/><rect x="3" y="16" width="7" height="5" rx="1"/></svg>;
      case 'invest': return <svg {...props}><path d="M3 17l6-6 4 4 8-9"/><path d="M14 6h7v7"/></svg>;
      case 'wallet': return <svg {...props}><rect x="2" y="6" width="20" height="14" rx="2"/><path d="M16 13h2"/><path d="M2 10h20"/></svg>;
      case 'box': return <svg {...props}><path d="M21 8l-9-5-9 5 9 5 9-5z"/><path d="M3 8v8l9 5 9-5V8"/><path d="M12 13v8"/></svg>;
      case 'arrows': return <svg {...props}><path d="M7 7h10M7 7l3-3M7 7l3 3"/><path d="M17 17H7M17 17l-3-3M17 17l-3 3"/></svg>;
      case 'chart': return <svg {...props}><path d="M3 3v18h18"/><path d="M7 14l4-4 3 3 5-6"/></svg>;
      case 'plus': return <svg {...props}><path d="M12 5v14M5 12h14"/></svg>;
      case 'search': return <svg {...props}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.5-4.5"/></svg>;
      case 'bell': return <svg {...props}><path d="M6 8a6 6 0 0112 0c0 7 3 7 3 9H3c0-2 3-2 3-9z"/><path d="M10 21a2 2 0 004 0"/></svg>;
      case 'arrow-up': return <svg {...props}><path d="M12 19V5M5 12l7-7 7 7"/></svg>;
      case 'arrow-down': return <svg {...props}><path d="M12 5v14M19 12l-7 7-7-7"/></svg>;
      case 'trash': return <svg {...props}><path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/></svg>;
      case 'edit': return <svg {...props}><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>;
      case 'calendar': return <svg {...props}><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>;
      case 'settings': return <svg {...props}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 11-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 11-4 0v-.09a1.65 1.65 0 00-1-1.51 1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 11-2.83-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 110-4h.09a1.65 1.65 0 001.51-1 1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 112.83-2.83l.06.06a1.65 1.65 0 001.82.33h0a1.65 1.65 0 001-1.51V3a2 2 0 114 0v.09a1.65 1.65 0 001 1.51h0a1.65 1.65 0 001.82-.33l.06-.06a2 2 0 112.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82v0a1.65 1.65 0 001.51 1H21a2 2 0 110 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg>;
      case 'users': return <svg {...props}><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>;
      case 'percent': return <svg {...props}><line x1="19" y1="5" x2="5" y2="19"/><circle cx="6.5" cy="6.5" r="2.5"/><circle cx="17.5" cy="17.5" r="2.5"/></svg>;
      case 'pie': return <svg {...props}><path d="M21.21 15.89A10 10 0 118 2.83"/><path d="M22 12A10 10 0 0012 2v10z"/></svg>;
      case 'x': return <svg {...props}><path d="M18 6L6 18M6 6l12 12"/></svg>;
      case 'filter': return <svg {...props}><path d="M4 4h16l-6 8v6l-4 2v-8z"/></svg>;
      case 'chevron-down': return <svg {...props}><path d="M6 9l6 6 6-6"/></svg>;
      case 'bolt': return <svg {...props}><path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z"/></svg>;
      case 'circle': return <svg {...props}><circle cx="12" cy="12" r="4" fill="currentColor"/></svg>;
      case 'dot': return <svg {...props}><circle cx="12" cy="12" r="2" fill="currentColor"/></svg>;
      case 'pulse': return <svg {...props}><path d="M2 12h4l3-9 4 18 3-9h6"/></svg>;
      default: return null;
    }
  }

  // ---- live clock ----
  function LiveClock() {
    const [now, setNow] = useState(new Date());
    useEffect(() => {
      const t = setInterval(() => setNow(new Date()), 1000);
      return () => clearInterval(t);
    }, []);
    const days = ['อา','จ','อ','พ','พฤ','ศ','ส'];
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontFamily: "'IBM Plex Mono', monospace", fontSize: 12 }}>
        <span style={{ color: '#22d3a3' }}>●</span>
        <span style={{ color: 'rgba(230,233,240,0.55)' }}>{days[now.getDay()]} {fmtDate(now, 'long')}</span>
        <span style={{ color: '#e6e9f0', fontWeight: 600 }}>{String(now.getHours()).padStart(2, '0')}:{String(now.getMinutes()).padStart(2, '0')}:{String(now.getSeconds()).padStart(2, '0')}</span>
        <span style={{ color: 'rgba(230,233,240,0.35)' }}>VTE</span>
      </div>
    );
  }

  // ---- Ticker (Bloomberg-ish scrolling bar) ----
  function Ticker({ items }) {
    return (
      <div className="ticker">
        <div className="ticker-track">
          {[...items, ...items].map((it, i) => (
            <span key={i} className="ticker-item">
              <span className="ticker-label">{it.label}</span>
              <span className="ticker-value">{it.value}</span>
              <span className="ticker-delta" style={{ color: it.delta >= 0 ? '#22d3a3' : '#ff5a78' }}>
                {it.delta >= 0 ? '▲' : '▼'} {Math.abs(it.delta).toFixed(2)}%
              </span>
            </span>
          ))}
        </div>
      </div>
    );
  }

  Object.assign(window, { Card, Pill, Icon, LiveClock, Ticker, fmtK, fmtInt, fmtLAK, fmtMoney, moneySymbol, fmtDate, fmtTime, CurrencyContext, useCurrency, useMoney, CurrencyToggle, CURRENCY, loadRate, DEFAULT_RATE });
})();
