"use client";

import { Toaster, ToastBar, toast } from "react-hot-toast";

// ─── Shared close button ───────────────────────────────────────────────────────
const CloseBtn = ({ toastId }: { toastId: string }) => (
  <button
    onClick={() => toast.dismiss(toastId)}
    style={{
      width: 30, height: 30, borderRadius: 7,
      border: "0.5px solid #e5e7eb",
      background: "#f9fafb",
      display: "flex", alignItems: "center", justifyContent: "center",
      cursor: "pointer", flexShrink: 0, marginRight: 14,
      transition: "background 0.15s",
    }}
    onMouseEnter={(e) => (e.currentTarget.style.background = "#f3f4f6")}
    onMouseLeave={(e) => (e.currentTarget.style.background = "#f9fafb")}
  >
    <svg width="11" height="11" viewBox="0 0 24 24" fill="none"
      stroke="#9ca3af" strokeWidth="2.5" strokeLinecap="round">
      <line x1="18" y1="6"  x2="6"  y2="18" />
      <line x1="6"  y1="6"  x2="18" y2="18" />
    </svg>
  </button>
);

// ─── Icon + colour config per type ────────────────────────────────────────────
const TYPE_CONFIG = {
  success: {
    bar:    "#16a34a",
    iconBg: "#f0fdf4",
    icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none"
        stroke="#16a34a" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="10" />
        <polyline points="9 12 11 14 15 10" />
      </svg>
    ),
  },
  error: {
    bar:    "#dc2626",
    iconBg: "#fef2f2",
    icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none"
        stroke="#dc2626" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="10" />
        <line x1="12" y1="8"  x2="12"    y2="12" />
        <line x1="12" y1="16" x2="12.01" y2="16" />
      </svg>
    ),
  },
  loading: {
    bar:    "#6d28d9",
    iconBg: "#f5f3ff",
    icon: (
      <div style={{
        width: 20, height: 20, borderRadius: "50%",
        border: "2.2px solid #e9d5ff",
        borderTopColor: "#6d28d9",
        animation: "ht-spin 0.75s linear infinite",
      }} />
    ),
  },
  blank: {
    bar:    "#6b7280",
    iconBg: "#f9fafb",
    icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none"
        stroke="#6b7280" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="10" />
        <line x1="12" y1="8"  x2="12.01" y2="8" />
        <line x1="12" y1="12" x2="12"    y2="16" />
      </svg>
    ),
  },
} as const;

// ─── Global keyframes injected once ───────────────────────────────────────────
if (typeof document !== "undefined" && !document.getElementById("ht-style")) {
  const s = document.createElement("style");
  s.id = "ht-style";
  s.textContent = `
    @keyframes ht-spin     { to { transform: rotate(360deg); } }
    @keyframes ht-in       { from { opacity:0; transform:translateY(-14px) scale(0.96); }
                             to   { opacity:1; transform:translateY(0)      scale(1);   } }
    @keyframes ht-progress { from { width: 100%; } to { width: 0%; } }
  `;
  document.head.appendChild(s);
}

// ─── AppToaster ───────────────────────────────────────────────────────────────
export const AppToaster = () => {
  return (
    <Toaster
      position="top-center"
      reverseOrder={false}
      gutter={10}
      containerStyle={{
        top: 24,
        left: 0,
        right: 0,
        position: "fixed",
        display: "flex",
        justifyContent: "center",
        zIndex: 9999,
        pointerEvents: "none",
      }}
      toastOptions={{
        duration: 3000,
        // Wipe out react-hot-toast's default shell completely
        style: { background: "transparent", boxShadow: "none", padding: 0, margin: 0, maxWidth: "none" },
      }}
    >
      {(t) => {
        const type   = t.type as keyof typeof TYPE_CONFIG;
        const config = TYPE_CONFIG[type] ?? TYPE_CONFIG.blank;

        // Support "Title | Subtitle" pattern
        const rawMsg  = typeof t.message === "string" ? t.message : "";
        const [title, ...rest] = rawMsg.split("|");
        const subtitle = rest.join("|").trim();

        return (
          <ToastBar toast={t} style={{ background: "transparent", padding: 0, boxShadow: "none", maxWidth: "none" }}>
            {() => (
              <div
                style={{
                  pointerEvents: "auto",
                  display: "flex",
                  alignItems: "center",
                  background: "#ffffff",
                  borderRadius: 14,
                  border: "0.5px solid #e5e7eb",
                  boxShadow: "0 8px 32px rgba(0,0,0,0.10), 0 2px 8px rgba(0,0,0,0.06)",

                  // ── Wide sizing ─────────────────────────────────────
                  minWidth: 620,
                  maxWidth: 780,
                  width: "100%",

                  overflow: "hidden",
                  position: "relative",
                  animation: t.visible
                    ? "ht-in 0.4s cubic-bezier(0.34,1.56,0.64,1) both"
                    : undefined,
                }}
              >
                {/* ── Coloured left bar ── */}
                <div style={{
                  width: 4, alignSelf: "stretch",
                  flexShrink: 0, background: config.bar,
                }} />

                {/* ── Icon pill ── */}
                <div style={{
                  width: 44, height: 44, borderRadius: 10,
                  background: config.iconBg,
                  display: "flex", alignItems: "center", justifyContent: "center",
                  margin: "16px 0 16px 16px", flexShrink: 0,
                }}>
                  {config.icon}
                </div>

                {/* ── Text body ── */}
                <div style={{ flex: 1, padding: "16px 14px", minWidth: 0 }}>
                  <p style={{
                    margin: subtitle ? "0 0 3px" : 0,
                    fontSize: 14, fontWeight: 600,
                    color: "#111827", letterSpacing: "-0.01em",
                    whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
                  }}>
                    {title.trim()}
                  </p>
                  {subtitle && (
                    <p style={{
                      margin: 0, fontSize: 13,
                      color: "#6b7280", lineHeight: 1.45,
                    }}>
                      {subtitle}
                    </p>
                  )}
                </div>

                {/* ── Close button ── */}
                <CloseBtn toastId={t.id} />

                {/* ── Animated progress bar (hidden on loading toasts) ── */}
                {t.type !== "loading" && (
                  <div style={{
                    position: "absolute", bottom: 0, left: 4, right: 0,
                    height: 2, background: "rgba(0,0,0,0.05)",
                  }}>
                    <div style={{
                      height: "100%",
                      background: config.bar,
                      borderRadius: 2,
                      animation: `ht-progress ${t.duration ?? 3000}ms linear forwards`,
                    }} />
                  </div>
                )}
              </div>
            )}
          </ToastBar>
        );
      }}
    </Toaster>
  );
};