// ui.jsx — shared low-level pieces for the FFkit UI (Button, Icon, etc.)
// All visuals pull from colors_and_type.css custom properties.

const uiStyles = {
  btn: {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    font: 'var(--type-h4)', fontWeight: 500,
    height: 36, padding: '0 14px',
    borderRadius: 8, border: '1px solid transparent',
    cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap',
    transition: 'background 140ms cubic-bezier(0.22,0.61,0.36,1), border-color 140ms, color 140ms, box-shadow 140ms',
  },
  segWrap: {
    display: 'inline-flex', padding: 3, gap: 2,
    background: 'var(--bg-sunken)', border: '1px solid var(--border)',
    borderRadius: 10,
  },
  segBtn: {
    appearance: 'none', border: 0, background: 'transparent',
    font: 'var(--type-body)', fontWeight: 500,
    padding: '7px 16px', borderRadius: 7,
    color: 'var(--fg-muted)', cursor: 'pointer',
    transition: 'background 120ms, color 120ms, box-shadow 120ms',
  },
  field: {
    width: '100%', boxSizing: 'border-box',
    height: 36, padding: '0 12px',
    border: '1px solid var(--border)', borderRadius: 8,
    background: 'var(--bg-elevated)', color: 'var(--fg)',
    font: 'var(--type-body)',
    outline: 'none',
    transition: 'border-color 120ms, box-shadow 120ms',
  },
  kbd: {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    minWidth: 18, height: 18, padding: '0 5px',
    background: 'var(--bg-sunken)', border: '1px solid var(--border)',
    borderRadius: 4, font: '500 11px/1 var(--font-mono)', color: 'var(--fg-muted)',
    boxShadow: 'inset 0 -1px 0 var(--border-subtle)',
  },
  badge: {
    display: 'inline-flex', alignItems: 'center', gap: 5,
    padding: '3px 8px', borderRadius: 5,
    font: '500 11px/1 var(--font-sans)',
    color: 'var(--fg-muted)',
    border: '1px solid var(--border)', background: 'var(--bg-elevated)',
  },
};

function Icon({ name, size = 18, style = {} }) {
  return (
    <img
      src={`./assets/icons/${name}.svg`}
      alt=""
      width={size}
      height={size}
      style={{
        display: 'inline-block',
        opacity: 0.85,
        ...style,
      }}
    />
  );
}

function Button({ variant = 'secondary', size = 'md', children, icon, onClick, disabled, style = {} }) {
  const [hover, setHover] = React.useState(false);
  const [press, setPress] = React.useState(false);
  const v = {
    primary: {
      background: press ? 'var(--accent-press)' : hover ? 'var(--accent-hover)' : 'var(--accent)',
      color: 'var(--accent-fg)',
    },
    secondary: {
      background: hover ? 'var(--bg-sunken)' : 'var(--bg-elevated)',
      borderColor: hover ? 'var(--fg)' : 'var(--fg-muted)',
      color: hover ? 'var(--fg)' : 'var(--fg-muted)',
    },
    ghost: {
      background: hover ? 'var(--bg-hover)' : 'transparent',
      color: hover ? 'var(--fg)' : 'var(--fg-muted)',
    },
  }[variant];
  const sz = {
    sm: { height: 28, padding: '0 10px', fontSize: 12, borderRadius: 6 },
    md: {},
    lg: { height: 44, padding: '0 22px', fontSize: 15, borderRadius: 10 },
  }[size];
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setPress(false); }}
      onMouseDown={() => setPress(true)}
      onMouseUp={() => setPress(false)}
      style={{
        ...uiStyles.btn, ...v, ...sz,
        opacity: disabled ? 0.4 : 1,
        cursor: disabled ? 'not-allowed' : 'pointer',
        ...style,
      }}
    >
      {icon && <Icon name={icon} size={size === 'sm' ? 14 : 16} style={variant === 'primary' ? { filter: 'invert(1) brightness(2)', opacity: 1 } : {}} />}
      {children}
    </button>
  );
}

function Segmented({ value, onChange, options }) {
  return (
    <div style={uiStyles.segWrap} role="radiogroup">
      {options.map((o) => {
        const on = value === o.value;
        return (
          <button
            key={o.value}
            role="radio"
            aria-checked={on}
            onClick={() => onChange(o.value)}
            style={{
              ...uiStyles.segBtn,
              background: on ? 'var(--bg-elevated)' : 'transparent',
              color: on ? 'var(--fg)' : 'var(--fg-muted)',
              boxShadow: on ? 'var(--shadow-sm)' : 'none',
            }}
          >
            {o.label}
            {o.sub && <span style={{ fontWeight: 400, color: 'var(--fg-subtle)', marginLeft: 6, fontSize: 12 }}>{o.sub}</span>}
          </button>
        );
      })}
    </div>
  );
}

function Field({ value, onChange, placeholder, style = {}, mono = false, ...rest }) {
  const [focus, setFocus] = React.useState(false);
  return (
    <input
      type="text"
      value={value ?? ''}
      onChange={(e) => onChange?.(e.target.value)}
      onFocus={() => setFocus(true)}
      onBlur={() => setFocus(false)}
      placeholder={placeholder}
      style={{
        ...uiStyles.field,
        font: mono ? 'var(--type-code)' : 'var(--type-body)',
        borderColor: focus ? 'var(--accent)' : 'var(--border)',
        boxShadow: focus ? 'var(--ring-focus)' : 'none',
        ...style,
      }}
      {...rest}
    />
  );
}

function Kbd({ children }) {
  return <span style={uiStyles.kbd}>{children}</span>;
}

function Badge({ tone = 'neutral', dot = false, children }) {
  const tones = {
    neutral: {},
    accent:  { color: 'var(--accent-press)', background: 'var(--accent-50)', borderColor: 'rgba(95,141,66,0.2)' },
    success: { color: 'var(--accent-press)', background: '#f1f6ec', borderColor: 'rgba(95,141,66,0.2)' },
    warning: { color: '#8a651a', background: '#fbf3e0', borderColor: 'rgba(176,133,39,0.25)' },
    danger:  { color: '#7a2a23', background: '#fbe9e7', borderColor: 'rgba(184,68,58,0.22)' },
    info:    { color: '#2a4d66', background: '#e8f0f6', borderColor: 'rgba(63,108,140,0.22)' },
  }[tone];
  return (
    <span style={{ ...uiStyles.badge, ...tones }}>
      {dot && <span style={{ width: 6, height: 6, borderRadius: 999, background: 'currentColor' }} />}
      {children}
    </span>
  );
}

function SectionLabel({ children, right }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      font: 'var(--type-eyebrow)', letterSpacing: '0.12em', textTransform: 'uppercase',
      color: 'var(--fg-subtle)', marginBottom: 10,
    }}>
      <span>{children}</span>
      {right && <span>{right}</span>}
    </div>
  );
}

// Viewport hook — used by section components to switch grid layouts at
// tablet (<960) and mobile (<640) breakpoints. SSR-safe via the initial guess.
function useViewport() {
  const get = () => (typeof window !== 'undefined' ? window.innerWidth : 1280);
  const [w, setW] = React.useState(get);
  React.useEffect(() => {
    const on = () => setW(get());
    window.addEventListener('resize', on);
    window.addEventListener('orientationchange', on);
    return () => {
      window.removeEventListener('resize', on);
      window.removeEventListener('orientationchange', on);
    };
  }, []);
  return {
    w,
    isMobile: w < 640,
    isTablet: w >= 640 && w < 960,
    isDesktop: w >= 960,
    isNarrow: w < 720,
  };
}

Object.assign(window, { Icon, Button, Segmented, Field, Kbd, Badge, SectionLabel, useViewport });
