"use client";

import Image from "next/image";
import { usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { REPAIR_END, REPAIR_NOTICE } from "@/lib/restaurant-repair";

const DISMISSED_KEY = "kiln-repair-notice-2026-dismissed";

export function RestaurantRepairNotice({ active }: { active: boolean }) {
  const pathname = usePathname();
  const [showNotice, setShowNotice] = useState(active);
  const dialog = useRef<HTMLDialogElement>(null);
  const dismissed = useRef(false);
  const staffPage = /^\/(admin|operator|access)(\/|$)/.test(pathname);

  useEffect(() => {
    const remaining = REPAIR_END - Date.now();
    if (!active || remaining <= 0) {
      setShowNotice(false);
      return;
    }
    setShowNotice(true);
    const timer = window.setTimeout(() => setShowNotice(false), remaining);
    return () => window.clearTimeout(timer);
  }, [active]);

  useEffect(() => {
    const popup = dialog.current;
    if (!showNotice || staffPage || !popup || dismissed.current) return;
    try {
      if (sessionStorage.getItem(DISMISSED_KEY)) return;
    } catch {
      // The dismissal still lasts as long as the notice is mounted.
    }
    if (!popup.open) popup.showModal();
  }, [showNotice, staffPage]);

  function rememberDismissal() {
    dismissed.current = true;
    try {
      sessionStorage.setItem(DISMISSED_KEY, "1");
    } catch {
      // Session storage can be unavailable.
    }
  }

  if (!showNotice || staffPage) return null;

  return (
    <>
      <p className="border-t border-white/10 bg-kiln-black py-2 text-center text-sm font-semibold text-kiln-flame">
        <span className="site-container block">{REPAIR_NOTICE}</span>
      </p>
      <dialog
        ref={dialog}
        aria-label={REPAIR_NOTICE}
        onClose={rememberDismissal}
        onClick={(event) => {
          if (event.target === event.currentTarget) event.currentTarget.close();
        }}
        className="m-auto max-h-[90dvh] w-[calc(100%-2rem)] max-w-3xl overflow-visible rounded-xl bg-transparent p-0 backdrop:bg-black/80"
      >
        <button
          type="button"
          aria-label="Закрыть уведомление о ремонте"
          onClick={() => dialog.current?.close()}
          className="relative block w-full rounded-xl"
        >
          <Image
            src="/remont.png"
            alt={REPAIR_NOTICE}
            width={1448}
            height={1086}
            unoptimized
            className="max-h-[90dvh] w-full rounded-xl object-contain"
          />
          <span aria-hidden="true" className="absolute right-2 top-2 grid size-10 place-items-center rounded-full bg-kiln-black text-2xl text-kiln-milk shadow">×</span>
        </button>
      </dialog>
    </>
  );
}
