"use client";

import { useSyncExternalStore } from "react";

const STORAGE_KEY = "tuvi-cookie-consent";

type ConsentValue = "accepted" | "rejected" | null;

function getSnapshot(): ConsentValue {
  if (typeof window === "undefined") return null;
  return (localStorage.getItem(STORAGE_KEY) as ConsentValue) ?? null;
}

function getServerSnapshot(): ConsentValue {
  return null;
}

function subscribe(onChange: () => void) {
  if (typeof window === "undefined") return () => {};
  const handler = (e: StorageEvent) => {
    if (e.key === STORAGE_KEY) onChange();
  };
  window.addEventListener("storage", handler);
  // Custom event for same-tab updates
  const localHandler = () => onChange();
  window.addEventListener("tuvi:consent", localHandler);
  return () => {
    window.removeEventListener("storage", handler);
    window.removeEventListener("tuvi:consent", localHandler);
  };
}

export function CookieConsent() {
  const consent = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);

  if (consent === "accepted" || consent === "rejected") {
    return null;
  }

  const handle = (value: "accepted" | "rejected") => {
    localStorage.setItem(STORAGE_KEY, value);
    window.dispatchEvent(new Event("tuvi:consent"));
    if ((window as unknown as { __consentChange?: (v: string) => void }).__consentChange) {
      (window as unknown as { __consentChange: (v: string) => void }).__consentChange(value);
    }
  };

  return (
    <div
      role="dialog"
      aria-labelledby="cookie-consent-title"
      className="fixed inset-x-0 bottom-0 z-50 border-t border-stone-800 bg-stone-950/95 px-4 py-4 backdrop-blur-md sm:right-auto sm:bottom-4 sm:left-4 sm:max-w-md sm:rounded-2xl sm:border"
    >
      <h2 id="cookie-consent-title" className="font-serif text-sm font-semibold text-stone-100">
        Cookie & Phân tích
      </h2>
      <p className="mt-1.5 text-xs leading-relaxed text-stone-400">
        Chúng tôi dùng cookie cho phiên đăng nhập (bắt buộc) và Google Analytics để cải thiện trải
        nghiệm. Bạn có thể từ chối analytics mà vẫn dùng được toàn bộ tính năng.
      </p>
      <div className="mt-3 flex gap-2">
        <button
          type="button"
          onClick={() => handle("accepted")}
          className="flex-1 rounded-md bg-amber-500 px-3 py-2 text-xs font-medium text-stone-950 transition hover:brightness-105"
        >
          Đồng ý tất cả
        </button>
        <button
          type="button"
          onClick={() => handle("rejected")}
          className="rounded-md border border-stone-700 px-3 py-2 text-xs text-stone-300 transition hover:border-stone-600"
        >
          Chỉ cookie cần thiết
        </button>
      </div>
    </div>
  );
}
