"use client";

import { AnimatePresence, motion } from "framer-motion";
import { Cookie } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { cn } from "@/utils/cn";

const STORAGE_KEY = "chathiro-cookie-consent";

type ConsentChoice = "accepted" | "essential";

function readStoredConsent(): ConsentChoice | null {
  try {
    const value = window.localStorage.getItem(STORAGE_KEY);
    if (value === "accepted" || value === "essential") return value;
  } catch {
    // private mode / blocked storage
  }
  return null;
}

function storeConsent(choice: ConsentChoice) {
  try {
    window.localStorage.setItem(STORAGE_KEY, choice);
  } catch {
    // ignore persistence failures; banner still dismisses for this session
  }
}

export default function CookieConsent() {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (readStoredConsent()) return;

    const timer = window.setTimeout(() => setVisible(true), 700);
    return () => window.clearTimeout(timer);
  }, []);

  const choose = (choice: ConsentChoice) => {
    storeConsent(choice);
    setVisible(false);
  };

  return (
    <AnimatePresence>
      {visible && (
        <motion.aside
          role="dialog"
          aria-modal="false"
          aria-labelledby="cookie-consent-title"
          aria-describedby="cookie-consent-description"
          initial={{ opacity: 0, y: 28 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: 20 }}
          transition={{ duration: 0.35, ease: [0.22, 1, 0.36, 1] }}
          className={cn(
            "fixed right-3 bottom-3 left-3 z-90 sm:right-6 sm:bottom-6 sm:left-auto",
            "w-auto sm:w-full sm:max-w-105",
          )}
        >
          <div
            className={cn(
              "overflow-hidden rounded-2xl bg-white",
              "border border-ink/08",
              "shadow-[0_24px_60px_-24px_rgba(4,16,57,0.45),0_0_0_1px_rgba(4,16,57,0.04)]",
            )}
          >
            <div
              className="px-5 pt-5 pb-4 sm:px-6 sm:pt-6"
              style={{
                backgroundImage: `
                  radial-gradient(ellipse 85% 100% at 0% 0%, #EDE9FF 0%, transparent 55%),
                  radial-gradient(ellipse 70% 90% at 100% 0%, #DDFBE9 0%, transparent 50%)
                `,
              }}
            >
              <div className="mb-3 inline-flex h-10 w-10 items-center justify-center rounded-xl bg-white/80 text-brand shadow-[0_1px_0_rgba(4,16,57,0.06)] ring-1 ring-ink/06">
                <Cookie className="h-5 w-5" strokeWidth={1.75} aria-hidden />
              </div>

              <h2
                id="cookie-consent-title"
                className="text-lg font-semibold tracking-tight text-ink sm:text-xl"
              >
                Cookies & privacy
              </h2>

              <p
                id="cookie-consent-description"
                className="mt-2 text-sm leading-relaxed text-ink/70"
              >
                We use essential cookies to keep the site working and improve
                reliability. Optional cookies help us understand usage. See our{" "}
                <Link
                  href="/legal/privacy-policy"
                  className="font-semibold text-brand underline decoration-brand/30 underline-offset-2 transition-colors hover:text-brand-hover hover:decoration-brand-hover/50"
                >
                  Privacy Policy
                </Link>
                .
              </p>
            </div>

            <div className="flex flex-col gap-2 border-t border-ink/06 bg-[#F8FAFC] px-5 py-4 sm:flex-row sm:items-center sm:justify-end sm:gap-3 sm:px-6">
              <button
                type="button"
                onClick={() => choose("essential")}
                className={cn(
                  "inline-flex h-11 items-center justify-center rounded-xl px-4",
                  "text-sm font-semibold text-ink",
                  "bg-white ring-1 ring-ink/10",
                  "transition-colors duration-200",
                  "hover:bg-[#F1F5F9] hover:ring-ink/16",
                  "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand",
                )}
              >
                Essential only
              </button>
              <button
                type="button"
                onClick={() => choose("accepted")}
                className={cn(
                  "inline-flex h-11 items-center justify-center rounded-xl px-5",
                  "text-sm font-semibold text-white",
                  "bg-brand shadow-[0_10px_24px_-12px_rgba(108,92,231,0.85)]",
                  "transition-colors duration-200",
                  "hover:bg-brand-strong",
                  "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand",
                )}
              >
                Accept all
              </button>
            </div>
          </div>
        </motion.aside>
      )}
    </AnimatePresence>
  );
}
