// Shared UI primitives — INLEARN CRM
// Badges, avatars, stage chips, popovers, etc.

const { useState, useEffect, useRef, useMemo } = React;

// ---------- Avatar ----------
function Avatar({ name, size = 28, color }) {
  const bg = color || avatarColor(name || '?');
  return (
    <div
      style={{
        width: size, height: size, background: bg,
        fontSize: size * 0.4, lineHeight: 1,
      }}
      className="rounded-full text-white font-semibold flex items-center justify-center shrink-0 tracking-tight"
    >
      {initials(name || '?')}
    </div>
  );
}
window.Avatar = Avatar;

// ---------- StageChip ----------
function StageChip({ stageId, size = 'sm' }) {
  const stage = STAGE_BY_ID[stageId]; if (!stage) return null;
  const tok = STAGE_TOKENS[stage.color];
  const py = size === 'lg' ? 'py-1' : 'py-0.5';
  const fs = size === 'lg' ? 'text-xs' : 'text-[11px]';
  return (
    <span
      className={`inline-flex items-center gap-1.5 px-2 ${py} ${fs} font-medium rounded-md`}
      style={{ background: tok.soft, color: tok.text }}
    >
      <span className="w-1.5 h-1.5 rounded-full" style={{ background: tok.dot }} />
      {stage.label}
    </span>
  );
}
window.StageChip = StageChip;

// ---------- SubjectChip ----------
function SubjectChip({ subject, size='sm' }) {
  const tok = SUBJECT_TOKENS[subject] || { soft:'#F1F5F9', text:'#334155', dot:'#64748B' };
  const fs = size === 'lg' ? 'text-xs' : 'text-[11px]';
  return (
    <span
      className={`inline-flex items-center gap-1 px-2 py-0.5 ${fs} font-medium rounded`}
      style={{ background: tok.soft, color: tok.text }}
    >
      {subject}
    </span>
  );
}
window.SubjectChip = SubjectChip;

// ---------- Segment Pill ----------
function SegmentPill({ segment }) {
  const isUni = segment === 'University';
  return (
    <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] font-medium rounded ${
      isUni ? 'bg-violet-50 text-violet-700' : 'bg-sky-50 text-sky-700'
    }`}>
      {isUni ? 'University' : 'High School'}
    </span>
  );
}
window.SegmentPill = SegmentPill;

// ---------- Type Badge (Contact type: Parent / Student) ----------
function TypeBadge({ type }) {
  const styles = {
    Parent:  { bg: 'bg-violet-50',  text: 'text-violet-700',  dot: '#8B5CF6' },
    Student: { bg: 'bg-sky-50',     text: 'text-sky-700',     dot: '#0EA5E9' },
    Other:   { bg: 'bg-slate-100',  text: 'text-slate-700',   dot: '#64748B' },
  };
  const s = styles[type] || styles.Other;
  return (
    <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 ${s.bg} ${s.text} rounded text-[10px] font-medium`}>
      <span className="w-1 h-1 rounded-full" style={{ background: s.dot }}/>
      {type}
    </span>
  );
}
window.TypeBadge = TypeBadge;

// ---------- Button ----------
function Button({ children, variant='secondary', size='md', icon, onClick, className='', type='button', disabled }) {
  const sizes = {
    sm: 'h-7 px-2.5 text-xs gap-1.5',
    md: 'h-9 px-3 text-sm gap-2',
    lg: 'h-10 px-4 text-sm gap-2',
  };
  const variants = {
    primary:   'bg-slate-900 text-white hover:bg-slate-800 border border-slate-900',
    secondary: 'bg-white text-slate-700 hover:bg-slate-50 border border-slate-200',
    ghost:     'bg-transparent text-slate-600 hover:bg-slate-100 border border-transparent',
    brand:     'bg-indigo-600 text-white hover:bg-indigo-700 border border-indigo-600',
    danger:    'bg-white text-rose-600 hover:bg-rose-50 border border-rose-200',
    success:   'bg-emerald-600 text-white hover:bg-emerald-700 border border-emerald-600',
  };
  return (
    <button
      type={type} onClick={onClick} disabled={disabled}
      className={`inline-flex items-center justify-center font-medium rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${sizes[size]} ${variants[variant]} ${className}`}
    >
      {icon}
      {children}
    </button>
  );
}
window.Button = Button;

// ---------- IconButton ----------
function IconButton({ icon, onClick, title, className='', variant='ghost' }) {
  const variants = {
    ghost:   'text-slate-500 hover:text-slate-900 hover:bg-slate-100',
    outline: 'text-slate-600 hover:text-slate-900 bg-white border border-slate-200 hover:bg-slate-50',
  };
  return (
    <button title={title} onClick={onClick}
      className={`h-8 w-8 rounded-md inline-flex items-center justify-center transition-colors ${variants[variant]} ${className}`}>
      {icon}
    </button>
  );
}
window.IconButton = IconButton;

// ---------- Card ----------
function Card({ children, className='', as='div', onClick }) {
  const Tag = as;
  return (
    <Tag onClick={onClick}
      className={`bg-white border border-slate-200 rounded-xl ${className}`}>
      {children}
    </Tag>
  );
}
window.Card = Card;

// ---------- Modal shell ----------
function Modal({ open, onClose, children, width = 'max-w-2xl' }) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/40 backdrop-blur-sm" onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()}
        className={`bg-white rounded-2xl shadow-xl border border-slate-200 w-full ${width} max-h-[90vh] flex flex-col overflow-hidden`}>
        {children}
      </div>
    </div>
  );
}
window.Modal = Modal;

// ---------- ConfirmDialog ----------
// Use via the useConfirm() hook below.
function ConfirmDialog({ open, options, onClose }) {
  if (!open || !options) return null;
  const {
    title = 'Are you sure?',
    body,
    confirmLabel = 'Confirm',
    cancelLabel = 'Cancel',
    tone = 'danger',   // 'danger' | 'warning' | 'info'
    onConfirm,
  } = options;

  const toneStyles = {
    danger:  { bg: 'bg-rose-50',   icon: 'text-rose-600',   button: 'danger' },
    warning: { bg: 'bg-amber-50',  icon: 'text-amber-600',  button: 'primary' },
    info:    { bg: 'bg-indigo-50', icon: 'text-indigo-600', button: 'brand' },
  };
  const t = toneStyles[tone] || toneStyles.danger;

  const buttonStyles = {
    danger: 'bg-rose-600 text-white hover:bg-rose-700 border-rose-600',
    primary: 'bg-slate-900 text-white hover:bg-slate-800 border-slate-900',
    brand: 'bg-indigo-600 text-white hover:bg-indigo-700 border-indigo-600',
  };

  const handleConfirm = () => { onConfirm && onConfirm(); onClose(); };

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-slate-900/40 backdrop-blur-sm" onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()}
        className="bg-white rounded-2xl shadow-xl border border-slate-200 w-full max-w-md overflow-hidden animate-in fade-in zoom-in-95">
        <div className="p-5">
          <div className="flex items-start gap-3.5">
            <div className={`h-10 w-10 shrink-0 rounded-full ${t.bg} ${t.icon} flex items-center justify-center`}>
              <Icon.Alert size={18}/>
            </div>
            <div className="flex-1 min-w-0 pt-0.5">
              <h3 className="text-[15px] font-semibold text-slate-900 leading-snug">{title}</h3>
              {body && <p className="text-[13px] text-slate-600 mt-1.5 leading-relaxed">{body}</p>}
            </div>
          </div>
        </div>
        <div className="px-5 py-3 bg-slate-50 border-t border-slate-200 flex items-center justify-end gap-2">
          <button onClick={onClose}
            className="h-9 px-3.5 text-sm font-medium text-slate-700 bg-white border border-slate-200 rounded-md hover:bg-slate-50">
            {cancelLabel}
          </button>
          <button onClick={handleConfirm} autoFocus
            className={`h-9 px-3.5 text-sm font-semibold rounded-md border ${buttonStyles[t.button]}`}>
            {confirmLabel}
          </button>
        </div>
      </div>
    </div>
  );
}
window.ConfirmDialog = ConfirmDialog;

// ---------- Segmented Tabs (Active / Archived toggle) ----------
function SegmentedTabs({ tabs, value, onChange }) {
  return (
    <div className="inline-flex items-center p-0.5 bg-slate-100 rounded-lg">
      {tabs.map(t => {
        const isActive = t.id === value;
        return (
          <button key={t.id} onClick={() => onChange(t.id)}
            className={`h-7 px-3 text-[12px] font-semibold rounded-md transition-all inline-flex items-center gap-1.5 ${
              isActive ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500 hover:text-slate-700'
            }`}>
            {t.dot && <span className="w-1.5 h-1.5 rounded-full" style={{ background: t.dot }}/>}
            {t.label}
            <span className={`text-[10px] tabular-nums px-1.5 h-4 rounded inline-flex items-center font-bold ${
              isActive ? 'bg-slate-100 text-slate-600' : 'bg-slate-200 text-slate-500'
            }`}>{t.count}</span>
          </button>
        );
      })}
    </div>
  );
}
window.SegmentedTabs = SegmentedTabs;
// Returns a tuple [ConfirmElement, confirm].
function useConfirm() {
  const [opts, setOpts] = useState(null);
  const confirm = (options) => setOpts(options);
  const close = () => setOpts(null);
  const Dialog = <ConfirmDialog open={!!opts} options={opts} onClose={close}/>;
  return [Dialog, confirm];
}
window.useConfirm = useConfirm;

// ---------- KPI metric tile ----------
function Metric({ label, value, sub, accent, icon, trend }) {
  return (
    <div className="bg-white border border-slate-200 rounded-xl p-5">
      <div className="flex items-center justify-between mb-3">
        <span className="text-[11px] font-medium tracking-wide uppercase text-slate-500">{label}</span>
        {icon && (
          <div className="h-7 w-7 rounded-md flex items-center justify-center text-slate-500 bg-slate-50">
            {icon}
          </div>
        )}
      </div>
      <div className="flex items-baseline gap-2">
        <div className="text-2xl font-semibold tracking-tight text-slate-900 tabular-nums">{value}</div>
        {trend != null && (
          <span className={`text-[11px] font-medium tabular-nums ${trend >= 0 ? 'text-emerald-600' : 'text-rose-600'}`}>
            {trend >= 0 ? '+' : ''}{trend}%
          </span>
        )}
      </div>
      {sub && <div className="text-xs text-slate-500 mt-1">{sub}</div>}
    </div>
  );
}
window.Metric = Metric;

// ---------- Empty State ----------
function Empty({ title, hint, icon }) {
  return (
    <div className="flex flex-col items-center justify-center text-center py-10 px-4">
      <div className="h-10 w-10 rounded-full bg-slate-100 text-slate-400 flex items-center justify-center mb-3">{icon}</div>
      <div className="text-sm font-medium text-slate-700">{title}</div>
      {hint && <div className="text-xs text-slate-500 mt-1 max-w-xs">{hint}</div>}
    </div>
  );
}
window.Empty = Empty;
