/* AAU CRM — Polaris UI primitives. Exposes components on window. */
const { useState, useEffect, useRef, useMemo } = React;

function Card({ title, subtitle, actions, children, pad, className = '', style }) {
  return (
    <div className={'card ' + className} style={style}>
      {(title || actions) && (
        <div className="card-head">
          {title && <div><div className="ct">{title}</div>{subtitle && <div className="cs">{subtitle}</div>}</div>}
          {actions && <div className="ca">{actions}</div>}
        </div>
      )}
      <div className={pad === false ? '' : 'card-body'}>{children}</div>
    </div>
  );
}

function Badge({ tone = 'neutral', dot, children }) {
  return <span className={'badge ' + tone}>{dot && <span className="dot" />}{children}</span>;
}

function Tag({ children, onRemove }) {
  return <span className="tag">{children}{onRemove && <span className="x" onClick={onRemove}><Icon name="x" size={12} /></span>}</span>;
}

function Avatar({ name, color, size = 32, src }) {
  const init = (name || '?').split(' ').slice(-2).map(w => w[0]).join('').toUpperCase().slice(0, 2);
  return <div className="avatar" style={{ width: size, height: size, fontSize: size * 0.4, background: color || '#5b6cff' }}>{src ? <img src={src} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : init}</div>;
}

function Button({ variant = 'secondary', size, icon, iconRight, children, onClick, disabled, style, title }) {
  const cls = ['btn', 'btn-' + variant, size === 'sm' ? 'btn-sm' : '', !children ? 'btn-icon' : ''].join(' ');
  return (
    <button className={cls} onClick={onClick} disabled={disabled} style={style} title={title}>
      {icon && <Icon name={icon} size={size === 'sm' ? 14 : 16} />}
      {children}
      {iconRight && <Icon name={iconRight} size={size === 'sm' ? 14 : 16} />}
    </button>
  );
}

function IconButton({ name, onClick, title, size = 18 }) {
  return <button className="iconbtn" onClick={onClick} title={title}><Icon name={name} size={size} /></button>;
}

function Field({ label, children }) {
  return <div className="field">{label && <label>{label}</label>}{children}</div>;
}
function Input({ icon, value, onChange, placeholder, type = 'text', style, onKeyDown, autoFocus }) {
  const el = <input className="input" value={value} onChange={e => onChange && onChange(e.target.value)} placeholder={placeholder} type={type} style={style} onKeyDown={onKeyDown} autoFocus={autoFocus} />;
  if (icon) return <div className="input-wrap"><Icon name={icon} size={16} />{el}</div>;
  return el;
}
function Select({ value, onChange, options, style }) {
  return (
    <select className="select" value={value} onChange={e => onChange && onChange(e.target.value)} style={style}>
      {options.map(o => typeof o === 'string' ? <option key={o} value={o}>{o}</option> : <option key={o.value} value={o.value}>{o.label}</option>)}
    </select>
  );
}
function Seg({ value, onChange, options }) {
  return <div className="seg">{options.map(o => { const v = o.value ?? o, l = o.label ?? o; return <button key={v} className={value === v ? 'on' : ''} onClick={() => onChange(v)}>{l}</button>; })}</div>;
}
function PillTabs({ value, onChange, options }) {
  return <div className="pill-tab">{options.map(o => { const v = o.value ?? o, l = o.label ?? o; return <button key={v} className={value === v ? 'on' : ''} onClick={() => onChange(v)}>{l}</button>; })}</div>;
}
function Switch({ on, onChange }) { return <div className={'switch' + (on ? ' on' : '')} onClick={() => onChange(!on)} />; }
function Checkbox({ on, onChange }) { return <div className={'check' + (on ? ' on' : '')} onClick={() => onChange(!on)}>{on && <Icon name="check" size={13} />}</div>; }

function Tabs({ tabs, value, onChange }) {
  return <div className="tabs">{tabs.map(t => { const v = t.value ?? t, l = t.label ?? t; return <button key={v} className={value === v ? 'on' : ''} onClick={() => onChange(v)}>{l}</button>; })}</div>;
}

function KPI({ label, value, delta, deltaDir, sub, icon }) {
  const dir = deltaDir || (delta > 0 ? 'up' : delta < 0 ? 'down' : 'flat');
  return (
    <div className="kpi">
      <div className="kl">{icon && <Icon name={icon} size={14} />}{label}</div>
      <div className="kv tnum">{value}</div>
      {(delta != null || sub) && (
        <div className="row aic g8">
          {delta != null && <span className={'kd ' + dir}><Icon name={dir === 'down' ? 'arrowDown' : 'arrowUp'} size={13} />{typeof delta === 'number' ? Math.abs(delta) + '%' : delta}</span>}
          {sub && <span className="ksub">{sub}</span>}
        </div>
      )}
    </div>
  );
}

function Progress({ value, max = 100, color, height = 7 }) {
  const pct = Math.min(100, Math.round((value / max) * 100));
  return <div className="prog" style={{ height }}><span style={{ width: pct + '%', background: color || undefined }} /></div>;
}

function Drawer({ title, onClose, children, footer, width }) {
  return (
    <div className="scrim right" onClick={onClose}>
      <div className="drawer" style={width ? { width } : null} onClick={e => e.stopPropagation()}>
        <div className="sheet-head"><div className="st">{title}</div><div className="mla"><IconButton name="x" onClick={onClose} /></div></div>
        <div className="sheet-body">{children}</div>
        {footer && <div className="sheet-foot">{footer}</div>}
      </div>
    </div>
  );
}
function Modal({ title, onClose, children, footer, width }) {
  return (
    <div className="scrim center" onClick={onClose}>
      <div className="modal" style={width ? { width } : null} onClick={e => e.stopPropagation()}>
        <div className="sheet-head"><div className="st">{title}</div><div className="mla"><IconButton name="x" onClick={onClose} /></div></div>
        <div className="sheet-body">{children}</div>
        {footer && <div className="sheet-foot">{footer}</div>}
      </div>
    </div>
  );
}

function EmptyState({ icon = 'inbox', title, desc, action }) {
  return <div className="empty"><div className="ei"><Icon name={icon} size={26} /></div><div className="et">{title}</div>{desc && <div className="ed">{desc}</div>}{action && <div className="mt16">{action}</div>}</div>;
}

function PageHead({ title, subtitle, actions, breadcrumb }) {
  return (
    <div>
      {breadcrumb && <div className="breadcrumb">{breadcrumb.map((b, i) => <React.Fragment key={i}>{i > 0 && <span className="sep"><Icon name="chevronRight" size={12} /></span>}{b.href ? <a className="linkish" onClick={b.onClick}>{b.label}</a> : <span>{b.label}</span>}</React.Fragment>)}</div>}
      <div className="page-head">
        <div><div className="pt">{title}</div>{subtitle && <div className="ps">{subtitle}</div>}</div>
        {actions && <div className="actions">{actions}</div>}
      </div>
    </div>
  );
}

// ---- domain helpers ----
function StageChip({ stageId }) {
  const s = AAU.stageById(stageId); if (!s) return null;
  return <span className="badge" style={{ background: s.color + '22', color: s.color }}><span className="dot" style={{ background: s.color }} />{s.code} {s.name}</span>;
}
function GradeBadge({ grade }) {
  const map = { A: 'success', B: 'info', C: 'warning', D: 'neutral' };
  return <span className="badge" style={{ minWidth: 22, justifyContent: 'center' }}><span className={'badge ' + (map[grade] || 'neutral')} style={{ padding: '0 6px' }}>{grade}</span></span>;
}
function SLATag({ sla, left }) {
  const map = { ok: { t: 'success', i: 'clock' }, warn: { t: 'warning', i: 'clock' }, bad: { t: 'critical', i: 'alert' } };
  const m = map[sla] || map.ok;
  return <span className={'badge ' + m.t}><Icon name={m.i} size={12} />{left}</span>;
}
function ChannelDot({ ch, size = 20, showLabel }) {
  const c = AAU.channels[ch]; if (!c) return null;
  return <span className="row aic g6"><span className="center" style={{ width: size, height: size, borderRadius: 6, background: c.color, color: '#fff', fontSize: size * 0.42, fontWeight: 700 }}>{c.short[0]}</span>{showLabel && <span className="t12 fw5">{c.label}</span>}</span>;
}
function HotIcon() { return <span className="hot" title="Hot signal" style={{ display: 'inline-flex' }}><Icon name="fire" size={15} /></span>; }

// ---- playbook helpers ----
function SignalBadge({ signal, compact }) {
  if (!signal) return null;
  const map = { HIGH: { bg: '#fdecea', fg: '#c4320a', dot: '#e8590c' }, MED: { bg: '#fff4e0', fg: '#9a6700', dot: '#f59e0b' }, LOW: { bg: '#eef1f4', fg: '#5a6472', dot: '#94a3b8' } };
  const m = map[signal.level] || map.LOW;
  return (
    <span className="sig-badge" style={{ background: m.bg, color: m.fg }} title={signal.text}>
      <span className="sig-dot" style={{ background: m.dot }} />{signal.level}{!compact && signal.text ? ' · ' + signal.text : ''}
    </span>
  );
}
function ScriptTag({ type }) {
  const meta = (window.PLAYBOOK && PLAYBOOK.scriptTypeMeta[type]) || { label: type, color: '#6b7280' };
  return <span className="script-tag" style={{ background: meta.color + '1c', color: meta.color, borderColor: meta.color + '44' }}>{meta.label}</span>;
}
function BranchTag({ branch }) {
  if (!branch) return null;
  const m = branch === 'A' ? { c: '#2563eb', t: 'Nánh A' } : { c: '#0d9488', t: 'Nhánh B' };
  return <span className="branch-tag" style={{ color: m.c, borderColor: m.c + '40', background: m.c + '12' }}>{branch === 'A' ? 'A' : 'B'}</span>;
}
function LaneTag({ lane }) {
  if (!lane) return null;
  const m = lane === 'hot' ? { c: '#ea580c', t: 'Hot lane' } : { c: '#6366f1', t: 'Nurture' };
  return <span className="lane-tag" style={{ color: m.c, background: m.c + '14' }}>{m.t}</span>;
}
function pbGuide(code) { return (window.PLAYBOOK && PLAYBOOK.guide[code]) || null; }

function Money({ v, m }) { return <span className="tnum">{m ? AAU.fmtVNDm(v) : AAU.fmtVND(v)}</span>; }

// relative time
function relTime(iso) {
  const diff = (Date.now() - new Date(iso).getTime()) / 60000;
  if (diff < 1) return 'vừa xong';
  if (diff < 60) return Math.round(diff) + ' phút';
  if (diff < 1440) return Math.round(diff / 60) + ' giờ';
  return Math.round(diff / 1440) + ' ngày';
}

Object.assign(window, {
  Card, Badge, Tag, Avatar, Button, IconButton, Field, Input, Select, Seg, PillTabs, Switch, Checkbox,
  Tabs, KPI, Progress, Drawer, Modal, EmptyState, PageHead,
  StageChip, GradeBadge, SLATag, ChannelDot, HotIcon, Money, relTime,
  SignalBadge, ScriptTag, BranchTag, LaneTag, pbGuide,
});
