---
interface Props {
  message?: string;
  type?: "error" | "success" | "warning" | "info";
  duration?: number;
}

const { message = "", type = "error", duration = 3000 } = Astro.props;

// Серверная конфигурация (используется для начального рендера)
const typeConfig = {
  error: {
    bg: "bg-red-50",
    border: "border-red-500",
    icon: "text-red-500",
    iconPath:
      '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />',
  },
  success: {
    bg: "bg-green-50",
    border: "border-green-500",
    icon: "text-green-500",
    iconPath:
      '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />',
  },
  warning: {
    bg: "bg-yellow-50",
    border: "border-yellow-500",
    icon: "text-yellow-500",
    iconPath:
      '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />',
  },
  info: {
    bg: "bg-blue-50",
    border: "border-blue-500",
    icon: "text-blue-500",
    iconPath:
      '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />',
  },
};

const config = typeConfig[type];
---

<div
  id="toast-notification"
  class="fixed top-4 left-0 right-0 mx-auto z-9999 min-w-[320px] max-w-md flex justify-center"
  role="alert"
  aria-live="polite"
  hidden
>
  <div
    id="toast-content"
    class={`${config.bg} border-l-4 ${config.border} rounded-lg shadow-2xl p-4 flex items-start gap-3 transition-all duration-300`}
  >
    <div
      id="toast-icon-container"
      class={`${config.icon} shrink-0 transition-colors duration-300`}
    >
      <svg
        id="toast-icon-svg"
        class="w-5 h-5"
        fill="none"
        stroke="currentColor"
        viewBox="0 0 24 24"
      >
        <Fragment set:html={config.iconPath} />
      </svg>
    </div>
    <p class="text-gray-800 text-sm font-medium flex-1" id="toast-message">
      {message}
    </p>
    <button
      type="button"
      id="toast-close"
      class="shrink-0 text-gray-400 hover:text-gray-600 cursor-pointer transition-colors"
      aria-label="Закрыть уведомление"
    >
      <svg
        class="w-4 h-4"
        fill="none"
        stroke="currentColor"
        viewBox="0 0 24 24"
      >
        <path
          stroke-linecap="round"
          stroke-linejoin="round"
          stroke-width="2"
          d="M6 18L18 6M6 6l12 12"></path>
      </svg>
    </button>
  </div>
</div>

<script is:inline>
  const toast = document.getElementById("toast-notification");
  const toastContent = document.getElementById("toast-content");
  const toastIconContainer = document.getElementById("toast-icon-container");
  const toastIconSvg = document.getElementById("toast-icon-svg");
  const toastMessage = document.getElementById("toast-message");
  const toastClose = document.getElementById("toast-close");
  let timeoutId;

  // Клиентская конфигурация для динамического изменения стилей
  const clientTypeConfig = {
    error: {
      bg: "bg-red-50",
      border: "border-red-500",
      icon: "text-red-500",
      path: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />',
    },
    success: {
      bg: "bg-green-50",
      border: "border-green-500",
      icon: "text-green-500",
      path: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />',
    },
    warning: {
      bg: "bg-yellow-50",
      border: "border-yellow-500",
      icon: "text-yellow-500",
      path: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />',
    },
    info: {
      bg: "bg-blue-50",
      border: "border-blue-500",
      icon: "text-blue-500",
      path: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />',
    },
  };

  function updateToastStyles(type) {
    if (!toastContent || !toastIconContainer || !toastIconSvg) return;

    const config = clientTypeConfig[type] || clientTypeConfig.error;

    // Очищаем старые классы (оставляем только базовые)
    toastContent.className = `border-l-4 rounded-lg shadow-lg p-4 flex items-start gap-3 transition-colors duration-300 ${config.bg} ${config.border}`;
    toastIconContainer.className = `flex-shrink-0 transition-colors duration-300 ${config.icon}`;

    // Меняем иконку
    toastIconSvg.innerHTML = config.path;
  }

  function showToast(message, type = "error", duration = 3000) {
    console.log("[TOAST] Вызов showToast:", { message, type, duration });
    console.log("[TOAST] Элементы:", {
      toast: !!toast,
      toastMessage: !!toastMessage,
    });

    // Очищаем предыдущий таймер
    clearTimeout(timeoutId);

    // Устанавливаем сообщение и обновляем стили
    if (toastMessage) toastMessage.textContent = message;
    updateToastStyles(type);

    // Показываем тост с анимацией
    if (toast) {
      console.log("[TOAST] Показываем toast, hidden был:", toast.hidden);
      console.log(
        "[TOAST] computed style до изменений:",
        window.getComputedStyle(toast).display,
      );

      toast.hidden = false;
      toast.style.display = "flex"; // Явно показываем
      toast.style.opacity = "0";
      toast.style.transform = "translateY(-20px)";
      toast.style.transition = "opacity 0.3s ease, transform 0.3s ease";

      // Форсируем перерисовку браузера (чтобы анимация сработала)
      toast.offsetHeight;
      console.log(
        "[TOAST] После offsetHeight, hidden:",
        toast.hidden,
        "display:",
        toast.style.display,
      );

      // Анимация появления
      toast.style.opacity = "1";
      toast.style.transform = "translateY(0)";

      console.log("[TOAST] Toast показан, opacity:", toast.style.opacity);
      console.log(
        "[TOAST] computed style после:",
        window.getComputedStyle(toast).display,
        window.getComputedStyle(toast).opacity,
      );

      // Автоматическое скрытие
      timeoutId = setTimeout(() => {
        console.log("[TOAST] Скрываем по таймеру");
        hideToast();
      }, duration);
    } else {
      console.error("[TOAST] Элемент toast не найден!");
    }
  }

  function hideToast() {
    if (toast) {
      toast.style.opacity = "0";
      toast.style.transform = "translateY(-20px)";

      setTimeout(() => {
        toast.hidden = true;
      }, 300);
    }
  }

  // Закрытие по кнопке
  if (toastClose) {
    toastClose.addEventListener("click", hideToast);
  }

  // Делаем функции доступными глобально для вызова из других компонентов (например, из LoginForm)
  window.showToast = showToast;
  window.hideToast = hideToast;
</script>

<style>
  #toast-notification[hidden] {
    display: none;
  }
</style>
