/* global React */
const { useState, useEffect, useRef, createContext, useContext } = React;

// ----------------------------------------------------------------------------
// Button
// ----------------------------------------------------------------------------
function Button({
  variant = 'secondary', size = 'md', icon, iconRight,
  children, loading, disabled, destructive, full, style, ...rest
}) {
  const [hover, setHover] = useState(false);
  const sizes = {
    sm: { padding: '0 10px', fontSize: 12.5, height: 26 },
    md: { padding: '0 12px', fontSize: 13,   height: 32 },
    lg: { padding: '0 16px', fontSize: 14,   height: 38 },
  };
  const v = destructive ? 'destructive' : variant;
  const variants = {
    primary:    { bg: 'var(--s-brand)',     fg: '#fff',                bd: 'var(--s-brand)',          hov: 'var(--s-brand-hover)' },
    secondary:  { bg: 'var(--s-bg-2)',      fg: 'var(--s-fg-1)',       bd: 'var(--s-border-strong)',  hov: 'var(--s-bg-3)' },
    ghost:      { bg: 'transparent',         fg: 'var(--s-fg-2)',       bd: 'transparent',             hov: 'var(--s-bg-2)' },
    destructive:{ bg: 'transparent',         fg: 'var(--s-danger)',     bd: 'var(--s-border-strong)',  hov: 'var(--s-danger-weak)' },
    danger:     { bg: 'var(--s-danger)',     fg: '#fff',                bd: 'var(--s-danger)',         hov: '#FF8390' },
  };
  const c = variants[v];
  return (
    <button
      disabled={disabled || loading}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        ...sizes[size],
        background: hover && !disabled ? c.hov : c.bg,
        color: c.fg,
        border: `1px solid ${c.bd}`,
        borderRadius: 'var(--s-r-md)',
        cursor: disabled || loading ? 'not-allowed' : 'pointer',
        fontWeight: 500,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        transition: 'background var(--s-dur-fast) var(--s-ease)',
        opacity: disabled ? 0.5 : 1,
        width: full ? '100%' : undefined,
        whiteSpace: 'nowrap',
        ...style,
      }}
      {...rest}>
      {loading ? <span className="spin-inline"/> : icon}
      {children}
      {iconRight}
    </button>
  );
}

// ----------------------------------------------------------------------------
// Badge
// ----------------------------------------------------------------------------
function Badge({ tone = 'neutral', children, dot, style }) {
  const tones = {
    neutral: { bg: 'var(--s-bg-3)',         fg: 'var(--s-fg-2)' },
    brand:   { bg: 'var(--s-brand-weak)',   fg: 'var(--s-link)' },
    success: { bg: 'var(--s-success-weak)', fg: 'var(--s-success)' },
    warning: { bg: 'var(--s-warning-weak)', fg: 'var(--s-warning)' },
    danger:  { bg: 'var(--s-danger-weak)',  fg: 'var(--s-danger)' },
    info:    { bg: 'var(--s-info-weak)',    fg: 'var(--s-info)' },
    accent:  { bg: 'var(--s-accent-weak)',  fg: 'var(--s-accent)' },
  };
  const t = tones[tone];
  return (
    <span style={{
      background: t.bg, color: t.fg,
      padding: '2px 8px', borderRadius: 'var(--s-r-pill)',
      fontSize: 11.5, fontWeight: 500,
      display: 'inline-flex', alignItems: 'center', gap: 5,
      whiteSpace: 'nowrap',
      ...style,
    }}>
      {dot && <span style={{
        width: 6, height: 6, borderRadius: '50%', background: t.fg,
      }}/>}
      {children}
    </span>
  );
}

// ----------------------------------------------------------------------------
// Input / Select
// ----------------------------------------------------------------------------
function Input({ label, hint, error, icon, style, ...rest }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {label && <span style={{ color: 'var(--s-fg-2)', fontSize: 12, fontWeight: 500 }}>{label}</span>}
      <div style={{ position: 'relative' }}>
        {icon && (
          <span style={{
            position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)',
            color: 'var(--s-fg-3)', display: 'flex',
          }}>{icon}</span>
        )}
        <input
          {...rest}
          className="input-base"
          style={{
            paddingLeft: icon ? 32 : undefined,
            borderColor: error ? 'var(--s-danger)' : undefined,
            ...style,
          }}/>
      </div>
      {hint && <span style={{ color: error ? 'var(--s-danger)' : 'var(--s-fg-3)', fontSize: 12 }}>{hint}</span>}
    </label>
  );
}

function Select({ label, options = [], value, onChange, style, ...rest }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {label && <span style={{ color: 'var(--s-fg-2)', fontSize: 12, fontWeight: 500 }}>{label}</span>}
      <div style={{ position: 'relative' }}>
        <select value={value} onChange={onChange} {...rest} className="input-base"
          style={{ appearance: 'none', paddingRight: 30, cursor: 'pointer', ...style }}>
          {options.map(o => {
            const val = o.value !== undefined ? o.value : o;
            const lbl = o.label !== undefined ? o.label : o;
            return <option key={val} value={val}>{lbl}</option>;
          })}
        </select>
        <span style={{
          position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)',
          color: 'var(--s-fg-3)', pointerEvents: 'none', display: 'flex',
        }}>
          <Icon d={I.chevDown} size={14}/>
        </span>
      </div>
    </label>
  );
}

// ----------------------------------------------------------------------------
// Toggle Switch
// ----------------------------------------------------------------------------
function Toggle({ checked, onChange }) {
  return (
    <button
      role="switch"
      aria-checked={checked}
      onClick={() => onChange(!checked)}
      style={{
        width: 36, height: 20, borderRadius: 999,
        background: checked ? 'var(--s-brand)' : 'var(--s-bg-4)',
        border: 0, padding: 0, cursor: 'pointer',
        position: 'relative',
        transition: 'background var(--s-dur-ui) var(--s-ease)',
        flexShrink: 0,
      }}>
      <span style={{
        position: 'absolute', top: 2, left: checked ? 18 : 2,
        width: 16, height: 16, borderRadius: '50%',
        background: '#fff',
        transition: 'left var(--s-dur-ui) var(--s-ease)',
      }}/>
    </button>
  );
}

// ----------------------------------------------------------------------------
// Tabs
// ----------------------------------------------------------------------------
function Tabs({ value, onChange, options }) {
  return (
    <div style={{
      display: 'flex', gap: 0,
      borderBottom: '1px solid var(--s-border)',
    }}>
      {options.map(o => {
        const active = o.value === value;
        return (
          <button key={o.value}
            onClick={() => onChange(o.value)}
            style={{
              background: 'transparent', border: 0, cursor: 'pointer',
              padding: '10px 14px', fontSize: 13,
              color: active ? 'var(--s-fg-1)' : 'var(--s-fg-2)',
              borderBottom: `2px solid ${active ? 'var(--s-brand)' : 'transparent'}`,
              marginBottom: -1, fontWeight: active ? 600 : 500,
              display: 'inline-flex', alignItems: 'center', gap: 6,
              transition: 'color var(--s-dur-fast) var(--s-ease)',
            }}>
            {o.icon}
            {o.label}
            {o.count != null && (
              <span style={{
                fontSize: 11, color: 'var(--s-fg-3)',
                background: 'var(--s-bg-3)', padding: '1px 6px', borderRadius: 999,
              }}>{o.count}</span>
            )}
          </button>
        );
      })}
    </div>
  );
}

// ----------------------------------------------------------------------------
// Section header (for screens)
// ----------------------------------------------------------------------------
function SectionHead({ title, hint, right, style }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
      gap: 16, marginBottom: 14, ...style,
    }}>
      <div>
        <h3 style={{ fontSize: 14, fontWeight: 600, color: 'var(--s-fg-1)', marginBottom: 2 }}>{title}</h3>
        {hint && <div style={{ fontSize: 12.5, color: 'var(--s-fg-3)' }}>{hint}</div>}
      </div>
      {right}
    </div>
  );
}

// ----------------------------------------------------------------------------
// Toast (singleton)
// ----------------------------------------------------------------------------
const ToastCtx = createContext(null);
function ToastProvider({ children }) {
  const [toast, setToast] = useState(null);
  const show = (msg, tone = 'success') => {
    setToast({ msg, tone, id: Math.random() });
    setTimeout(() => setToast(null), 2800);
  };
  return (
    <ToastCtx.Provider value={show}>
      {children}
      {toast && (
        <div className={`toast ${toast.tone}`}>
          <Icon d={toast.tone === 'success' ? I.check : I.alert} size={14}/>
          {toast.msg}
        </div>
      )}
    </ToastCtx.Provider>
  );
}
const useToast = () => useContext(ToastCtx);

// ----------------------------------------------------------------------------
// Modal
// ----------------------------------------------------------------------------
function Modal({ open, onClose, title, children, width = 720 }) {
  useEffect(() => {
    if (!open) return;
    const onKey = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-panel" style={{ width, maxWidth: '92vw', maxHeight: '88vh', display: 'flex', flexDirection: 'column' }}
        onClick={e => e.stopPropagation()}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '14px 18px', borderBottom: '1px solid var(--s-border)',
        }}>
          <h3 style={{ fontSize: 14, fontWeight: 600 }}>{title}</h3>
          <button onClick={onClose} style={{
            background: 'transparent', border: 0, color: 'var(--s-fg-2)',
            cursor: 'pointer', padding: 4, display: 'flex', borderRadius: 4,
          }}><Icon d={I.x}/></button>
        </div>
        <div style={{ overflow: 'auto', flex: 1 }}>{children}</div>
      </div>
    </div>
  );
}

// ----------------------------------------------------------------------------
// KPI Card
// ----------------------------------------------------------------------------
function Kpi({ label, value, hint, tone = 'neutral', icon }) {
  const accent = tone === 'accent';
  return (
    <div className="card" style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span className="micro">{label}</span>
        {icon && <span style={{ color: 'var(--s-fg-3)', display: 'flex' }}>{icon}</span>}
      </div>
      <div style={{
        fontSize: 26, fontWeight: 600, fontFamily: 'var(--s-font-display)',
        color: accent ? 'var(--s-accent)' : 'var(--s-fg-1)',
        letterSpacing: '-0.01em', lineHeight: 1.1,
      }}>{value}</div>
      {hint && <div style={{ fontSize: 12, color: 'var(--s-fg-3)' }}>{hint}</div>}
    </div>
  );
}

window.Button = Button;
window.Badge = Badge;
window.Input = Input;
window.Select = Select;
window.Toggle = Toggle;
window.Tabs = Tabs;
window.SectionHead = SectionHead;
window.ToastProvider = ToastProvider;
window.useToast = useToast;
window.Modal = Modal;
window.Kpi = Kpi;
