// src/primitives.jsx — small, reusable UI atoms for the Piixi product surface.
// All names prefixed Ax to avoid global collisions with React/Babel scope.

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

// ─────────────────────────────────────────────────────────────────────────────
// ICONS — inline SVG only, single-color, 2px stroke (matches design system rule)
// ─────────────────────────────────────────────────────────────────────────────
const AxIcon = ({ name, size = 16, style }) => {
  const s = size;
  const c = 'currentColor';
  const stroke = { stroke: c, strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round', fill: 'none' };
  const sv = { width: s, height: s, viewBox: '0 0 24 24', display: 'block', ...style };
  switch (name) {
    case 'home':       return <svg {...sv}><path {...stroke} d="M3 11l9-7 9 7v9a1 1 0 0 1-1 1h-5v-7h-6v7H4a1 1 0 0 1-1-1z"/></svg>;
    case 'upload':     return <svg {...sv}><path {...stroke} d="M12 16V4M6 10l6-6 6 6M4 20h16"/></svg>;
    case 'inbox':      return <svg {...sv}><path {...stroke} d="M3 14h5l1 2h6l1-2h5M5 4h14l2 10v5a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-5z"/></svg>;
    case 'folder':     return <svg {...sv}><path {...stroke} d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>;
    case 'book':       return <svg {...sv}><path {...stroke} d="M4 4h12a3 3 0 0 1 3 3v13H7a3 3 0 0 1-3-3zM4 17a3 3 0 0 1 3-3h12"/></svg>;
    case 'tag':        return <svg {...sv}><path {...stroke} d="M3 12V4h8l10 10-8 8z"/><circle {...stroke} cx="7.5" cy="7.5" r="1.2"/></svg>;
    case 'settings':   return <svg {...sv}><circle {...stroke} cx="12" cy="12" r="3"/><path {...stroke} d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>;
    case 'search':     return <svg {...sv}><circle {...stroke} cx="11" cy="11" r="7"/><path {...stroke} d="m21 21-4.3-4.3"/></svg>;
    case 'arrow-right':return <svg {...sv}><path {...stroke} d="M5 12h14M13 5l7 7-7 7"/></svg>;
    case 'arrow-left': return <svg {...sv}><path {...stroke} d="M19 12H5M11 5l-7 7 7 7"/></svg>;
    case 'arrow-up':   return <svg {...sv}><path {...stroke} d="M12 19V5M5 12l7-7 7 7"/></svg>;
    case 'check':      return <svg {...sv}><path {...stroke} d="m4 12 5 5L20 6"/></svg>;
    case 'x':          return <svg {...sv}><path {...stroke} d="M6 6l12 12M18 6 6 18"/></svg>;
    case 'plus':       return <svg {...sv}><path {...stroke} d="M12 5v14M5 12h14"/></svg>;
    case 'dots':       return <svg {...sv}><circle cx="5" cy="12" r="1.4" fill={c}/><circle cx="12" cy="12" r="1.4" fill={c}/><circle cx="19" cy="12" r="1.4" fill={c}/></svg>;
    case 'chevron-right': return <svg {...sv}><path {...stroke} d="m9 6 6 6-6 6"/></svg>;
    case 'chevron-down':  return <svg {...sv}><path {...stroke} d="m6 9 6 6 6-6"/></svg>;
    case 'pdf':        return <svg {...sv}><path {...stroke} d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path {...stroke} d="M14 3v5h5"/></svg>;
    case 'drive':      return <svg {...sv}><path {...stroke} d="m7 4 5 9-3 5-5-9zM7 4h10l5 9-5 9H9"/></svg>;
    case 'refresh':    return <svg {...sv}><path {...stroke} d="M3 12a9 9 0 0 1 16-5l2 2M21 12a9 9 0 0 1-16 5l-2-2M21 4v5h-5M3 20v-5h5"/></svg>;
    case 'shield':     return <svg {...sv}><path {...stroke} d="M12 3 4 6v6c0 5 3.5 8.4 8 9 4.5-.6 8-4 8-9V6z"/></svg>;
    case 'eye':        return <svg {...sv}><path {...stroke} d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle {...stroke} cx="12" cy="12" r="3"/></svg>;
    case 'eye-off':    return <svg {...sv}><path {...stroke} d="M1 1l22 22M10.6 6.1a11 11 0 0 1 1.4-.1c7 0 11 7 11 7a14 14 0 0 1-2.6 3.4M6.1 6.1A14 14 0 0 0 1 12s4 7 11 7c2 0 3.7-.5 5.2-1.3M9 9a3 3 0 0 0 4.2 4.2"/></svg>;
    case 'edit':       return <svg {...sv}><path {...stroke} d="M12 20h9M16.5 3.5a2.1 2.1 0 1 1 3 3L7 19l-4 1 1-4z"/></svg>;
    case 'trash':      return <svg {...sv}><path {...stroke} d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>;
    case 'copy':       return <svg {...sv}><rect {...stroke} x="9" y="9" width="13" height="13" rx="2"/><path {...stroke} d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>;
    case 'info':       return <svg {...sv}><circle {...stroke} cx="12" cy="12" r="9"/><path {...stroke} d="M12 8h.01M11 12h1v5h1"/></svg>;
    case 'alert':      return <svg {...sv}><path {...stroke} d="m10.3 3.9-8.1 14a2 2 0 0 0 1.7 3h16.2a2 2 0 0 0 1.7-3l-8.1-14a2 2 0 0 0-3.4 0z"/><path {...stroke} d="M12 9v4M12 17h.01"/></svg>;
    case 'help':       return <svg {...sv}><circle {...stroke} cx="12" cy="12" r="9"/><path {...stroke} d="M9.5 9a2.5 2.5 0 1 1 4 2c-.7.4-1.5 1-1.5 2v.5M12 17h.01"/></svg>;
    case 'logo':       return <svg {...sv} viewBox="0 0 24 24"><rect x="2" y="2" width="20" height="20" rx="4" fill="#0A0A0A"/><circle cx="17" cy="17" r="2.8" fill="#00FF88"/></svg>;
    case 'bell':       return <svg {...sv}><path {...stroke} d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9M10 21a2 2 0 0 0 4 0"/></svg>;
    case 'user':       return <svg {...sv}><circle {...stroke} cx="12" cy="8" r="4"/><path {...stroke} d="M4 21a8 8 0 0 1 16 0"/></svg>;
    case 'mail':       return <svg {...sv}><rect {...stroke} x="3" y="5" width="18" height="14" rx="2"/><path {...stroke} d="m3 7 9 7 9-7"/></svg>;
    case 'phone':      return <svg {...sv}><path {...stroke} d="M22 16.9V20a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2 4.2 2 2 0 0 1 4 2h3.1a2 2 0 0 1 2 1.7c.1 1 .4 1.9.7 2.8a2 2 0 0 1-.4 2.1L8 10a16 16 0 0 0 6 6l1.4-1.4a2 2 0 0 1 2.1-.4c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.7 2z"/></svg>;
    case 'map':        return <svg {...sv}><path {...stroke} d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0 1 18 0z"/><circle {...stroke} cx="12" cy="10" r="3"/></svg>;
    case 'cal':        return <svg {...sv}><rect {...stroke} x="3" y="5" width="18" height="16" rx="2"/><path {...stroke} d="M8 3v4M16 3v4M3 11h18"/></svg>;
    case 'filter':     return <svg {...sv}><path {...stroke} d="M3 5h18l-7 9v6l-4-2v-4z"/></svg>;
    case 'sort':       return <svg {...sv}><path {...stroke} d="M3 6h13M3 12h9M3 18h5M17 8V20M14 17l3 3 3-3"/></svg>;
    case 'cloud':      return <svg {...sv}><path {...stroke} d="M17 18a4 4 0 0 0 1-7.8A6 6 0 0 0 6 9.5 4 4 0 0 0 7 18z"/></svg>;
    case 'play':       return <svg {...sv}><path {...stroke} d="m6 4 14 8-14 8z"/></svg>;
    case 'pause':      return <svg {...sv}><path {...stroke} d="M6 4h4v16H6zM14 4h4v16h-4z"/></svg>;
    default: return null;
  }
};

// ─────────────────────────────────────────────────────────────────────────────
// BUTTON
// ─────────────────────────────────────────────────────────────────────────────
function AxButton({ variant = 'secondary', size = 'md', icon, iconRight, children, onClick, disabled, loading, style, type = 'button', title }) {
  const className = `ax-btn ax-btn--${variant}${size !== 'md' ? ' ax-btn--' + size : ''}`;
  return (
    <button type={type} className={className} disabled={disabled || loading} onClick={onClick} style={style} title={title}>
      {loading ? <span className="ax-spinner"/> : icon ? <AxIcon name={icon} size={size === 'sm' ? 13 : 15}/> : null}
      {children ? <span>{children}</span> : null}
      {iconRight ? <AxIcon name={iconRight} size={size === 'sm' ? 13 : 15}/> : null}
    </button>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// PILL
// ─────────────────────────────────────────────────────────────────────────────
function AxPill({ tone = 'neutral', dot, children, style }) {
  return (
    <span className={`ax-pill ax-pill--${tone}`} style={style}>
      {dot ? <span className="ax-pill-dot"/> : null}
      {children}
    </span>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// FIELD (label-above-field, helper, error)
// ─────────────────────────────────────────────────────────────────────────────
function AxField({ label, required, helper, error, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      {label ? (
        <label className="ax-field-label">
          {label}{required ? <span className="req">*</span> : null}
        </label>
      ) : null}
      {children}
      {error ? <div className="ax-field-error">{error}</div> : helper ? <div className="ax-field-helper">{helper}</div> : null}
    </div>
  );
}

function AxInput(props) { return <input className="ax-input" {...props}/>; }
function AxTextarea(props) { return <textarea className="ax-textarea" {...props}/>; }
function AxSelect({ children, ...props }) { return <select className="ax-select" {...props}>{children}</select>; }

// ─────────────────────────────────────────────────────────────────────────────
// STATUS PILL (looks up status code → label + tone)
// ─────────────────────────────────────────────────────────────────────────────
function AxStatusPill({ code }) {
  const s = AdmixData.STATUSES[code];
  if (!s) return <AxPill>{code}</AxPill>;
  return <AxPill tone={s.pill}>{s.label}</AxPill>;
}

// ─────────────────────────────────────────────────────────────────────────────
// RAMO TAG (mono code + readable label tooltip)
// ─────────────────────────────────────────────────────────────────────────────
function AxRamoTag({ code, showLabel }) {
  if (!code) return <span style={{ color: 'var(--ax-fg-faint)' }}>—</span>;
  const label = AdmixData.formatRamoLabel(code);
  return (
    <span title={label} className="ax-mono" style={{
      fontSize: 10, letterSpacing: '0.12em',
      color: 'var(--ax-fg-muted)', textTransform: 'uppercase',
      border: '1px solid var(--ax-border-strong)',
      padding: '2px 6px', borderRadius: 3,
      display: 'inline-flex', alignItems: 'center', gap: 6,
    }}>
      {code}
      {showLabel ? <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--ax-fg)' }}>{label}</span> : null}
    </span>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// CARRIER AVATAR — tiny monogram, deterministic color
// ─────────────────────────────────────────────────────────────────────────────
const CARRIER_COLORS = {
  gnp:      '#3DA168',  // GNP brand-ish
  axa:      '#3E5BFF',
  metlife:  '#0098CD',
  qualitas: '#D0A93E',
  zurich:   '#1B6EBF',
};
function AxCarrierAvatar({ id, size = 24 }) {
  const c = AdmixData.carrierById(id);
  if (!c) return <span style={{ width: size, height: size, display: 'inline-block', borderRadius: 4, background: 'var(--ax-bg-3)', border: '1px solid var(--ax-border)' }}/>;
  const bg = CARRIER_COLORS[id] || '#444';
  return (
    <span style={{
      width: size, height: size, borderRadius: 4,
      background: bg + '22',
      border: '1px solid ' + bg + '44',
      color: bg,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: size * 0.42,
      letterSpacing: '0.04em',
      flexShrink: 0,
    }}>{c.initials}</span>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// AVATAR for clients
// ─────────────────────────────────────────────────────────────────────────────
function AxAvatar({ name, size = 32 }) {
  const initials = (name || '?').split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0].toUpperCase()).join('');
  const hue = Array.from(name || '').reduce((a, ch) => (a + ch.charCodeAt(0)) % 360, 0);
  return (
    <span style={{
      width: size, height: size, borderRadius: '50%',
      background: `hsl(${hue}, 22%, 18%)`,
      border: `1px solid hsl(${hue}, 28%, 28%)`,
      color: `hsl(${hue}, 40%, 72%)`,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: size * 0.4,
      flexShrink: 0,
    }}>{initials}</span>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// EYEBROW — section label
// ─────────────────────────────────────────────────────────────────────────────
function AxEyebrow({ children, color, style }) {
  return <div className="ax-eyebrow" style={{ color: color || 'var(--ax-fg-muted)', ...style }}>{children}</div>;
}

// ─────────────────────────────────────────────────────────────────────────────
// MODAL
// ─────────────────────────────────────────────────────────────────────────────
function AxModal({ open, onClose, title, children, footer, width = 480 }) {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.6)',
      backdropFilter: 'blur(2px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div onClick={(e) => e.stopPropagation()} className="ax-fade-in" style={{
        width, maxWidth: 'calc(100vw - 80px)',
        background: 'var(--ax-bg-2)',
        border: '1px solid var(--ax-border-strong)',
        borderRadius: 10,
        boxShadow: '0 24px 80px rgba(0,0,0,0.6)',
        display: 'flex', flexDirection: 'column',
      }}>
        {title ? (
          <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--ax-border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <h3 style={{ margin: 0, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16, color: 'var(--ax-fg-strong)' }}>{title}</h3>
            <button onClick={onClose} className="ax-btn ax-btn--tertiary" style={{ height: 28, width: 28, padding: 0 }}>
              <AxIcon name="x" size={14}/>
            </button>
          </div>
        ) : null}
        <div style={{ padding: 20 }}>{children}</div>
        {footer ? <div style={{ padding: '14px 20px', borderTop: '1px solid var(--ax-border)', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>{footer}</div> : null}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// EMPTY STATE
// ─────────────────────────────────────────────────────────────────────────────
function AxEmpty({ icon, title, body, action }) {
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: '64px 24px', gap: 14, color: 'var(--ax-fg-muted)', textAlign: 'center',
    }}>
      {icon ? (
        <div style={{
          width: 44, height: 44, borderRadius: 10,
          border: '1px solid var(--ax-border-strong)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--ax-fg-faint)', marginBottom: 4,
        }}><AxIcon name={icon} size={22}/></div>
      ) : null}
      <div style={{ fontSize: 15, color: 'var(--ax-fg-strong)', fontWeight: 500 }}>{title}</div>
      {body ? <div style={{ fontSize: 13, maxWidth: 320 }}>{body}</div> : null}
      {action ? <div style={{ marginTop: 6 }}>{action}</div> : null}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// PAGE — section header pattern reused on every screen
// ─────────────────────────────────────────────────────────────────────────────
function AxPageHeader({ eyebrow, title, subtitle, actions, breadcrumb }) {
  return (
    <div style={{ padding: '24px 32px 18px', borderBottom: '1px solid var(--ax-border)' }}>
      {breadcrumb ? <div style={{ marginBottom: 10, fontSize: 12, color: 'var(--ax-fg-muted)', display: 'flex', alignItems: 'center', gap: 8 }}>{breadcrumb}</div> : null}
      {eyebrow ? <AxEyebrow style={{ marginBottom: 8 }}>{eyebrow}</AxEyebrow> : null}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16 }}>
        <div style={{ minWidth: 0 }}>
          <h1 style={{
            margin: 0, fontFamily: 'var(--font-body)', fontWeight: 600,
            fontSize: 24, color: 'var(--ax-fg-strong)', letterSpacing: '-0.01em',
          }}>{title}</h1>
          {subtitle ? <div style={{ marginTop: 6, color: 'var(--ax-fg-muted)', fontSize: 13 }}>{subtitle}</div> : null}
        </div>
        {actions ? <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>{actions}</div> : null}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// PROVENANCE TAG — where a value came from (UDEE / fingerprint / typed)
// ─────────────────────────────────────────────────────────────────────────────
function AxProvenance({ source, confidence }) {
  if (!source) return null;
  const config = {
    udee:        { label: 'UDEE',        tone: 'accent' },
    fingerprint: { label: 'fingerprint', tone: 'info'   },
    typed:       { label: 'manual',      tone: 'neutral' },
    identity:    { label: 'identidad',   tone: 'ghost' },
  };
  const c = config[source] || config.typed;
  return (
    <span style={{
      fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.1em',
      textTransform: 'uppercase', color: 'var(--ax-fg-faint)',
      display: 'inline-flex', gap: 4, alignItems: 'baseline',
    }}>
      <span>{c.label}</span>
      {confidence != null ? <span style={{ color: 'var(--ax-fg-faint)' }}>· {confidence}%</span> : null}
    </span>
  );
}

Object.assign(window, {
  AxIcon, AxButton, AxPill, AxField, AxInput, AxTextarea, AxSelect,
  AxStatusPill, AxRamoTag, AxCarrierAvatar, AxAvatar, AxEyebrow,
  AxModal, AxEmpty, AxPageHeader, AxProvenance, CARRIER_COLORS,
});
