/* Shared atoms: Button, Badge, HashChip, Card */

const Button = ({ variant = "secondary", size, icon, iconRight, children, onClick, disabled, type, className = "", ...rest }) => {
  const cls = [
    "btn",
    `btn--${variant}`,
    size === "sm" ? "btn--sm" : "",
    size === "lg" ? "btn--lg" : "",
    className,
  ].filter(Boolean).join(" ");
  return (
    <button className={cls} onClick={onClick} disabled={disabled} type={type || "button"} {...rest}>
      {icon && <span className="btn__icon">{icon}</span>}
      {children}
      {iconRight && <span className="btn__icon">{iconRight}</span>}
    </button>
  );
};

const Verdict = ({ kind, size, label }) => {
  const v = window.VERDICT[kind] || window.VERDICT.verified;
  const IconNode = window.Icon[v.iconName]({ size: 12 });
  return (
    <span className={`badge badge--${kind === "contradicted" ? "contra" : kind} ${size === "lg" ? "badge--lg" : ""}`}>
      {IconNode}
      <span>{label || v.label}</span>
    </span>
  );
};

const Badge = ({ tone = "neutral", icon, children, size }) => (
  <span className={`badge badge--${tone} ${size === "lg" ? "badge--lg" : ""}`}>
    {icon}{children}
  </span>
);

const HashChip = ({ value, short, copyable = true, onCopy }) => {
  const [copied, setCopied] = React.useState(false);
  const display = short || value;
  const handleCopy = (e) => {
    e.stopPropagation();
    try { navigator.clipboard?.writeText(value || display); } catch (_) {}
    setCopied(true);
    onCopy && onCopy(value || display);
    setTimeout(() => setCopied(false), 1500);
  };
  return (
    <span className="hash-chip" title={value}>
      <span>{display}</span>
      {copyable && (
        <button onClick={handleCopy} aria-label="Copy hash">
          {copied ? window.Icon.checkSimple({ size: 12 }) : window.Icon.copy({ size: 12 })}
        </button>
      )}
    </span>
  );
};

const Card = ({ title, meta, action, children, padded = true, className = "" }) => (
  <div className={`card ${className}`}>
    {(title || action) && (
      <div className="card__header">
        {title && <h3>{title}</h3>}
        {meta && <span className="meta">{meta}</span>}
        <div className="spacer" />
        {action}
      </div>
    )}
    <div className={padded ? "card__body" : ""}>{children}</div>
  </div>
);

const Field = ({ label, hint, error, required, children }) => (
  <div className="field">
    {label && (
      <label className="field__label">
        {label} {required && <span className="field__req">*</span>}
      </label>
    )}
    {children}
    {error ? <span className="field__error">{error}</span> :
     hint ? <span className="field__hint">{hint}</span> : null}
  </div>
);

const RadioCard = ({ selected, title, sub, onClick, icon }) => (
  <button className={`radio-card ${selected ? "radio-card--selected" : ""}`} onClick={onClick}>
    {icon && <div style={{ color: "var(--ink-3)", marginBottom: 4 }}>{icon}</div>}
    <div className="radio-card__title">{title}</div>
    {sub && <div className="radio-card__sub">{sub}</div>}
  </button>
);

const SkeletonLine = ({ w = "100%", h = 12 }) => (
  <div className="skeleton" style={{ width: w, height: h }} />
);

const ProgressBar = ({ value, max = 100, accent }) => (
  <div className="progress">
    <div className={`progress__bar ${accent ? "progress__bar--accent" : ""}`} style={{ width: `${(value / max) * 100}%` }} />
  </div>
);

const Tabs = ({ items, value, onChange }) => (
  <div className="tabs">
    {items.map((it) => (
      <button
        key={it.value}
        className={`tab ${value === it.value ? "tab--active" : ""}`}
        onClick={() => onChange(it.value)}
      >
        {it.label}
      </button>
    ))}
  </div>
);

const Modal = ({ open, onClose, title, sub, children, footer, wide }) => {
  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className={`modal ${wide ? "modal--wide" : ""}`} onClick={(e) => e.stopPropagation()}>
        {(title || sub) && (
          <div className="modal__header">
            {title && <h2>{title}</h2>}
            {sub && <div className="modal__sub">{sub}</div>}
          </div>
        )}
        <div className="modal__body">{children}</div>
        {footer && <div className="modal__footer">{footer}</div>}
      </div>
    </div>
  );
};

const Drawer = ({ open, onClose, title, sub, children, wide }) => {
  if (!open) return null;
  return (
    <>
      <div className="drawer-backdrop" onClick={onClose} />
      <div className={`drawer ${wide ? "drawer--wide" : ""}`}>
        <div className="drawer__header">
          <div style={{ flex: 1 }}>
            <h2>{title}</h2>
            {sub && <div className="text-xs muted" style={{ marginTop: 2 }}>{sub}</div>}
          </div>
          <button className="btn btn--ghost btn--sm" onClick={onClose} aria-label="Close drawer">
            {window.Icon.x({ size: 16 })}
          </button>
        </div>
        <div className="drawer__body">{children}</div>
      </div>
    </>
  );
};

// Tiny inline sparkline (SVG path through values)
const Sparkline = ({ values, color = "var(--ink-1)", w = 90, h = 28 }) => {
  if (!values || !values.length) return null;
  const max = Math.max(...values);
  const min = Math.min(...values);
  const range = max - min || 1;
  const stepX = w / (values.length - 1);
  const pts = values.map((v, i) => `${(i * stepX).toFixed(1)},${(h - 4 - ((v - min) / range) * (h - 8)).toFixed(1)}`).join(" ");
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{ display: "block" }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
};

const Toast = ({ kind = "info", title, sub, onClose }) => {
  const map = { success: "check", warn: "alertTriangle", error: "xCircle", info: "shield" };
  return (
    <div className={`toast toast--${kind}`}>
      <span className="toast__icon">{window.Icon[map[kind]]({ size: 16 })}</span>
      <div className="toast__body">
        <div className="toast__title">{title}</div>
        {sub && <div className="toast__sub">{sub}</div>}
      </div>
      {onClose && <button className="toast__close" onClick={onClose}>{window.Icon.x({ size: 14 })}</button>}
    </div>
  );
};

const ToastStack = ({ toasts, dismiss }) => (
  <div className="toast-stack">
    {toasts.map((t) => (
      <Toast key={t.id} {...t} onClose={() => dismiss(t.id)} />
    ))}
  </div>
);

Object.assign(window, {
  Button, Verdict, Badge, HashChip, Card, Field, RadioCard,
  SkeletonLine, ProgressBar, Tabs, Modal, Drawer, Sparkline,
  Toast, ToastStack,
});
