/**
 * Toast Notification Component
 * Real-time notification popups (bottom-right corner)
 */

"use client";

import { useState, useEffect } from "react";
import type { Lang } from "@/lib/config";

interface Toast {
  id: string;
  type: "success" | "error" | "info" | "warning";
  title: string;
  message: string;
}

interface ToastNotificationProps {
  lang: Lang;
}

export default function ToastNotification({ lang }: ToastNotificationProps) {
  const isAr = lang === "ar";
  const [toasts, setToasts] = useState<Toast[]>([]);

  // Listen for custom toast events (can be triggered from anywhere in the app)
  useEffect(() => {
    const handleToast = (event: CustomEvent) => {
      const { type, title, message } = event.detail;
      const id = Math.random().toString(36).substr(2, 9);

      setToasts((prev) => [...prev, { id, type, title, message }]);

      // Auto-remove after 5 seconds
      setTimeout(() => {
        setToasts((prev) => prev.filter((t) => t.id !== id));
      }, 5000);
    };

    window.addEventListener("showToast" as any, handleToast as EventListener);

    return () => {
      window.removeEventListener(
        "showToast" as any,
        handleToast as EventListener,
      );
    };
  }, []);

  const getToastStyles = (type: string) => {
    switch (type) {
      case "success":
        return "bg-emerald-50 border-emerald-200 text-emerald-900";
      case "error":
        return "bg-rose-50 border-rose-200 text-rose-900";
      case "warning":
        return "bg-amber-50 border-amber-200 text-amber-900";
      case "info":
      default:
        return "bg-sky-50 border-sky-200 text-sky-900";
    }
  };

  const getToastIcon = (type: string) => {
    switch (type) {
      case "success":
        return "✅";
      case "error":
        return "❌";
      case "warning":
        return "⚠️";
      case "info":
      default:
        return "ℹ️";
    }
  };

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

  return (
    <div
      className={`fixed ${isAr ? "left-4" : "right-4"} bottom-4 z-50 flex flex-col gap-3 w-80`}
    >
      {toasts.map((toast) => (
        <div
          key={toast.id}
          className={`animate-slide-up rounded-xl border-2 p-4 shadow-lg ${getToastStyles(toast.type)}`}
        >
          <div className="flex items-start gap-3">
            <span className="text-2xl">{getToastIcon(toast.type)}</span>
            <div className="flex-1">
              <p className="text-sm font-semibold">{toast.title}</p>
              <p className="mt-1 text-xs opacity-90">{toast.message}</p>
            </div>
            <button
              onClick={() =>
                setToasts((prev) => prev.filter((t) => t.id !== toast.id))
              }
              className="text-lg opacity-50 hover:opacity-100"
            >
              ×
            </button>
          </div>
        </div>
      ))}
    </div>
  );
}
