"use client";
import React, { useState, useEffect, useRef } from "react";
import Link from "next/link";

const CONSENT_KEY = "bb_cookie_consent";
const CONSENT_DAYS = 365;

function readConsent(): string | null {
  // Cookie first — survives most "clear localStorage on close" settings.
  if (typeof document !== "undefined") {
    const m = document.cookie.match(/(?:^|;\s*)bb_cookie_consent=([^;]+)/);
    if (m) return decodeURIComponent(m[1]);
  }
  try {
    return localStorage.getItem(CONSENT_KEY);
  } catch {
    return null;
  }
}

function writeConsent(value: "accepted" | "declined") {
  // Write to BOTH so we survive browsers that wipe one but not the other.
  try {
    const maxAge = CONSENT_DAYS * 24 * 60 * 60;
    document.cookie = `${CONSENT_KEY}=${encodeURIComponent(value)}; path=/; max-age=${maxAge}; SameSite=Lax`;
  } catch {}
  try {
    localStorage.setItem(CONSENT_KEY, value);
  } catch {}
}

export default function CookieConsent() {
  const [visible, setVisible] = useState(false);
  const acceptRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    if (readConsent()) return; // already decided — stay hidden
    const timer = setTimeout(() => setVisible(true), 1200);
    return () => clearTimeout(timer);
  }, []);

  // Focus the accept button when banner appears (accessibility)
  useEffect(() => {
    if (visible) {
      acceptRef?.current?.focus();
    }
  }, [visible]);

  const handleAccept = () => {
    writeConsent("accepted");
    setVisible(false);
  };

  const handleDecline = () => {
    writeConsent("declined");
    setVisible(false);
  };

  if (!visible) return null;

  return (
    <div
      role="dialog"
      aria-modal="false"
      aria-label="Cookie consent"
      aria-describedby="cookie-consent-desc"
      className="fixed bottom-0 left-0 right-0 z-[9999] bg-[#0d1117] border-t border-[#2a3a50] shadow-2xl"
    >
      <div className="max-w-container mx-auto px-4 py-4 flex flex-col sm:flex-row items-start sm:items-center gap-4 justify-between">
        <div className="flex-1 min-w-0">
          <p
            id="cookie-consent-desc"
            className="text-[#aaa] text-sm font-body leading-relaxed"
          >
            <span className="font-bold text-white">AV Beat</span> uses cookies and similar technologies to improve your experience, analyze site traffic, and serve relevant advertising. By clicking{" "}
            <strong className="text-white">Accept All</strong>, you consent to our use of cookies.{" "}
            <Link
              href="/privacy"
              className="text-[#1D4ED8] underline hover:text-blue-400 focus:outline-none focus-visible:ring-1 focus-visible:ring-[#1D4ED8] transition-colors"
            >
              Privacy Policy
            </Link>
          </p>
        </div>
        <div className="flex items-center gap-3 flex-shrink-0">
          <button
            type="button"
            onClick={handleDecline}
            className="px-4 py-2 text-sm font-body font-bold text-[#888] border border-[#333] rounded hover:border-[#555] hover:text-[#aaa] transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-[#1D4ED8] focus-visible:ring-offset-1 focus-visible:ring-offset-[#0d1117]"
            aria-label="Decline non-essential cookies"
          >
            Decline
          </button>
          <button
            ref={acceptRef}
            type="button"
            onClick={handleAccept}
            className="px-5 py-2 text-sm font-body font-bold text-white bg-[#1D4ED8] rounded hover:bg-blue-500 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-[#1D4ED8] focus-visible:ring-offset-2 focus-visible:ring-offset-[#0d1117]"
            aria-label="Accept all cookies"
          >
            Accept All
          </button>
        </div>
      </div>
    </div>
  );
}
