/* Tarot Battle UI Kit — overlays, states & board token */

/* imperative toast: dispatch a window event from anywhere */
function tbToast(text, opts) {
  window.dispatchEvent(new CustomEvent("tb-toast", { detail: Object.assign({ text }, opts) }));
}
function ToastHost() {
  const [items, setItems] = React.useState([]);
  React.useEffect(() => {
    const on = (e) => {
      const id = Math.random().toString(36).slice(2);
      setItems((l) => [...l, Object.assign({ id }, e.detail)]);
      setTimeout(() => setItems((l) => l.filter((t) => t.id !== id)), e.detail.duration || 2600);
    };
    window.addEventListener("tb-toast", on);
    return () => window.removeEventListener("tb-toast", on);
  }, []);
  return (
    <div className="toast-wrap">
      {items.map((t) => (
        <div key={t.id} className={"toast" + (t.kind === "danger" ? " danger" : "")}>
          <Icon name={t.icon || (t.kind === "danger" ? "TriangleAlert" : "Check")} size={17}
                style={{ color: t.kind === "danger" ? "var(--blood-red)" : "var(--volt-green)" }} />
          <span className="tx">{t.title && <b>{t.title} — </b>}{t.text}</span>
        </div>
      ))}
    </div>
  );
}

function Modal({ open, title, children, onClose, actions }) {
  if (!open) return null;
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="x" onClick={onClose}><Icon name="X" size={20} /></button>
        {title && <h3>{title}</h3>}
        {children}
        {actions && <div className="actions">{actions}</div>}
      </div>
    </div>
  );
}

function Tooltip({ label, children }) {
  const [show, setShow] = React.useState(false);
  return (
    <span className="tipwrap" onMouseEnter={() => setShow(true)} onMouseLeave={() => setShow(false)}>
      {children}
      {show && <span className="tooltip">{label}</span>}
    </span>
  );
}

function EmptyState({ icon = "Sparkles", title, children }) {
  return (
    <div className="empty-state">
      <div className="es-emblem"><Icon name={icon} size={30} /></div>
      <h3>{title}</h3>
      <p>{children}</p>
    </div>
  );
}

/* A board token — portrait disc with side bar, MAD, and hp pips */
function Token({ unit, side, hp, maxHp, selected, onClick }) {
  return (
    <div className={"token " + side + (selected ? " sel" : "")}
         style={{ backgroundImage: `url('${unit.img}')` }} onClick={onClick}>
      <span className="side-bar" />
      <span className="tok-mad">{unit.a}</span>
      <span className="tok-hp">
        {Array.from({ length: maxHp }).map((_, i) => (
          <i key={i} className={i < hp ? "" : "empty"} />
        ))}
      </span>
    </div>
  );
}

Object.assign(window, { tbToast, ToastHost, Modal, Tooltip, EmptyState, Token });
