"use client";

import { useEffect, useState } from "react";
import { BottomToast, type BottomToastNotice } from "@/components/bottom-toast";

export function DismissibleBottomToast({
  notice,
  autoHideMs = 4200,
  clearSearchParams = [],
}: {
  notice: BottomToastNotice | null;
  autoHideMs?: number;
  clearSearchParams?: string[];
}) {
  const noticeKey = notice ? `${notice.tone}:${notice.message}` : "";
  const [dismissedNoticeKey, setDismissedNoticeKey] = useState("");

  useEffect(() => {
    if (!noticeKey || clearSearchParams.length === 0 || typeof window === "undefined") {
      return;
    }

    const url = new URL(window.location.href);
    let changed = false;

    for (const key of clearSearchParams) {
      if (url.searchParams.has(key)) {
        url.searchParams.delete(key);
        changed = true;
      }
    }

    if (!changed) {
      return;
    }

    const nextUrl = `${url.pathname}${url.search}${url.hash}`;
    window.history.replaceState(window.history.state, "", nextUrl);
  }, [clearSearchParams, noticeKey]);

  useEffect(() => {
    if (!noticeKey) {
      return;
    }

    const timer = window.setTimeout(() => {
      setDismissedNoticeKey(noticeKey);
    }, autoHideMs);

    return () => window.clearTimeout(timer);
  }, [autoHideMs, noticeKey]);

  if (!notice || dismissedNoticeKey === noticeKey) {
    return null;
  }

  return <BottomToast notice={notice} onClose={() => setDismissedNoticeKey(noticeKey)} />;
}
