// Primitives.jsx — shared building blocks for Cortex admin UI kit
// Uses Phosphor Icons web font (loaded via CSS in index.html).

// Map semantic React-style names (PhosphorReact naming) to phosphor web classes.
// Only the subset used across the app needs to be here.
const PHOSPHOR_MAP = {
  // nav/product
  HouseIcon: 'house', RocketLaunchIcon: 'rocket-launch', KanbanIcon: 'kanban',
  BookOpenIcon: 'book-open', MedalIcon: 'medal', FlagIcon: 'flag',
  ChartLineUpIcon: 'chart-line-up', LightningIcon: 'lightning', PlugIcon: 'plug',
  BinocularsIcon: 'binoculars', TableIcon: 'table', GraphIcon: 'graph',
  FileCodeIcon: 'file-code', IdentificationCardIcon: 'identification-card',
  WrenchIcon: 'wrench', FoldersIcon: 'folders', UsersThreeIcon: 'users-three',
  UsersIcon: 'users', HandshakeIcon: 'handshake', CalendarBlankIcon: 'calendar-blank',
  SparkleIcon: 'sparkle', BugIcon: 'bug', BrainIcon: 'brain',
  RobotIcon: 'robot', CodeIcon: 'code', DatabaseIcon: 'database',
  StackIcon: 'stack', GearIcon: 'gear',
  // actions/controls
  MagnifyingGlassIcon: 'magnifying-glass', CaretDownIcon: 'caret-down',
  CaretUpDownIcon: 'caret-up-down', CaretRightIcon: 'caret-right',
  CaretLeftIcon: 'caret-left', ArrowLeftIcon: 'arrow-left',
  ArrowRightIcon: 'arrow-right', ArrowUpRightIcon: 'arrow-up-right',
  PlusIcon: 'plus', CheckIcon: 'check', XIcon: 'x',
  BellIcon: 'bell', QuestionIcon: 'question', PencilIcon: 'pencil',
  DownloadIcon: 'download', ShareNetworkIcon: 'share-network',
  ChatCircleIcon: 'chat-circle', PresentationIcon: 'presentation-chart',
  PlayIcon: 'play', FunnelIcon: 'funnel', SlidersIcon: 'sliders',
  TrendUpIcon: 'trend-up', TrendDownIcon: 'trend-down',
  CheckCircleIcon: 'check-circle', CircleDashedIcon: 'circle-dashed',
  UserCircleIcon: 'user-circle', GitBranchIcon: 'git-branch',
  GitMergeIcon: 'git-merge', ClockIcon: 'clock', FireIcon: 'fire',
  TargetIcon: 'target', BroadcastIcon: 'broadcast', ListChecksIcon: 'list-checks',
  PackageIcon: 'package', PaperPlaneIcon: 'paper-plane-tilt',
  SalesforceIcon: 'cloud', BracketsCurlyIcon: 'brackets-curly',
  WarningIcon: 'warning', WarningCircleIcon: 'warning-circle', StarIcon: 'star', LifebuoyIcon: 'lifebuoy',
  MegaphoneIcon: 'megaphone', CurrencyDollarIcon: 'currency-dollar',
  FunnelSimpleIcon: 'funnel-simple', TrayIcon: 'tray',
};

// Icon: fetches Phosphor SVG once, caches, inlines with currentColor fill.
const __iconCache = new Map();
const __iconListeners = new Map();

function fetchIconSvg(url) {
  if (__iconCache.has(url)) return Promise.resolve(__iconCache.get(url));
  if (__iconListeners.has(url)) return new Promise(res => __iconListeners.get(url).push(res));
  __iconListeners.set(url, []);
  return fetch(url).then(r => r.text()).then(svg => {
    // Strip width/height; ensure it inherits currentColor.
    svg = svg
      .replace(/<svg([^>]*?)\swidth="[^"]*"/, '<svg$1')
      .replace(/<svg([^>]*?)\sheight="[^"]*"/, '<svg$1')
      .replace(/<svg /, '<svg fill="currentColor" width="100%" height="100%" ');
    __iconCache.set(url, svg);
    (__iconListeners.get(url) || []).forEach(res => res(svg));
    __iconListeners.delete(url);
    return svg;
  }).catch(() => '');
}

function Icon({ name, size = 16, weight = 'regular', color, className = '', style }) {
  const slug = PHOSPHOR_MAP[name] || name.replace(/Icon$/, '').replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  const w = weight === 'fill' ? 'fill' : weight === 'bold' ? 'bold' : 'regular';
  const suffix = w === 'regular' ? '' : `-${w}`;
  const url = `https://cdn.jsdelivr.net/npm/@phosphor-icons/core@2.1.1/assets/${w}/${slug}${suffix}.svg`;
  const [svg, setSvg] = React.useState(() => __iconCache.get(url) || null);
  React.useEffect(() => {
    if (__iconCache.has(url)) { setSvg(__iconCache.get(url)); return; }
    let alive = true;
    fetchIconSvg(url).then(s => { if (alive) setSvg(s); });
    return () => { alive = false; };
  }, [url]);
  return (
    <span
      className={className}
      aria-hidden="true"
      style={{
        display: 'inline-flex',
        width: size, height: size,
        color: color || 'currentColor',
        flex: '0 0 auto',
        verticalAlign: '-0.15em',
        alignItems: 'center',
        justifyContent: 'center',
        ...style,
      }}
      dangerouslySetInnerHTML={svg ? { __html: svg } : undefined}
    />
  );
}

function Button({ variant = 'secondary', size, icon, iconRight, children, onClick, className = '', ...rest }) {
  const cls = ['btn', `btn-${variant}`, size === 'sm' ? 'btn-sm' : '', icon && !children ? 'btn-icon' : '', className].filter(Boolean).join(' ');
  return (
    <button className={cls} onClick={onClick} {...rest}>
      {icon && <Icon name={icon} size={size === 'sm' ? 12 : 14} />}
      {children}
      {iconRight && <Icon name={iconRight} size={size === 'sm' ? 12 : 14} />}
    </button>
  );
}

function Badge({ variant = 'neutral', dot, children }) {
  return (
    <span className={`badge b-${variant}`}>
      {dot && <span className="dot" />}
      {children}
    </span>
  );
}

function Input({ icon, ...rest }) {
  if (!icon) return <input className="inp" {...rest} />;
  return (
    <div style={{ position: 'relative' }}>
      <Icon name={icon} size={14} style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-neutral-subtle)' }} />
      <input className="inp" style={{ paddingLeft: 32 }} {...rest} />
    </div>
  );
}

function Avatar({ initials, n = 1, size = 22 }) {
  return <div className={`avatar n${n}`} style={{ width: size, height: size, fontSize: size * 0.45 }}>{initials}</div>;
}

function Checkbox({ checked, onChange }) {
  return (
    <span className={`chk ${checked ? 'on' : ''}`} onClick={() => onChange && onChange(!checked)}>
      {checked && <Icon name="CheckIcon" size={10} weight="bold" color="#fff" />}
    </span>
  );
}

function Card({ title, description, action, children, className = '', bodyClassName = 'card-body' }) {
  return (
    <div className={`card ${className}`}>
      {(title || action) && (
        <div className="card-header">
          <div>
            {title && <div className="card-title">{title}</div>}
            {description && <div className="card-sub">{description}</div>}
          </div>
          {action}
        </div>
      )}
      <div className={bodyClassName}>{children}</div>
    </div>
  );
}

// Simple SVG Cortex X-lattice mark
function CortexMark({ size = 18, color = '#fff' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 164 164" fill="none" aria-hidden="true">
      <path fill={color} d="M13.9 3.4L3.4 13.9L25.9 36.4C51.2 61.8 51.2 102.8 25.8 128.2L3.4 150.6L13.9 161.1L36.4 138.7C61.7 113.4 102.7 113.3 128.1 138.6L150.6 161.1L161.1 150.6L138.6 128.1C113.3 102.7 113.4 61.7 138.7 36.4L161.1 13.9L150.6 3.4L128.2 25.8C102.8 51.2 61.8 51.2 36.4 25.9L13.9 3.4ZM101.1 101.1V63.4H63.4V101.1H101.1Z" />
    </svg>
  );
}

Object.assign(window, { Icon, Button, Badge, Input, Avatar, Checkbox, Card, CortexMark });
