// Shared primitives: buttons, badges, dividers, kbd, etc. All formal / hairline.

const Btn = ({ children, onClick, variant = 'ghost', size = 'md', icon, iconRight, style, active, title, ...rest }) => {
  const sizes = {
    sm: { h: 22, px: 8, fs: 11.5 },
    md: { h: 28, px: 10, fs: 12.5 },
    lg: { h: 34, px: 14, fs: 13 },
  }[size];

  const variants = {
    ghost: {
      background: active ? 'var(--bg-panel-2)' : 'transparent',
      color: 'var(--ink)',
      border: '1px solid transparent',
    },
    line: {
      background: 'var(--bg-elevated)',
      color: 'var(--ink)',
      border: '1px solid var(--line-2)',
    },
    solid: {
      background: 'var(--ink)',
      color: 'var(--bg-panel)',
      border: '1px solid var(--ink)',
    },
    gold: {
      background: 'var(--gold)',
      color: '#FBF8F1',
      border: '1px solid var(--gold)',
    },
    danger: {
      background: 'transparent',
      color: 'var(--status-err)',
      border: '1px solid var(--line-2)',
    },
  }[variant];

  return (
    <button
      onClick={onClick}
      title={title}
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 6,
        height: sizes.h,
        padding: `0 ${sizes.px}px`,
        fontSize: sizes.fs,
        fontWeight: 500,
        letterSpacing: variant === 'solid' || variant === 'gold' ? '0.02em' : '0',
        borderRadius: 2,
        cursor: 'pointer',
        transition: 'background 100ms, border-color 100ms',
        whiteSpace: 'nowrap',
        ...variants,
        ...style,
      }}
      onMouseEnter={(e) => {
        if (variant === 'ghost' && !active) e.currentTarget.style.background = 'var(--bg-panel-2)';
      }}
      onMouseLeave={(e) => {
        if (variant === 'ghost' && !active) e.currentTarget.style.background = 'transparent';
      }}
      {...rest}
    >
      {icon}
      {children}
      {iconRight}
    </button>
  );
};

const IconBtn = ({ icon, onClick, active, title, size = 28, style }) => (
  <button
    onClick={onClick}
    title={title}
    style={{
      width: size,
      height: size,
      display: 'inline-flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: active ? 'var(--ink)' : 'transparent',
      color: active ? 'var(--bg-panel)' : 'var(--ink-2)',
      border: '1px solid transparent',
      borderRadius: 2,
      cursor: 'pointer',
      transition: 'background 100ms',
      ...style,
    }}
    onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'var(--bg-panel-2)'; }}
    onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
  >
    {icon}
  </button>
);

const Kbd = ({ children }) => (
  <span
    className="mono"
    style={{
      display: 'inline-flex',
      alignItems: 'center',
      justifyContent: 'center',
      minWidth: 16,
      height: 16,
      padding: '0 4px',
      fontSize: 10,
      color: 'var(--ink-muted)',
      background: 'var(--bg-panel-2)',
      border: '1px solid var(--line-2)',
      borderRadius: 2,
      letterSpacing: 0,
    }}
  >
    {children}
  </span>
);

const Badge = ({ children, tone = 'neutral', style }) => {
  const tones = {
    neutral: { bg: 'transparent', fg: 'var(--ink-muted)', bd: 'var(--line-2)' },
    ok:      { bg: 'transparent', fg: 'var(--status-ok)', bd: 'var(--status-ok)' },
    warn:    { bg: 'transparent', fg: 'var(--status-warn)', bd: 'var(--status-warn)' },
    err:     { bg: 'transparent', fg: 'var(--status-err)', bd: 'var(--status-err)' },
    info:    { bg: 'transparent', fg: 'var(--status-info)', bd: 'var(--status-info)' },
    gold:    { bg: 'var(--gold-soft)', fg: 'var(--gold)', bd: 'var(--gold)' },
    solid:   { bg: 'var(--ink)', fg: 'var(--bg-panel)', bd: 'var(--ink)' },
  }[tone];
  return (
    <span
      className="mono"
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 4,
        padding: '1px 6px',
        fontSize: 10,
        fontWeight: 500,
        letterSpacing: '0.06em',
        textTransform: 'uppercase',
        color: tones.fg,
        background: tones.bg,
        border: `1px solid ${tones.bd}`,
        borderRadius: 2,
        ...style,
      }}
    >
      {children}
    </span>
  );
};

const Divider = ({ vertical, style }) => (
  <div
    style={{
      background: 'var(--line)',
      ...(vertical
        ? { width: 1, height: '100%', minHeight: 12 }
        : { height: 1, width: '100%' }),
      ...style,
    }}
  />
);

const Row = ({ children, gap = 8, align = 'center', justify = 'flex-start', style, ...rest }) => (
  <div
    style={{
      display: 'flex',
      flexDirection: 'row',
      alignItems: align,
      justifyContent: justify,
      gap,
      ...style,
    }}
    {...rest}
  >
    {children}
  </div>
);

const Col = ({ children, gap = 8, align = 'stretch', style, ...rest }) => (
  <div
    style={{
      display: 'flex',
      flexDirection: 'column',
      alignItems: align,
      gap,
      ...style,
    }}
    {...rest}
  >
    {children}
  </div>
);

const Label = ({ children, style }) => (
  <div
    className="mono"
    style={{
      fontSize: 10,
      fontWeight: 500,
      letterSpacing: '0.1em',
      textTransform: 'uppercase',
      color: 'var(--ink-muted)',
      ...style,
    }}
  >
    {children}
  </div>
);

// Formal user avatar — square with initials
const Avatar = ({ name = '?', tone = 'ink', size = 22, style }) => {
  const initials = name.split(' ').map(n => n[0]).slice(0, 2).join('').toUpperCase();
  const bg = tone === 'gold' ? 'var(--gold)' : tone === 'ink' ? 'var(--ink)' : 'var(--ink-3)';
  return (
    <div
      className="mono"
      style={{
        width: size,
        height: size,
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: bg,
        color: 'var(--bg-panel)',
        fontSize: size * 0.42,
        fontWeight: 600,
        letterSpacing: '0.02em',
        borderRadius: 2,
        ...style,
      }}
      title={name}
    >
      {initials}
    </div>
  );
};

// Number stepper — for panel inputs
const NumInput = ({ value, onChange, unit, width = 64, step = 1, min, max, style }) => {
  const [local, setLocal] = React.useState(value);
  React.useEffect(() => setLocal(value), [value]);
  return (
    <div
      className="mono"
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        height: 22,
        width,
        border: '1px solid var(--line-2)',
        background: 'var(--bg-elevated)',
        borderRadius: 2,
        overflow: 'hidden',
        ...style,
      }}
    >
      <input
        type="text"
        value={local}
        onChange={(e) => setLocal(e.target.value)}
        onBlur={() => {
          const n = parseFloat(local);
          if (!isNaN(n)) { onChange && onChange(n); }
          else setLocal(value);
        }}
        style={{
          width: '100%',
          height: '100%',
          padding: '0 6px',
          background: 'transparent',
          border: 'none',
          outline: 'none',
          fontFamily: 'inherit',
          fontSize: 11.5,
          color: 'var(--ink)',
        }}
      />
      {unit && (
        <span style={{ fontSize: 10, color: 'var(--ink-subtle)', padding: '0 5px', borderLeft: '1px solid var(--line)' }}>{unit}</span>
      )}
    </div>
  );
};

// Formal group with sidebar label
const Field = ({ label, children, style }) => (
  <div style={{ display: 'grid', gridTemplateColumns: '52px 1fr', alignItems: 'center', gap: 8, ...style }}>
    <Label>{label}</Label>
    <div style={{ display: 'flex', gap: 4, alignItems: 'center', flexWrap: 'wrap' }}>{children}</div>
  </div>
);

// Colored swatch tile
const Swatch = ({ color, label, size = 20, active, onClick, style }) => (
  <button
    onClick={onClick}
    title={label}
    style={{
      width: size,
      height: size,
      background: color,
      border: active ? '1.5px solid var(--ink)' : '1px solid var(--line-2)',
      borderRadius: 2,
      cursor: 'pointer',
      padding: 0,
      outlineOffset: 1,
      ...style,
    }}
  />
);

// Section header inside panels
const PanelSection = ({ title, right, children, defaultOpen = true, style }) => {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div style={{ borderBottom: '1px solid var(--line)', ...style }}>
      <div
        onClick={() => setOpen(!open)}
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '8px 12px',
          cursor: 'pointer',
          userSelect: 'none',
        }}
      >
        <Row gap={6}>
          <span style={{ color: 'var(--ink-muted)', transform: open ? 'rotate(90deg)' : 'rotate(0)', transition: 'transform 120ms', display: 'inline-flex' }}>
            <I.chevronRight size={10}/>
          </span>
          <Label style={{ color: 'var(--ink)' }}>{title}</Label>
        </Row>
        <div onClick={(e) => e.stopPropagation()}>{right}</div>
      </div>
      {open && <div style={{ padding: '4px 12px 12px' }}>{children}</div>}
    </div>
  );
};

Object.assign(window, {
  Btn, IconBtn, Kbd, Badge, Divider, Row, Col, Label, Avatar, NumInput, Field, Swatch, PanelSection
});
