import React, { createContext, useCallback, useContext, useMemo, useRef, useState } from "react";

const ToastContext = createContext(null);

function uid() {
  return Math.random().toString(16).slice(2) + Date.now().toString(16);
}

export function ToastProvider({ children }) {
  const [toasts, setToasts] = useState([]);
  const timers = useRef(new Map());

  const removeToast = useCallback((id) => {
    setToasts((prev) => prev.filter((t) => t.id !== id));
    const t = timers.current.get(id);
    if (t) clearTimeout(t);
    timers.current.delete(id);
  }, []);

  const showToast = useCallback(
    ({ title, message, type = "info", duration = 3500 } = {}) => {
      const id = uid();
      const toast = { id, title, message, type };
      setToasts((prev) => [...prev, toast]);

      if (duration && duration > 0) {
        const timer = setTimeout(() => removeToast(id), duration);
        timers.current.set(id, timer);
      }

      return id;
    },
    [removeToast]
  );

  const api = useMemo(
    () => ({
      toast: showToast,
      success: (message, opts) => showToast({ type: "success", message, ...opts }),
      error: (message, opts) => showToast({ type: "error", message, ...opts }),
      info: (message, opts) => showToast({ type: "info", message, ...opts }),
      warning: (message, opts) => showToast({ type: "warning", message, ...opts }),
      remove: removeToast,
      clear: () => setToasts([]),
    }),
    [showToast, removeToast]
  );

  return (
    <ToastContext.Provider value={api}>
      {children}
      <ToastViewport toasts={toasts} onClose={removeToast} />
    </ToastContext.Provider>
  );
}

export function useToast() {
  const ctx = useContext(ToastContext);
  if (!ctx) throw new Error("useToast must be used within <ToastProvider />");
  return ctx;
}

function ToastViewport({ toasts, onClose }) {
  // ✅ فقط شرط اضافه شد (بدون react-router)
  const pathname = typeof window !== "undefined" ? window.location.pathname : "";
  const isAuthPage =
    pathname === "/auth/login" ||
    pathname === "/auth/forget-password" ||
    pathname === "/auth/register" ||
    pathname === "/auth/payment" ||
    pathname.startsWith("/auth/payment/") ||
    pathname.startsWith("/auth/login/") ||
    pathname.startsWith("/auth/forget-password/") ||
    pathname.startsWith("/auth/register/");

  return (
    <div className={`fixed z-[9999] ${isAuthPage ? "dark" : ""} top-4 right-4 flex flex-col gap-3 w-[340px] max-w-[90vw]`}>
      {toasts.map((t) => (
        <ToastItem key={t.id} toast={t} onClose={() => onClose(t.id)} />
      ))}
    </div>
  );
}

function ToastItem({ toast, onClose }) {
  const styles = {
    success: "border-green-500/40 bg-green-500/10",
    error: "border-red-500/40 bg-red-500/10",
    info: "border-sky-500/40 bg-sky-500/10",
    warning: "border-amber-500/40 bg-amber-500/10",
  };

  const dot = {
    success: "bg-green-400",
    error: "bg-red-400",
    info: "bg-sky-400",
    warning: "bg-amber-400",
  };

  return (
    <div
      className={`backdrop-blur-md border rounded-xl px-4 py-3 dark:text-white shadow-lg ${styles[toast.type] || styles.info}`}
      role="status"
    >
      <div className="flex items-start gap-3">
        <span className={`mt-1.5 w-2.5 h-2.5 rounded-full ${dot[toast.type] || dot.info}`} />
        <div className="flex-1">
          {toast.title ? <div className="font-bold text-sm mb-0.5">{toast.title}</div> : null}
          {toast.message ? <div className="text-sm opacity-90 leading-6">{toast.message}</div> : null}
        </div>
        <button
          onClick={onClose}
          className="dark:text-white/80 dark:hover:text-white text-lg leading-none px-2"
          aria-label="Close toast"
          type="button"
        >
          ×
        </button>
      </div>
    </div>
  );
}
