import React from 'react';
import { Icon } from '../core/Icon';
import { IconButton } from '../core/IconButton';

const CSS = `
.ct-toast {
  display: flex; align-items: flex-start; gap: 10px;
  background: var(--surface-card);
  border: 1px solid var(--border-hairline);
  border-radius: var(--radius-2);
  box-shadow: var(--shadow-2);
  padding: 12px 14px;
  max-width: 420px;
  font: var(--text-body);
  color: var(--ink-1);
  animation: ct-toast-in var(--duration-slow) var(--ease-out);
}
.ct-toast__icon { display: flex; margin-top: 1px; }
.ct-toast--ok .ct-toast__icon { color: var(--ok); }
.ct-toast--warn .ct-toast__icon { color: var(--warn); }
.ct-toast--danger .ct-toast__icon { color: var(--danger); }
.ct-toast--info .ct-toast__icon { color: var(--info); }
.ct-toast__content { flex: 1; min-width: 0; }
.ct-toast__title { font: var(--text-body-strong); margin: 0 0 2px; }
@keyframes ct-toast-in { from { opacity: 0; transform: translateY(6px); } }
@media (prefers-reduced-motion: reduce) { .ct-toast { animation: none; } }
`;
(function inject() {
  if (typeof document !== 'undefined' && !document.getElementById('ct-toast-css')) {
    const s = document.createElement('style'); s.id = 'ct-toast-css'; s.textContent = CSS;
    document.head.appendChild(s);
  }
})();

const TOAST_ICONS = {
  ok: 'circle-check',
  warn: 'triangle-alert',
  danger: 'circle-alert',
  info: 'info',
};

export function Toast({ tone = 'info', title, onDismiss, children, style, ...rest }) {
  return (
    <div className={`ct-toast ct-toast--${tone}`} role="status" style={style} {...rest}>
      <span className="ct-toast__icon"><Icon name={TOAST_ICONS[tone]} size={16} /></span>
      <div className="ct-toast__content">
        {title ? <p className="ct-toast__title">{title}</p> : null}
        {children}
      </div>
      {onDismiss ? <IconButton icon="x" label="Dismiss" size="sm" onClick={onDismiss} /> : null}
    </div>
  );
}
