/* Mereka v2 — Finance kit: lucide-style icons, toast, primitives, mock data.
   Faithful port of the "Finance Page for Transactions" Figma Make export. */

/* ---------------- Mock data (from src/app/data/mockData.ts) ---------------- */
const FIN_HUBS = [
  { id: 'hub1', name: 'Creative Hub KL' },
  { id: 'hub2', name: 'Tech Incubator MY' },
  { id: 'hub3', name: 'Design Center SG' },
];

const FIN_BANK_ACCOUNTS = [
  { id: 'ba1', bankName: 'STRIPE TEST BANK', last4: '6000', isDefault: true, holder: 'Creative Hub KL Admin', type: 'business' },
];

const FIN_TRANSACTIONS = [
  { id: 't1', date: '2025-05-18', description: 'Website Designer', mainType: 'PURCHASE', subType: 'Jobs', gross: 3433.00, net: 3429.00, fees: 1.19, status: 'on hold', type: 'expense', category: 'Jobs', hubId: 'hub1', vendor: 'Lucas Miller', vendorAvatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=100&h=100&fit=crop', id_long: 'pi_3RR4lfAXr3UuDcCV1iibQ7vp', timeline: [ { status: 'pending', label: 'On Hold', date: '18 May 2025, 14:00' }, { status: 'completed', label: 'Payment initiated', date: '18 May 2025, 12:30' } ] },
  { id: 't2', date: '2025-05-18', description: 'Regulatory Reporting Expert – Transa...', subDescription: 'Week 2: Nov 11 - Nov 17', mainType: 'REFUND', subType: 'Experiences', gross: 25.00, net: 28.00, fees: 0, status: 'completed', type: 'earning', category: 'Experiences', hubId: 'hub1', vendor: 'Lucas Miller', vendorAvatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=100&h=100&fit=crop', id_long: 'pi_4BB8lkCXr5UuDdBV2jkbW8wq', timeline: [ { status: 'completed', label: 'Refund successful', date: '18 May 2025, 12:30' } ] },
  { id: 't3', date: '2025-05-18', description: 'Punch & Create: Needle Punch Works...', subDescription: '1 x Paid Ticket', mainType: 'PURCHASE', subType: 'Experiences', gross: 82.46, net: 78.00, fees: 1.19, status: 'on hold', type: 'expense', category: 'Experiences', hubId: 'hub1', vendor: 'Mereka', vendorSub: 'Felicia Wong', vendorAvatar: 'https://images.unsplash.com/photo-1573497019940-1c28c88b4f3e?w=100&h=100&fit=crop', id_long: 'pi_9ZZ2lmDXr8UuEeCV4lkbY9zz', timeline: [ { status: 'pending', label: 'On Hold', date: '18 May 2025, 09:00' } ] },
  { id: 't4', date: '2025-05-17', description: 'UI/UX Design Mentorship', subDescription: 'Session #4', mainType: 'PURCHASE', subType: 'Expertise', gross: 150.00, net: 145.00, fees: 5.00, status: 'completed', type: 'earning', category: 'Expertise', hubId: 'hub2', vendor: 'Sarah Chen', vendorAvatar: 'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=100&h=100&fit=crop', id_long: 'pi_2RR3lfAXr2UuDcCV1iibQ6xx', timeline: [ { status: 'completed', label: 'Payment received', date: '17 May 2025, 15:00' } ] },
  { id: 't5', date: '2025-05-16', description: 'Cloud Infrastructure Fee', subDescription: 'AWS Monthly Sub', mainType: 'PURCHASE', subType: 'Software', gross: 45.99, net: 45.99, fees: 0, status: 'completed', type: 'expense', category: 'Infrastructure', hubId: 'hub3', vendor: 'Amazon Web Services', vendorAvatar: 'https://images.unsplash.com/photo-1614680376593-902f74cf0d41?w=100&h=100&fit=crop', id_long: 'pi_1RR2lfAXr1UuDcCV1iibQ5yy', timeline: [ { status: 'completed', label: 'Paid', date: '16 May 2025, 10:00' } ] },
  { id: 't6', date: '2026-01-24', description: 'Bulk Expert Payout', subDescription: '12 Experts', mainType: 'WITHDRAWAL', subType: 'Payout', gross: 12450.00, net: 12400.00, fees: 50.00, status: 'succeeded', type: 'withdrawal', hubId: 'hub1', vendor: 'Multiple Experts', destination: 'Stripe Payout to Bank', id_long: 'po_5LL9mmEXr9UuFfDV5lkbZ0aa', timeline: [ { status: 'completed', label: 'Withdrawal initiated', date: '24 Jan 2026, 09:00' }, { status: 'completed', label: 'Funds sent to bank', date: '24 Jan 2026, 14:00' } ] },
  { id: 't7', date: '2026-01-25', description: 'Personal Earnings Withdrawal', subDescription: 'Wallet to Bank', mainType: 'WITHDRAWAL', subType: 'Transfer', gross: 850.00, net: 845.00, fees: 5.00, status: 'pending', type: 'withdrawal', hubId: 'hub1', vendor: 'Sarah Chen', destination: 'Maybank •••• 4421', id_long: 'po_6MM0nnFXs0VvGgEV6mlca1bb', timeline: [ { status: 'completed', label: 'Withdrawal initiated', date: '25 Jan 2026, 10:00' }, { status: 'pending', label: 'Processing by bank', date: 'Expected 26 Jan 2026' } ] },
  { id: 't8', date: '2026-02-15', description: 'Expert Skills Workshop Revenue', subDescription: '15 x Corporate Bookings', mainType: 'EARNING', subType: 'Expertise', gross: 4500.00, net: 4050.00, fees: 450.00, status: 'completed', type: 'earning', category: 'Expertise', hubId: 'hub1', vendor: 'Mereka', vendorSub: 'Multiple Experts', vendorAvatar: 'https://images.unsplash.com/photo-1552664730-d307ca884978?w=100&h=100&fit=crop', id_long: 'pi_7KK1ooGXv1WwHhFV7nlcb2cc', timeline: [ { status: 'completed', label: 'Revenue processed', date: '15 Feb 2026, 09:00' }, { status: 'completed', label: 'Funds added to balance', date: '15 Feb 2026, 11:30' } ] },
];

const FIN_SERVICES = [
  { id: 's1', name: 'Experiences', expertSplit: 80, hubSplit: 20 },
  { id: 's2', name: 'Expertise', expertSplit: 70, hubSplit: 30 },
  { id: 's3', name: 'Jobs', expertSplit: 90, hubSplit: 10 },
];

const FIN_USERS = [
  { id: 'u1', name: 'Shuhada Rabi', email: 'shuhada@ouch.my', department: 'Customer Service', balance: 1500.00, status: 'active', cards: [ { id: 'c1', bankName: 'Maybank', last4: '4421', type: 'Savings', isDefault: true }, { id: 'c2', bankName: 'CIMB', last4: '8892', type: 'Current' } ] },
  { id: 'u2', name: 'Raymond Hong Yeow Him', email: 'raymondhong@ouch.my', department: 'Finance', balance: 3250.50, status: 'active', cards: [ { id: 'c3', bankName: 'Public Bank', last4: '1122', type: 'Savings', isDefault: true } ] },
  { id: 'u3', name: 'Tan Jia Ming', email: 'jiaming@ouch.my', department: 'Human Resource (HR)', balance: 800.00, status: 'active', cards: [ { id: 'c4', bankName: 'Hong Leong', last4: '3344', type: 'Savings', isDefault: true } ] },
  { id: 'u4', name: 'Mohamed Asyraf Bin Jaafar', email: 'asyraf@ouch.my', department: 'Human Resource (HR)', balance: 1200.00, status: 'active', cards: [ { id: 'c5', bankName: 'RHB', last4: '5566', type: 'Savings', isDefault: true }, { id: 'c6', bankName: 'Maybank', last4: '9988', type: 'Current' } ] },
];

const FIN_EXPERT_HUB_BALANCES = [
  { hubId: 'hub1', hubName: 'Creative Hub KL', balance: 4500.00 },
  { hubId: 'hub2', hubName: 'Tech Incubator MY', balance: 2150.50 },
  { hubId: 'hub3', hubName: 'Design Center SG', balance: 800.00 },
];

/* ---------------- Icons (lucide paths) ---------------- */
const FIN_ICONS = {
  building2: <><path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z"/><path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2"/><path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"/><path d="M10 6h4M10 10h4M10 14h4M10 18h4"/></>,
  creditCard: <><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20"/></>,
  plus: <path d="M5 12h14M12 5v14"/>,
  trash2: <><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M10 11v6M14 11v6"/></>,
  download: <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/></>,
  refreshCw: <><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/><path d="M3 21v-5h5"/></>,
  search: <><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></>,
  fileText: <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/><path d="M16 13H8M16 17H8M10 9H8"/></>,
  settings: <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.09a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.09a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z"/></>,
  helpCircle: <><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/></>,
  arrowLeft: <><path d="M19 12H5"/><path d="m12 19-7-7 7-7"/></>,
  alertCircle: <><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></>,
  checkCircle2: <><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><path d="m9 11 3 3L22 4"/></>,
  clock: <><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></>,
  arrowUpRight: <><path d="M7 7h10v10"/><path d="M7 17 17 7"/></>,
  arrowDownRight: <><path d="m7 7 10 10"/><path d="M17 7v10H7"/></>,
  chevronRight: <path d="m9 18 6-6-6-6"/>,
  calendar: <><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></>,
  sparkles: <><path d="m12 3 1.9 5.8L20 11l-6.1 2.2L12 19l-1.9-5.8L4 11l6.1-2.2z"/><path d="M5 3v4M3 5h4M19 17v4M17 19h4"/></>,
  info: <><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></>,
  wallet: <><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><path d="M18 12a2 2 0 0 0 0 4h4v-4Z"/></>,
  check: <path d="M20 6 9 17l-5-5"/>,
  pencil: <><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></>,
  externalLink: <><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/></>,
  percent: <><path d="M19 5 5 19"/><circle cx="6.5" cy="6.5" r="2.5"/><circle cx="17.5" cy="17.5" r="2.5"/></>,
  dollarSign: <><path d="M12 1v22"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></>,
  filter: <path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z"/>,
  users: <><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></>,
  briefcase: <><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></>,
  x: <path d="M18 6 6 18M6 6l12 12"/>,
  moreHorizontal: <><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></>,
  userCheck: <><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="m16 11 2 2 4-4"/></>,
  chevronDown: <path d="m6 9 6 6 6-6"/>,
};

function FIcon({ name, size = 18, className = '', strokeWidth = 2 }) {
  const p = FIN_ICONS[name];
  if (!p) return null;
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden="true">
      {p}
    </svg>
  );
}

/* ---------------- Toast (sonner-like) ---------------- */
function finToast(title, opts = {}) {
  let host = document.getElementById('fin-toast-host');
  if (!host) {
    host = document.createElement('div');
    host.id = 'fin-toast-host';
    host.style.cssText = 'position:fixed;top:16px;right:16px;z-index:10000;display:flex;flex-direction:column;gap:10px;max-width:380px;';
    document.body.appendChild(host);
  }
  const type = opts.type || 'default';
  const ring = type === 'success' ? '#16a34a' : type === 'error' ? '#dc2626' : '#111827';
  const el = document.createElement('div');
  el.style.cssText = `background:#fff;border:1px solid #e5e7eb;border-left:4px solid ${ring};border-radius:12px;padding:12px 14px;box-shadow:0 8px 30px rgba(0,0,0,.12);font-family:Inter,system-ui,sans-serif;animation:slideInRight .25s ease both;`;
  el.innerHTML = `<div style="font-weight:700;font-size:14px;color:#111827">${title}</div>` +
    (opts.description ? `<div style="font-size:12px;color:#6b7280;margin-top:2px;line-height:1.4">${opts.description}</div>` : '');
  host.appendChild(el);
  setTimeout(() => { el.style.transition = 'opacity .3s, transform .3s'; el.style.opacity = '0'; el.style.transform = 'translateX(12px)'; setTimeout(() => el.remove(), 320); }, opts.duration || 4000);
}
finToast.success = (t, o = {}) => finToast(t, { ...o, type: 'success' });
finToast.error = (t, o = {}) => finToast(t, { ...o, type: 'error' });

/* ---------------- Primitives ---------------- */
function FSelect({ value, onValueChange, options = [], placeholder, leftIcon, rightIcon, className = '', triggerClassName = '' }) {
  return (
    <div className={`relative ${className}`}>
      {leftIcon && <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none">{leftIcon}</span>}
      <select value={value} onChange={e => onValueChange && onValueChange(e.target.value)}
        className={`appearance-none w-full bg-white border border-gray-200 rounded-xl text-[14px] text-gray-900 focus:outline-none focus:border-gray-400 ${leftIcon ? 'pl-9' : 'pl-4'} pr-9 ${triggerClassName || 'h-11'}`}>
        {placeholder && <option value="" disabled>{placeholder}</option>}
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
      <span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none">{rightIcon || <FIcon name="chevronDown" size={16} />}</span>
    </div>
  );
}

function FAvatar({ src, fallback, className = '' }) {
  const [err, setErr] = useState(false);
  return (
    <div className={`relative overflow-hidden bg-gray-50 flex items-center justify-center ${className}`}>
      {src && !err
        ? <img src={src} onError={() => setErr(true)} className="w-full h-full object-cover" alt="" />
        : <span className="text-[11px] font-bold text-gray-700">{fallback}</span>}
    </div>
  );
}

function FSwitch({ checked, onCheckedChange }) {
  return (
    <button type="button" role="switch" aria-checked={checked} onClick={() => onCheckedChange && onCheckedChange(!checked)}
      className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${checked ? 'bg-black' : 'bg-gray-200'}`}>
      <span className={`inline-block h-5 w-5 transform rounded-full bg-white shadow transition-transform ${checked ? 'translate-x-5' : 'translate-x-0.5'}`} />
    </button>
  );
}

/* Modal shell: backdrop + centered panel. panelClassName controls width/shape. */
function FModal({ open, onClose, children, panelClassName = 'max-w-md' }) {
  useEffect(() => {
    if (!open) return;
    const onKey = e => { if (e.key === 'Escape') onClose && onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[1000] flex items-center justify-center p-4" onClick={onClose}>
      <div className="absolute inset-0 bg-black/40 backdrop-blur-[2px]" />
      <div onClick={e => e.stopPropagation()} className={`relative bg-white rounded-2xl shadow-2xl w-full ${panelClassName}`} style={{ animation: 'fadeUp .2s ease both' }}>
        {children}
      </div>
    </div>
  );
}

/* Helper: format date like 'en-GB' short */
function finDate(d, opts) { return new Date(d).toLocaleDateString('en-GB', opts || { day: 'numeric', month: 'short', year: 'numeric' }); }
function finNum(n, min = 2) { return Number(n || 0).toLocaleString(undefined, { minimumFractionDigits: min }); }

Object.assign(window, {
  FIN_HUBS, FIN_BANK_ACCOUNTS, FIN_TRANSACTIONS, FIN_SERVICES, FIN_USERS, FIN_EXPERT_HUB_BALANCES,
  FIcon, finToast, FSelect, FAvatar, FSwitch, FModal, finDate, finNum,
});
