/* global React, Icon */
(function () {
const { useState, useRef, useEffect } = React;

// ============================================================
// Button
// ============================================================
function Button({ variant = 'secondary', size = 'md', icon: IconC, iconRight: IconR, children, kbd, block, type = 'button', onClick, className = '', isIcon = false, title, disabled = false }) {
  const cls = ['btn'];
  if (variant === 'primary')   cls.push('is-primary');
  if (variant === 'secondary') cls.push('is-secondary');
  if (variant === 'ghost')     cls.push('is-ghost');
  if (variant === 'danger')    cls.push('is-danger');
  if (variant === 'outline')   { /* default */ }
  if (size === 'sm') cls.push('is-sm');
  if (size === 'lg') cls.push('is-lg');
  if (block) cls.push('is-block');
  if (isIcon) cls.push('is-icon');
  if (disabled) cls.push('is-disabled');
  if (className) cls.push(className);
  return (
    <button type={type} className={cls.join(' ')} onClick={onClick} title={title} disabled={disabled} aria-disabled={disabled || undefined}>
      {IconC && <IconC size={isIcon ? 16 : 14} />}
      {!isIcon && children}
      {IconR && <IconR size={14} />}
      {kbd && <span className="kbd">{kbd}</span>}
    </button>
  );
}

// ============================================================
// Badge
// ============================================================
function Badge({ tone = 'neutral', dot = false, children }) {
  const cls = ['badge'];
  if (tone === 'success') cls.push('is-success');
  if (tone === 'warning') cls.push('is-warning');
  if (tone === 'danger')  cls.push('is-danger');
  if (tone === 'neutral') cls.push('is-neutral');
  if (tone === 'accent')  cls.push('is-accent');
  return (
    <span className={cls.join(' ')}>
      {dot && <span className="dot"></span>}
      {children}
    </span>
  );
}

// ============================================================
// Avatar — initial-based, deterministic tone
// ============================================================
function Avatar({ name, size = 'sm', tone }) {
  const initials = (name || '?').slice(0, 1);
  const cls = ['avatar'];
  if (size === 'md') cls.push('is-md');
  if (size === 'lg') cls.push('is-lg');
  if (size === 'sm') cls.push('is-sm');
  cls.push(tone || 'tone-a');
  return <span className={cls.join(' ')}>{initials}</span>;
}

// ============================================================
// Kbd
// ============================================================
const Kbd = ({ children }) => <span className="kbd">{children}</span>;

// ============================================================
// Card
// ============================================================
function Card({ children, className = '', style }) {
  return <section className={`card ${className}`} style={style}>{children}</section>;
}
function CardHeader({ title, subtitle, actions, children }) {
  return (
    <header className="card__header">
      {title && <div className="card__title">{title}</div>}
      {subtitle && <div className="card__subtitle">{subtitle}</div>}
      {children}
      {actions && <div className="card__actions">{actions}</div>}
    </header>
  );
}
function CardBody({ children, flush, style }) {
  return <div className={`card__body${flush ? ' card__body--flush' : ''}`} style={style}>{children}</div>;
}
function CardFooter({ children }) {
  return <footer className="card__footer">{children}</footer>;
}

// ============================================================
// Tabs
// ============================================================
function Tabs({ items, active, onChange }) {
  return (
    <div className="tabs">
      {items.map(it => (
        <button
          key={it.id}
          className={`tabs__item ${active === it.id ? 'is-active' : ''}`}
          onClick={() => onChange(it.id)}
        >
          {it.label}
        </button>
      ))}
    </div>
  );
}

// ============================================================
// Drawer (right-side)
// ============================================================
function Drawer({ open, onClose, title, children, footer, width = 560 }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  return (
    <React.Fragment>
      <div className={`drawer-overlay ${open ? 'is-open' : ''}`} onClick={onClose}></div>
      <aside className={`drawer ${open ? 'is-open' : ''}`} style={{ width }}>
        <header className="drawer__header">
          <div style={{ flex: 1 }}>{title}</div>
          <button className="icon-btn" onClick={onClose} title="닫기"><Icon.X size={16}/></button>
        </header>
        <div className="drawer__body">{children}</div>
        {footer && <div className="drawer__footer">{footer}</div>}
      </aside>
    </React.Fragment>
  );
}

// ============================================================
// Sparkline — tiny SVG, for KPI cards
// ============================================================
function Sparkline({ values, width = 120, height = 32, stroke = 'currentColor' }) {
  if (!values || !values.length) return null;
  const max = Math.max(...values);
  const min = Math.min(...values);
  const range = (max - min) || 1;
  const step = width / (values.length - 1);
  const pts = values.map((v, i) => `${i * step},${height - ((v - min) / range) * height}`).join(' ');
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} fill="none">
      <polyline points={pts} fill="none" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

// ============================================================
// Empty state
// ============================================================
function Empty({ icon: IconC = Icon.Calendar, title, hint, action }) {
  return (
    <div style={{ padding: '32px 16px', textAlign: 'center', color: 'var(--text-tertiary)' }}>
      <div style={{ width: 40, height: 40, borderRadius: 99, background: 'var(--bg-subtle)', display: 'inline-grid', placeItems: 'center', color: 'var(--text-secondary)', marginBottom: 12 }}>
        <IconC size={20}/>
      </div>
      <div className="t-h3" style={{ color: 'var(--text-primary)', marginBottom: 4 }}>{title}</div>
      {hint && <div className="t-caption">{hint}</div>}
      {action && <div style={{ marginTop: 16 }}>{action}</div>}
    </div>
  );
}

// ============================================================
// Modal — centered dialog
// ============================================================
function Modal({ open, onClose, title, children, footer, width = 560, dense = false }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  return (
    <React.Fragment>
      <div className={`modal-overlay ${open ? 'is-open' : ''}`} onClick={onClose}>
        <div className="modal" style={{ width }} onClick={(e) => e.stopPropagation()}>
          <header className="modal__header">
            <div style={{ flex: 1, fontSize: 16, fontWeight: 600, letterSpacing: '-0.014em' }}>{title}</div>
            <button className="icon-btn" onClick={onClose} title="닫기"><Icon.X size={16}/></button>
          </header>
          <div className={`modal__body${dense ? ' modal__body--dense' : ''}`}>{children}</div>
          {footer && <div className="modal__footer">{footer}</div>}
        </div>
      </div>
    </React.Fragment>
  );
}

// ============================================================
// Toggle / Switch
// ============================================================
function Toggle({ checked, onChange, label, hint }) {
  return (
    <label className="toggle">
      <input type="checkbox" checked={!!checked} onChange={(e) => onChange && onChange(e.target.checked)}/>
      <span className="toggle__track"><span className="toggle__thumb"/></span>
      {(label || hint) && (
        <span className="toggle__text">
          {label && <span className="toggle__label">{label}</span>}
          {hint && <span className="toggle__hint">{hint}</span>}
        </span>
      )}
    </label>
  );
}

// ============================================================
// Checkbox
// ============================================================
function Check({ checked, onChange, label, hint }) {
  return (
    <label className="check">
      <input type="checkbox" checked={!!checked} onChange={(e) => onChange && onChange(e.target.checked)}/>
      <span className="check__box"><Icon.Check size={12}/></span>
      {(label || hint) && (
        <span className="check__text">
          {label && <span className="check__label">{label}</span>}
          {hint && <span className="check__hint">{hint}</span>}
        </span>
      )}
    </label>
  );
}

// ============================================================
// Radio group
// ============================================================
function Radio({ checked, onChange, label, hint, name }) {
  return (
    <label className="check">
      <input type="radio" name={name} checked={!!checked} onChange={() => onChange && onChange()}/>
      <span className="check__box check__box--radio"><span className="check__dot"/></span>
      {(label || hint) && (
        <span className="check__text">
          {label && <span className="check__label">{label}</span>}
          {hint && <span className="check__hint">{hint}</span>}
        </span>
      )}
    </label>
  );
}

// ============================================================
// Toast — global lightweight notifier; call window.toast(...)
// ============================================================
const { useRef: _useRef } = React;
function ToastHost() {
  const [items, setItems] = useState([]);
  useEffect(() => {
    window.toast = (msg, opts = {}) => {
      const id = 't' + Date.now() + Math.random().toString(16).slice(2, 6);
      const tone = opts.tone || 'default';
      const duration = opts.duration || 3500;
      setItems(s => [...s, { id, msg, tone, leaving: false }]);
      setTimeout(() => setItems(s => s.map(t => t.id === id ? { ...t, leaving: true } : t)), duration - 200);
      setTimeout(() => setItems(s => s.filter(t => t.id !== id)), duration);
      return id;
    };
    return () => { window.toast = null; };
  }, []);
  return (
    <div className="toast-container" aria-live="polite">
      {items.map(t => (
        <div key={t.id}
             className={`toast ${t.tone === 'success' ? 'is-success' : t.tone === 'warning' ? 'is-warning' : t.tone === 'danger' ? 'is-danger' : ''} ${t.leaving ? 'is-leaving' : ''}`}>
          {t.msg}
        </div>
      ))}
    </div>
  );
}

window.UI = { Button, Badge, Avatar, Kbd, Card, CardHeader, CardBody, CardFooter, Tabs, Drawer, Modal, Sparkline, Empty, Toggle, Check, Radio, ToastHost };
})();
