"use client";

import { useEffect, useState } from "react";
import { NOTIFICATION_ROUTE_EVENT } from "../platform/adapter";

export const FLASH_TOAST_EVENT = "slackwsh:flash-toast";

export interface FlashToastDetail {
  title: string;
  body: string;
  route?: string;
  tag?: string;
}

interface FlashToast extends FlashToastDetail {
  id: string;
  leaving?: boolean;
}

const SHOW_MS = 2800;
const LEAVE_MS = 280;
const MAX_VISIBLE = 5;

/**
 * Right-side in-app flash notifications. Stacks oldest at the top, newest at
 * the bottom; each toast auto-dismisses after a few seconds. Driven by
 * `FLASH_TOAST_EVENT` from RealtimeProvider when the user has in-app flash on.
 */
export function FlashToastHost() {
  const [toasts, setToasts] = useState<FlashToast[]>([]);

  useEffect(() => {
    function onFlash(event: Event) {
      const detail = (event as CustomEvent<FlashToastDetail>).detail;
      if (!detail?.title) return;
      const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
      setToasts((prev) => {
        const withoutDup =
          detail.tag != null ? prev.filter((toast) => toast.tag !== detail.tag) : prev;
        const next = [...withoutDup, { ...detail, id }];
        return next.slice(-MAX_VISIBLE);
      });
      window.setTimeout(() => {
        setToasts((prev) => prev.map((toast) => (toast.id === id ? { ...toast, leaving: true } : toast)));
        window.setTimeout(() => {
          setToasts((prev) => prev.filter((toast) => toast.id !== id));
        }, LEAVE_MS);
      }, SHOW_MS);
    }
    window.addEventListener(FLASH_TOAST_EVENT, onFlash);
    return () => window.removeEventListener(FLASH_TOAST_EVENT, onFlash);
  }, []);

  if (toasts.length === 0) return null;

  return (
    <div className="flash-toast-stack" aria-live="polite" aria-relevant="additions">
      {toasts.map((toast) => (
        <button
          key={toast.id}
          type="button"
          className={toast.leaving ? "flash-toast leaving" : "flash-toast"}
          onClick={() => {
            if (toast.route) {
              window.dispatchEvent(new CustomEvent(NOTIFICATION_ROUTE_EVENT, { detail: { route: toast.route } }));
            }
            setToasts((prev) => prev.filter((row) => row.id !== toast.id));
          }}
        >
          <strong>{toast.title}</strong>
          <span>{toast.body}</span>
        </button>
      ))}
    </div>
  );
}

export function pushFlashToast(detail: FlashToastDetail) {
  if (typeof window === "undefined") return;
  window.dispatchEvent(new CustomEvent(FLASH_TOAST_EVENT, { detail }));
}
