// Shared components for EMPHASIS Tracking System.
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ----- Icons (inline SVG, stroke based) -----
const Icon = ({ name, className = 'w-4 h-4', strokeWidth = 1.75 }) => {
  const paths = {
    calendar: <><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 9h18M8 3v4M16 3v4"/></>,
    dashboard: <><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></>,
    phone: <><rect x="6" y="2" width="12" height="20" rx="3"/><path d="M10 18h4"/></>,
    target: <><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1.5"/></>,
    book: <><path d="M4 4v15a2 2 0 0 0 2 2h14V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2zM4 19a2 2 0 0 1 2-2h14"/></>,
    chart: <><path d="M3 21h18"/><path d="M6 17v-5M10 17V8M14 17v-3M18 17V5"/></>,
    plus: <><path d="M12 5v14M5 12h14"/></>,
    check: <><path d="M5 12l4 4 10-10"/></>,
    x: <><path d="M6 6l12 12M18 6L6 18"/></>,
    chevL: <><path d="M15 6l-6 6 6 6"/></>,
    chevR: <><path d="M9 6l6 6-6 6"/></>,
    chevD: <><path d="M6 9l6 6 6-6"/></>,
    user: <><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-7 8-7s8 3 8 7"/></>,
    users: <><circle cx="9" cy="8" r="3.5"/><circle cx="17" cy="9" r="2.5"/><path d="M3 20c0-3 3-5.5 6-5.5s6 2.5 6 5.5M15 20c0-2.2 2-4 4-4s2 .8 2 2"/></>,
    bell: <><path d="M6 16V11a6 6 0 0 1 12 0v5l1.5 2H4.5L6 16zM10 21h4"/></>,
    search: <><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></>,
    pin: <><path d="M12 21s-7-7-7-12a7 7 0 1 1 14 0c0 5-7 12-7 12z"/><circle cx="12" cy="9" r="2.5"/></>,
    flag: <><path d="M5 21V4M5 4h12l-2 4 2 4H5"/></>,
    clock: <><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>,
    sparkles: <><path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5L18 18M6 18l2.5-2.5M15.5 8.5L18 6"/></>,
    drag: <><circle cx="9" cy="6" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="9" cy="18" r="1"/><circle cx="15" cy="6" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="18" r="1"/></>,
    filter: <><path d="M4 5h16l-6 8v6l-4-2v-4L4 5z"/></>,
    fire: <><path d="M12 3c2 4-1 5 1 8 1.5 2 4 2 4 5a5 5 0 0 1-10 0c0-3 2-4 2-7 0-2 2-4 3-6z"/></>,
    weight: <><path d="M5 8h14l-1 13H6L5 8zM9 8a3 3 0 0 1 6 0"/></>,
    line: <><path d="M3 12c0-5 4-8 9-8s9 3 9 8c0 4-4 7-9 7-1 0-2-.1-3-.3L4 21l1.5-4C4 16 3 14 3 12z"/></>,
    sun: <><circle cx="12" cy="12" r="4"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4L7 17M17 7l1.4-1.4"/></>,
    arrowR: <><path d="M5 12h14M13 6l6 6-6 6"/></>,
    bolt: <><path d="M13 3L4 14h7l-1 7 9-11h-7l1-7z"/></>,
    home: <><path d="M3 11l9-8 9 8v10a1 1 0 0 1-1 1h-5v-7H9v7H4a1 1 0 0 1-1-1V11z"/></>,
    list: <><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></>,
    spark: <><path d="M12 2v6M12 16v6M2 12h6M16 12h6"/></>,
    settings: <><circle cx="12" cy="12" r="3"/><path d="M19 12a7 7 0 0 0-.1-1.3l2-1.5-2-3.4-2.3.9a7 7 0 0 0-2.3-1.3L14 3h-4l-.3 2.4a7 7 0 0 0-2.3 1.3L5 5.8 3 9.2l2 1.5A7 7 0 0 0 5 12c0 .4 0 .9.1 1.3l-2 1.5 2 3.4 2.3-.9a7 7 0 0 0 2.3 1.3L10 21h4l.3-2.4a7 7 0 0 0 2.3-1.3l2.3.9 2-3.4-2-1.5c.1-.4.1-.9.1-1.3z"/></>,
    info: <><circle cx="12" cy="12" r="9"/><path d="M12 8v.01M11 12h1v5h1"/></>,
    activity: <><path d="M3 12h4l3-8 4 16 3-8h4"/></>,
    'share-2': <><circle cx="6" cy="12" r="2.5"/><circle cx="18" cy="6" r="2.5"/><circle cx="18" cy="18" r="2.5"/><path d="M8 11l8-4M8 13l8 4"/></>,
    lock: <><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></>,
    shield: <><path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6l8-3z"/></>,
    youtube: <><rect x="2.5" y="6" width="19" height="12" rx="3"/><path d="M11 9.5l4 2.5-4 2.5v-5z" fill="currentColor"/></>,
    megaphone: <><path d="M3 11v3a2 2 0 0 0 2 2h2v3l4-3 8 3V6L11 9H5a2 2 0 0 0-2 2z"/></>,
    slides: <><rect x="3" y="4" width="18" height="13" rx="2"/><path d="M3 13l5-3 4 2 5-4 4 3M8 21h8M12 17v4"/></>,
    eye: <><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></>,
    refresh: <><path d="M21 12a9 9 0 1 1-3-6.7L21 8"/><path d="M21 3v5h-5"/></>,
    zoom: <><rect x="3" y="6" width="14" height="12" rx="2"/><path d="M17 10l4-2v8l-4-2z"/></>,
    google: <><circle cx="12" cy="12" r="9"/><path d="M12 8v8M8 12h8"/></>,
    star: <><path d="M12 3l2.6 5.3 5.9.8-4.3 4.2 1 5.8L12 16.4 6.8 19l1-5.8L3.5 9.1l5.9-.8L12 3z"/></>,
  };
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className}>
      {paths[name] || null}
    </svg>
  );
};

// ----- Avatar circle -----
const Avatar = ({ user, size = 36, ring = false }) => (
  <div
    className={`flex items-center justify-center rounded-full text-white font-semibold ${ring ? 'ring-2 ring-white' : ''}`}
    style={{ width: size, height: size, background: user.color, fontSize: size * 0.42 }}
  >{user.avatar}</div>
);

// ----- Badge / Pill -----
const Pill = ({ children, color = '#64748B', tint = '#F1F5F9', icon = null, size = 'sm', className = '' }) => {
  const px = size === 'xs' ? 'px-1.5 py-0.5 text-[10px]' : 'px-2 py-0.5 text-[11px]';
  return (
    <span className={`inline-flex items-center gap-1 rounded-full font-medium ${px} ${className}`} style={{ background: tint, color }}>
      {icon}{children}
    </span>
  );
};

// ----- Card -----
const Card = ({ title, action, children, className = '', pad = true, headerClass = '' }) => (
  <div className={`bg-white rounded-2xl shadow-card border border-ink-100 ${className}`}>
    {(title || action) && (
      <div className={`flex items-center justify-between px-5 pt-4 ${pad ? 'pb-3' : ''} ${headerClass}`}>
        <div className="flex items-center gap-2">
          {typeof title === 'string' ? <h3 className="text-sm font-semibold text-ink-800">{title}</h3> : title}
        </div>
        <div>{action}</div>
      </div>
    )}
    <div className={pad ? 'px-5 pb-5' : ''}>{children}</div>
  </div>
);

// ----- Stat tile -----
const Stat = ({ label, value, sub, accent, trend, icon }) => (
  <div className="flex flex-col gap-1">
    <div className="flex items-center gap-2 text-ink-500 text-xs">
      {icon}<span>{label}</span>
    </div>
    <div className="flex items-baseline gap-2">
      <div className="text-2xl font-semibold num text-ink-900" style={{ color: accent }}>{value}</div>
      {sub && <div className="text-xs text-ink-400 num">{sub}</div>}
    </div>
    {trend !== undefined && (
      <div className={`text-[11px] font-medium ${trend >= 0 ? 'text-emerald-600' : 'text-rose-500'}`}>
        {trend >= 0 ? '▲' : '▼'} {Math.abs(trend)}% wow
      </div>
    )}
  </div>
);

// ----- Progress bar -----
const Bar = ({ value, max = 1, color = '#2F5DE5', height = 6, track = '#E6EAF3', className = '' }) => {
  const pct = Math.max(0, Math.min(1, value / max));
  return (
    <div className={`w-full rounded-full overflow-hidden ${className}`} style={{ background: track, height }}>
      <div className="h-full rounded-full transition-all duration-500" style={{ width: `${pct * 100}%`, background: color }} />
    </div>
  );
};

// ----- Ring progress -----
const Ring = ({ value, max = 1, size = 64, stroke = 8, color = '#2F5DE5', track = '#E6EAF3', children }) => {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const pct = Math.max(0, Math.min(1, value / max));
  return (
    <div className="relative inline-flex items-center justify-center" style={{ width: size, height: size }}>
      <svg width={size} height={size} className="-rotate-90">
        <circle cx={size/2} cy={size/2} r={r} stroke={track} strokeWidth={stroke} fill="none" />
        <circle cx={size/2} cy={size/2} r={r} stroke={color} strokeWidth={stroke} fill="none"
                strokeDasharray={c} strokeDashoffset={c * (1 - pct)} strokeLinecap="round"
                style={{ transition: 'stroke-dashoffset .6s ease' }} />
      </svg>
      <div className="absolute inset-0 flex items-center justify-center">{children}</div>
    </div>
  );
};

// ----- Modal -----
const Modal = ({ open, onClose, title, children, footer, size = 'md' }) => {
  if (!open) return null;
  const w = size === 'lg' ? 'max-w-2xl' : size === 'sm' ? 'max-w-sm' : 'max-w-md';
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-ink-900/40 backdrop-blur-sm" onClick={onClose}>
      <div className={`bg-white rounded-2xl shadow-lift w-full ${w} animate-[fadeIn_.2s_ease]`} onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between px-5 py-4 border-b border-ink-100">
          <h3 className="text-sm font-semibold text-ink-900">{title}</h3>
          <button onClick={onClose} className="text-ink-400 hover:text-ink-700"><Icon name="x" /></button>
        </div>
        <div className="px-5 py-4">{children}</div>
        {footer && <div className="px-5 py-3 border-t border-ink-100 bg-ink-50/50 rounded-b-2xl">{footer}</div>}
      </div>
    </div>
  );
};

// ----- Tabs -----
const Tabs = ({ tabs, active, onChange, variant = 'pill', size = 'md' }) => {
  if (variant === 'underline') {
    return (
      <div className="flex items-center gap-6 border-b border-ink-100">
        {tabs.map(t => (
          <button
            key={t.id}
            onClick={() => onChange(t.id)}
            className={`relative py-2.5 text-sm font-medium transition-colors ${active === t.id ? 'text-ink-900' : 'text-ink-400 hover:text-ink-700'}`}
          >
            <span className="flex items-center gap-2">{t.icon}{t.label}</span>
            {active === t.id && <span className="absolute left-0 right-0 -bottom-px h-0.5 bg-brand-500 rounded-full" />}
          </button>
        ))}
      </div>
    );
  }
  return (
    <div className="inline-flex bg-ink-100/70 p-1 rounded-xl">
      {tabs.map(t => (
        <button key={t.id} onClick={() => onChange(t.id)}
          className={`flex items-center gap-1.5 px-3 ${size === 'sm' ? 'py-1 text-xs' : 'py-1.5 text-sm'} rounded-lg font-medium transition-all ${active === t.id ? 'bg-white shadow-card text-ink-900' : 'text-ink-500 hover:text-ink-800'}`}>
          {t.icon}{t.label}
        </button>
      ))}
    </div>
  );
};

// ----- Button -----
const Btn = ({ variant = 'primary', size = 'md', icon, children, ...rest }) => {
  const sz = size === 'sm' ? 'h-8 px-3 text-xs' : 'h-9 px-3.5 text-sm';
  const variants = {
    primary: 'bg-ink-900 text-white hover:bg-ink-800',
    brand:   'bg-brand-500 text-white hover:bg-brand-600',
    ghost:   'bg-white border border-ink-200 text-ink-700 hover:border-ink-300',
    soft:    'bg-ink-100 text-ink-700 hover:bg-ink-200',
    gold:    'bg-gold-400 text-ink-900 hover:bg-gold-300',
  };
  return (
    <button {...rest} className={`inline-flex items-center gap-1.5 font-medium rounded-lg transition-all ${sz} ${variants[variant]} ${rest.className || ''}`}>
      {icon}{children}
    </button>
  );
};

// ----- Section header -----
const SectionHead = ({ eyebrow, title, sub, right }) => (
  <div className="flex items-end justify-between mb-4">
    <div>
      {eyebrow && <div className="text-[11px] uppercase tracking-[0.14em] font-semibold text-brand-600 mb-1">{eyebrow}</div>}
      <h2 className="text-xl font-semibold text-ink-900">{title}</h2>
      {sub && <p className="text-sm text-ink-500 mt-0.5">{sub}</p>}
    </div>
    {right}
  </div>
);

// ----- Config context (live-editable appointment types / lead sources) -----
const ConfigContext = React.createContext(null);
const useConfig = () => React.useContext(ConfigContext);

Object.assign(window, {
  Icon, Avatar, Pill, Card, Stat, Bar, Ring, Modal, Tabs, Btn, SectionHead,
  ConfigContext, useConfig,
});
