// ─── Primitivas visuales compartidas ───────────────────────────────
// Piezas chicas reusadas por TODO el bundle: GlowCard (wrapper con spotlight de
// mouse), StatusPill (pill de STATUS_CONFIG), KpiCard (tile de KPI con
// sparkline), Avatar (iniciales con color), Sparkline (mini área+línea),
// IdDateCell (celda id+fecha, primera columna de toda lista), TablePill (pill
// de tono genérico para celdas de tabla) y los controles de formulario
// AltaSelect (select con chevron propio) + ReadOnlyField (campo bloqueado con
// candado). Extraídas de screens-list.jsx (GlowCard/StatusPill/KpiCard/Avatar/
// Sparkline) y entity-list.jsx (IdDateCell/TablePill) en P4; AltaSelect/
// ReadOnlyField promovidas acá en P6 desde screens-nuevo.jsx (compuerta 1,
// hallazgo 4: ui/record-form.jsx y ui/party-selector.jsx las consumían desde
// una pantalla — dependencia ui→screens invertida). Expone a window: GlowCard,
// StatusPill, KpiCard, Avatar, Sparkline, IdDateCell, TablePill, AltaSelect,
// ReadOnlyField. Consume window.STATUS_CONFIG (dominio/pipeline.js),
// window.formatDate (dominio/formato.js) e IconChevronDown (ui/icons.jsx). Se
// carga en el bloque `ui` de Micos ERP.html, antes de ui/entity-list.jsx (que
// usa KpiCard) y de las screens que usan cualquiera de estas piezas.

const { useRef: _usePrimRef } = React;

// ─── Glow card wrapper (mouse spotlight) ─────────
function GlowCard({ children, className = '', onClick, ...rest }) {
  const ref = _usePrimRef(null);
  const handle = (e) => {
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    el.style.setProperty('--mx', `${e.clientX - r.left}px`);
    el.style.setProperty('--my', `${e.clientY - r.top}px`);
  };
  return (
    <div ref={ref} onMouseMove={handle} onClick={onClick} className={`glow-card ${className}`} {...rest}>
      {children}
    </div>
  );
}

// ─── Status pill ─────────────────────────────────
function StatusPill({ status, size = 'md' }) {
  const cfg = STATUS_CONFIG[status];
  if (!cfg) return null;
  return (
    <span className={`pill ${cfg.pill}`} style={size === 'sm' ? { padding: '4px 12px', fontSize: '10.5px' } : {}}>
      {cfg.label}
    </span>
  );
}

// ─── Avatar (colored initials) ───────────────────
function Avatar({ name, size = 32 }) {
  const init = name.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase();
  return (
    <div
      className="flex items-center justify-center rounded-full text-[10.5px] font-extrabold flex-shrink-0"
      style={{
        width: size,
        height: size,
        background: 'color-mix(in oklab, var(--accent) 14%, transparent)',
        color: 'var(--accent)',
        letterSpacing: '0.02em',
      }}
    >
      {init}
    </div>
  );
}

// ─── KPI card (icon + value + optional sparkline) ───
// Sparkline: pass `trend` as a number[] of arbitrary length; renders as a
// thin teal area chart in the bottom-right corner. `deltaTone` se conserva
// SOLO para el color del sparkline (neg = rojo) — API real de este componente:
// label + value + trend + deltaTone (+ icon). P4: se borró el soporte del prop
// `highlighted` (declarado pero nunca leído en el cuerpo, bug del mapa) — no
// tenía `delta` desde antes de este paquete. Los callers viejos que todavía
// pasan `delta`/`highlighted` (~84, ver mapa) siguen andando sin cambios: React
// ignora props que el componente no declara; se limpian recién en P6-P10
// cuando se toque cada pantalla.
function KpiCard({ label, value, deltaTone = 'pos', icon: Icon, trend }) {
  return (
    <div
      className="kpi-card-tile relative rounded-2xl p-5 sm:p-6 transition-all duration-300 overflow-hidden"
      style={{
        background: 'var(--card)',
        border: '1px solid color-mix(in oklab, var(--border) 60%, transparent)',
        boxShadow: 'var(--shadow-card)',
        // Altura reservada: igual a cuando había "delta" debajo del value, para
        // que sacar/poner esa info extra no cambie la altura de la tarjeta.
        minHeight: '152px',
      }}
    >
      {/* Sparkline (bottom-right, optional) */}
      {trend && trend.length > 1 && (
        <Sparkline data={trend} positive={deltaTone !== 'neg'} />
      )}

      <div className="relative flex items-start justify-between gap-3">
        <p className="text-[10.5px] font-bold uppercase tracking-[0.14em]" style={{ color: 'var(--muted-foreground)' }}>
          {label}
        </p>
        {Icon && (
          <span
            className="inline-flex items-center justify-center rounded-xl flex-shrink-0"
            style={{
              width: 34,
              height: 34,
              background: 'color-mix(in oklab, var(--accent) 12%, transparent)',
              color: 'var(--accent)',
            }}
          >
            <Icon size={16} />
          </span>
        )}
      </div>
      <p
        className="relative text-[clamp(26px,4vw,34px)] font-extrabold tabular-nums tracking-tight leading-none mt-4"
        style={{ color: 'var(--foreground)' }}
      >
        {value}
      </p>
    </div>
  );
}

// ─── Sparkline (compact area + line) ──────────────────────────
function Sparkline({ data, positive = true, width = 90, height = 36 }) {
  if (!data || data.length < 2) return null;
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const stepX = width / (data.length - 1);
  const points = data.map((v, i) => {
    const x = i * stepX;
    const y = height - ((v - min) / range) * (height - 4) - 2;
    return [x, y];
  });
  const linePath = points.map(([x, y], i) => (i === 0 ? `M${x},${y}` : `L${x},${y}`)).join(' ');
  const areaPath = `${linePath} L${width},${height} L0,${height} Z`;
  const stroke = positive ? 'var(--accent)' : 'var(--danger)';
  const gradId = 'spark-grad-' + Math.random().toString(36).slice(2, 8);
  return (
    <svg
      width={width}
      height={height}
      viewBox={`0 0 ${width} ${height}`}
      className="absolute bottom-3 right-3 pointer-events-none opacity-90"
      aria-hidden="true"
    >
      <defs>
        <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={stroke} stopOpacity="0.32" />
          <stop offset="100%" stopColor={stroke} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={areaPath} fill={`url(#${gradId})`} />
      <path d={linePath} fill="none" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ─── Standard "ID + creation date" first-cell ──────
// Used as the first column for every list view (particulares, médicos,
// entidades, inventario, compras, logística, caja chica, expedientes…)
function IdDateCell({ id, date }) {
  return (
    <div className="min-w-0">
      <span className="font-mono text-[12.5px] font-bold tracking-wide uppercase" style={{ color: 'var(--accent)' }}>
        {id}
      </span>
      <p className="text-[11.5px] mt-1 tabular-nums" style={{ color: 'var(--muted-foreground)' }}>
        {formatDate(date)}
      </p>
    </div>
  );
}

// ─── Reusable Table pill ──────────────────────────
function TablePill({ label, tone = 'neutral' }) {
  const TONES = {
    neutral: { bg: 'color-mix(in oklab, var(--muted-foreground) 12%, transparent)', fg: 'var(--muted-foreground)' },
    accent:  { bg: 'color-mix(in oklab, var(--accent) 14%, transparent)',           fg: 'var(--accent)' },
    pos:     { bg: 'rgba(5, 150, 105, 0.14)',                                       fg: 'var(--success)' },
    neg:     { bg: 'rgba(239, 68, 68, 0.18)',                                       fg: '#ef4444' },
    warn:    { bg: 'rgba(217, 119, 6, 0.16)',                                       fg: 'var(--warning)' },
    info:    { bg: 'rgba(59, 130, 246, 0.14)',                                      fg: '#3b82f6' },
  };
  const t = TONES[tone] || TONES.neutral;
  return (
    <span
      className="inline-flex items-center font-bold uppercase tracking-[0.06em]"
      style={{
        background: t.bg,
        color: t.fg,
        padding: '4px 10px',
        borderRadius: 999,
        fontSize: '10.5px',
        letterSpacing: '0.08em',
      }}
    >
      {label}
    </span>
  );
}

// ─── Controles de formulario compartidos (P6, ex screens-nuevo.jsx) ───────
// Estilo para inputs read-only (mismo alto que AltaSelect), marcadamente
// deshabilitados: texto atenuado, fondo grisado, borde punteado (regla §4 del
// CLAUDE.md del bundle — esta pareja ES la referencia de esa regla).
const ALTA_RO = {
  height: '2.25rem',
  opacity: 1,
  cursor: 'not-allowed',
  color: 'var(--muted-foreground)',
  WebkitTextFillColor: 'var(--muted-foreground)',
  background: 'color-mix(in oklab, var(--muted-foreground) 9%, transparent)',
  border: '1px dashed color-mix(in oklab, var(--border) 85%, transparent)',
  paddingRight: '2rem',
};

const LockGlyph = () => (
  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <rect x="4" y="11" width="16" height="9" rx="2" />
    <path d="M8 11V8a4 4 0 0 1 8 0v3" />
  </svg>
);

// Select con chevron propio (la flecha nativa se ve mal con el estilo .input)
function AltaSelect({ value, onChange, children, style }) {
  return (
    <div className="relative">
      <select className="input" value={value} onChange={onChange}
        style={{ height: '2.25rem', appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none', paddingRight: '2rem', ...(style || {}) }}>
        {children}
      </select>
      <span className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none" style={{ color: 'var(--muted-foreground)' }}>
        <IconChevronDown size={14} />
      </span>
    </div>
  );
}

// Campo de solo lectura (claramente deshabilitado, con candado)
function ReadOnlyField({ label, value }) {
  return (
    <div className="space-y-1.5">
      <p className="text-[10px] font-bold uppercase tracking-[0.12em]" style={{ color: 'var(--muted-foreground)' }}>{label}</p>
      <div className="relative" title="Campo automático (no editable)">
        <input className="input" disabled readOnly value={value} style={ALTA_RO} />
        <span className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"
          style={{ color: 'color-mix(in oklab, var(--muted-foreground) 65%, transparent)' }}>
          <LockGlyph />
        </span>
      </div>
    </div>
  );
}

Object.assign(window, { GlowCard, StatusPill, KpiCard, Avatar, Sparkline, IdDateCell, TablePill, AltaSelect, ReadOnlyField });
