/* ============ Shared UI components ============ */

const Pill = ({ tone = 'gray', children }) => (
  <span className={"pill " + tone}>{children}</span>
);

const Button = ({ variant = 'default', size, icon, children, ...rest }) => {
  const cls = ['btn'];
  if (variant === 'primary')  cls.push('primary');
  if (variant === 'tinted')   cls.push('tinted');
  if (variant === 'bordered') cls.push('bordered');
  if (variant === 'danger')   cls.push('danger');
  if (size === 'lg') cls.push('lg');
  return (
    <button className={cls.join(' ')} {...rest}>
      {icon && <Icon name={icon} size={14} />}
      {children}
    </button>
  );
};

const IconButton = ({ name, size = 16, ...rest }) => (
  <button className="icon-btn" {...rest}><Icon name={name} size={size} /></button>
);

const Segmented = ({ value, onChange, options }) => (
  <div className="seg">
    {options.map(o => (
      <button key={o.value} className={value === o.value ? 'active' : ''} onClick={() => onChange(o.value)}>
        {o.label}
      </button>
    ))}
  </div>
);

const Field = ({ label, children }) => (
  <div className="field">
    <label>{label}</label>
    {children}
  </div>
);

const Input = (props) => <input className="input" {...props} />;
const Select = ({ options, children, ...rest }) => (
  <select className="select" {...rest}>
    {options ? options.map(o => (typeof o === 'string' ? <option key={o} value={o}>{o}</option> : <option key={o.value} value={o.value}>{o.label}</option>)) : children}
  </select>
);
const Textarea = (props) => <textarea className="textarea" {...props} />;

const Checkbox = ({ checked, onChange, ...rest }) => (
  <input type="checkbox" className="checkbox" checked={!!checked} onChange={e => onChange(e.target.checked)} {...rest} />
);

/* Modal */
const Modal = ({ title, onClose, children, footer, width }) => {
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, [onClose]);
  return (
    <div className="modal-backdrop" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" style={width ? { width } : null}>
        <div className="modal-head">
          <div className="modal-title">{title}</div>
          <IconButton name="x" onClick={onClose} />
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
};

/* Stat card */
const Stat = ({ label, value, delta, deltaTone = 'up', iconName, iconColor = 'var(--blue)' }) => (
  <div className="stat">
    <div className="stat-label">
      {iconName && <span className="stat-icon" style={{ background: iconColor }}><Icon name={iconName} size={13} /></span>}
      {label}
    </div>
    <div className="stat-value">{value}</div>
    {delta && <div className="stat-delta"><span className={deltaTone}>{delta}</span></div>}
  </div>
);

/* Card */
const Card = ({ title, action, children, pad = true, sub }) => (
  <div className="card">
    {title && (
      <div className="card-header">
        <div>
          <div className="card-title">{title}</div>
          {sub && <div className="card-sub">{sub}</div>}
        </div>
        {action}
      </div>
    )}
    <div className={pad ? 'card-pad' : ''}>{children}</div>
  </div>
);

/* Empty */
const Empty = ({ icon = 'sparkle', title, hint, action }) => (
  <div className="empty">
    <div className="empty-icon"><Icon name={icon} size={26} /></div>
    <h3>{title}</h3>
    {hint && <p>{hint}</p>}
    {action}
  </div>
);

/* Toaster */
const ToastCtx = React.createContext(null);
const ToastProvider = ({ children }) => {
  const [items, setItems] = React.useState([]);
  const push = React.useCallback((msg) => {
    const id = uid();
    setItems(prev => [...prev, { id, msg }]);
    setTimeout(() => setItems(prev => prev.filter(t => t.id !== id)), 2200);
  }, []);
  return (
    <ToastCtx.Provider value={push}>
      {children}
      <div className="toast-wrap">
        {items.map(t => <div key={t.id} className="toast"><Icon name="check" size={14} />{t.msg}</div>)}
      </div>
    </ToastCtx.Provider>
  );
};
const useToast = () => React.useContext(ToastCtx);

Object.assign(window, { Pill, Button, IconButton, Segmented, Field, Input, Select, Textarea, Checkbox, Modal, Stat, Card, Empty, ToastProvider, useToast });
