import { useEffect, useState } from "preact/hooks";

type ToastType = "success" | "error" | "info" | "warning";

interface ToastMessage {
  text: string;
  title?: string;
  type: ToastType;
}

const ICONS: Record<ToastType, string> = { success: "✓", error: "✕", info: "ℹ", warning: "⚠" };
const BORDERS: Record<ToastType, string> = {
  success: "rgba(34,197,94,0.4)",
  error: "rgba(239,68,68,0.4)",
  info: "rgba(59,130,246,0.4)",
  warning: "rgba(234,179,8,0.4)",
};
const ICON_COLORS: Record<ToastType, string> = {
  success: "#4ade80",
  error: "#f87171",
  info: "#60a5fa",
  warning: "#facc15",
};

let _showToast: (msg: string, type?: ToastType, title?: string) => void = () => {};

/** Global imperative toast. */
export function showToast(msg: string, type: ToastType = "success", title?: string) {
  _showToast(msg, type, title);
}

/** Mount once at app root. */
export function ToastContainer() {
  const [toast, setToast] = useState<ToastMessage | null>(null);
  const [visible, setVisible] = useState(false);

  _showToast = (text, type = "success", title) => {
    setToast({ text, type, title });
    setVisible(true);
    setTimeout(() => setVisible(false), 2800);
  };

  if (!toast) return null;

  return (
    <div
      class="fixed bottom-6 left-1/2 z-50 pointer-events-none transition-all duration-300"
      style={{
        transform: `translateX(-50%) translateY(${visible ? "0" : "20px"})`,
        opacity: visible ? 1 : 0,
      }}
    >
      <div
        class="flex items-start gap-2.5 px-4 py-3 rounded-[var(--z-radius-card)] shadow-lg max-w-sm"
        style={{ background: "var(--z-surface)", border: `1px solid ${BORDERS[toast.type]}` }}
      >
        <span class="text-sm mt-0.5" style={{ color: ICON_COLORS[toast.type] }}>{ICONS[toast.type]}</span>
        <div>
          {toast.title && <p class="text-xs font-semibold mb-0.5">{toast.title}</p>}
          <p class="text-[var(--z-font-md)]" style={{ color: "var(--z-muted)" }}>{toast.text}</p>
        </div>
      </div>
    </div>
  );
}
