// Utilities + icons for INLEARN CRM

// Expose React hooks globally so each Babel script can use them
window.useState = React.useState;
window.useEffect = React.useEffect;
window.useRef = React.useRef;
window.useMemo = React.useMemo;
window.useCallback = React.useCallback;

window.fmtZAR = (n) => 'R' + (n || 0).toLocaleString('en-ZA');
window.fmtZARShort = (n) => {
  if (n == null) return '—';
  if (n >= 1000) return 'R' + (n/1000).toFixed(n % 1000 === 0 ? 0 : 1) + 'k';
  return 'R' + n;
};

window.fmtDate = (iso) => {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleDateString('en-ZA', { day: 'numeric', month: 'short' });
};
window.fmtDateLong = (iso) => {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleDateString('en-ZA', { day: 'numeric', month: 'short', year: 'numeric' });
};
window.fmtDateTime = (iso) => {
  if (!iso) return '—';
  const d = new Date(iso);
  const date = d.toLocaleDateString('en-ZA', { day: 'numeric', month: 'short' });
  const time = d.toLocaleTimeString('en-ZA', { hour: '2-digit', minute: '2-digit', hour12: false });
  return `${date}, ${time}`;
};
window.fmtTimeAgo = (iso) => {
  if (!iso) return '—';
  const d = new Date(iso); const now = new Date();
  const diffMs = now - d;
  const mins = Math.floor(diffMs / 60000);
  if (mins < 1) return 'just now';
  if (mins < 60) return mins + 'm ago';
  const hrs = Math.floor(mins/60);
  if (hrs < 24) return hrs + 'h ago';
  const days = Math.floor(hrs/24);
  if (days < 30) return days + 'd ago';
  return d.toLocaleDateString('en-ZA', { day: 'numeric', month: 'short' });
};

window.initials = (name) => name.split(' ').filter(Boolean).slice(0,2).map(s => s[0]).join('').toUpperCase();

// ---------- Three-entity helpers (Contacts / Deals) ----------
window.contactFullName = (c) => c ? `${c.firstName} ${c.lastName}`.trim() : '—';
window.getContact = (contacts, id) => (contacts || []).find(c => c.id === id) || null;
window.dealsForContact = (deals, contactId) =>
  (deals || []).filter(d => d.studentId === contactId || d.payerId === contactId);
window.lifetimeValue = (deals, contactId) =>
  dealsForContact(deals, contactId).filter(d => d.stage === 'FulfillmentReady')
    .reduce((s, d) => s + (d.customPackagePrice || 0), 0);
window.referralsFor = (contacts, contactId) =>
  (contacts || []).filter(c => (c.relationships || []).some(r => r.kind === 'referredBy' && r.contactId === contactId));
window.isWonStage = (stageId) => stageId === 'FulfillmentReady';
window.isLostStage = (stageId) => stageId === 'LostDisqualified';
window.isActiveStage = (stageId) => !isWonStage(stageId) && !isLostStage(stageId);

// Available placeholder tokens for playbook templates (used by the Playbook editor + lead drawer)
window.PLAYBOOK_TOKENS = [
  { key: '{name}',          desc: 'Lead full name' },
  { key: '{studentName}',   desc: 'Student name (if parent submitted)' },
  { key: '{grade}',         desc: 'Grade / year (e.g. Grade 10)' },
  { key: '{subjects}',      desc: 'Subjects (e.g. Mathematics/Accounting)' },
  { key: '{package}',       desc: 'Selected package (Bronze/Silver/Gold/Platinum)' },
  { key: '{price}',         desc: 'Monthly package price (R formatted)' },
  { key: '{callDate}',      desc: 'Clarity call date' },
  { key: '{callTime}',      desc: 'Clarity call time' },
  { key: '{invoiceNumber}', desc: 'Invoice number' },
  { key: '{invoiceAmount}', desc: 'Invoice amount (R formatted)' },
];

// Replace {placeholder} tokens with real values from a lead.
window.renderPlaybookText = (text, lead) => {
  if (!text || !lead) return text || '';
  const values = {
    '{name}':          lead.name || '',
    '{studentName}':   lead.studentName || lead.name || '',
    '{grade}':         lead.gradeOrYear || '',
    '{subjects}':      (lead.subjects || []).join('/'),
    '{package}':       lead.selectedPackage || '',
    '{price}':         lead.customPackagePrice ? fmtZAR(lead.customPackagePrice) : '',
    '{callDate}':      lead.clarityCallDate || '',
    '{callTime}':      lead.clarityCallTime || '',
    '{invoiceNumber}': lead.invoiceNumber || '',
    '{invoiceAmount}': lead.invoiceAmount ? fmtZAR(lead.invoiceAmount) : '',
  };
  return Object.entries(values).reduce((acc, [k,v]) => acc.split(k).join(v), text);
};

// Deterministic pastel for avatar fill, keyed by string
window.avatarColor = (s) => {
  const palette = ['#4F46E5','#059669','#D97706','#DB2777','#0891B2','#7C3AED','#B45309','#0EA5E9'];
  let h = 0; for (let i=0;i<s.length;i++) h = (h*31 + s.charCodeAt(i)) | 0;
  return palette[Math.abs(h) % palette.length];
};

// ---------- Inline SVG icons (no external dependency) ----------
const I = (props) => {
  const { children, size = 16, stroke = 'currentColor', fill = 'none', sw = 1.75, className = '' } = props;
  return React.createElement('svg', {
    width: size, height: size, viewBox: '0 0 24 24', fill,
    stroke, strokeWidth: sw, strokeLinecap: 'round', strokeLinejoin: 'round',
    className,
  }, children);
};

window.Icon = {
  Search: (p) => <I {...p}><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></I>,
  Plus:   (p) => <I {...p}><path d="M12 5v14M5 12h14"/></I>,
  ChevronDown: (p) => <I {...p}><path d="m6 9 6 6 6-6"/></I>,
  ChevronRight: (p) => <I {...p}><path d="m9 6 6 6-6 6"/></I>,
  ChevronLeft:  (p) => <I {...p}><path d="m15 6-6 6 6 6"/></I>,
  X:      (p) => <I {...p}><path d="M18 6 6 18M6 6l12 12"/></I>,
  Filter: (p) => <I {...p}><path d="M3 6h18M6 12h12M10 18h4"/></I>,
  Grid:   (p) => <I {...p}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></I>,
  Layers: (p) => <I {...p}><path d="m12 2 9 5-9 5-9-5 9-5z"/><path d="m3 12 9 5 9-5"/><path d="m3 17 9 5 9-5"/></I>,
  Users:  (p) => <I {...p}><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"/></I>,
  Pie:    (p) => <I {...p}><path d="M21.21 15.89A10 10 0 1 1 8 2.83"/><path d="M22 12A10 10 0 0 0 12 2v10z"/></I>,
  Settings: (p) => <I {...p}><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 1 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 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.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.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 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.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></I>,
  Inbox:  (p) => <I {...p}><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></I>,
  Bell:   (p) => <I {...p}><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></I>,
  Phone:  (p) => <I {...p}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92z"/></I>,
  Mail:   (p) => <I {...p}><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-10 6L2 7"/></I>,
  Chat:   (p) => <I {...p}><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></I>,
  Calendar:(p) => <I {...p}><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></I>,
  Book:   (p) => <I {...p}><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></I>,
  School: (p) => <I {...p}><path d="M22 10v6M2 10l10-5 10 5-10 5z"/><path d="M6 12v5c3 3 9 3 12 0v-5"/></I>,
  Trash:  (p) => <I {...p}><path d="M3 6h18M19 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"/></I>,
  More:   (p) => <I {...p}><circle cx="5" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/></I>,
  Logout: (p) => <I {...p}><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="m16 17 5-5-5-5"/><path d="M21 12H9"/></I>,
  Shield: (p) => <I {...p}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></I>,
  Sparkles:(p)=> <I {...p}><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/></I>,
  Trend:  (p) => <I {...p}><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></I>,
  Alert:  (p) => <I {...p}><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></I>,
  Check:  (p) => <I {...p}><path d="M20 6 9 17l-5-5"/></I>,
  Clock:  (p) => <I {...p}><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></I>,
  ArrowRight: (p) => <I {...p}><path d="M5 12h14M13 5l7 7-7 7"/></I>,
  ArrowUp:    (p) => <I {...p}><path d="M12 19V5M5 12l7-7 7 7"/></I>,
  ArrowDown:  (p) => <I {...p}><path d="M12 5v14M19 12l-7 7-7-7"/></I>,
  Refresh:    (p) => <I {...p}><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></I>,
  Dot:    (p) => <I {...p}><circle cx="12" cy="12" r="3"/></I>,
  Money:  (p) => <I {...p}><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></I>,
  Flame:  (p) => <I {...p}><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/></I>,
  Box:    (p) => <I {...p}><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></I>,
  Tag:    (p) => <I {...p}><path d="M20.59 13.41 13.42 20.6a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><circle cx="7" cy="7" r="1.2" fill="currentColor"/></I>,
};
