"use client";

import { useEffect, useState } from "react";
import { api } from "@/lib/api-client";

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

  useEffect(() => {
    try {
      if (!localStorage.getItem("playtube-cookies")) setVisible(true);
    } catch {
      /* private mode */
    }
  }, []);

  if (!visible) return null;
  return (
    <div className="fixed bottom-20 left-3 right-3 z-[125] mx-auto max-w-3xl rounded-xl border border-line bg-bg-elevated p-4 shadow-2xl sm:bottom-4">
      <p className="text-sm text-muted">
        PlayTube uses cookies to keep you signed in, remember your theme and language, and measure aggregate
        performance. You can change this any time in Settings.
      </p>
      <div className="mt-3 flex flex-wrap gap-2">
        <button
          className="rounded-full bg-brand px-4 py-1.5 text-sm font-semibold text-white"
          onClick={() => {
            try {
              localStorage.setItem("playtube-cookies", "all");
            } catch {}
            setVisible(false);
          }}
        >
          Accept all
        </button>
        <button
          className="rounded-full border border-line px-4 py-1.5 text-sm font-semibold"
          onClick={() => {
            try {
              localStorage.setItem("playtube-cookies", "essential");
            } catch {}
            setVisible(false);
          }}
        >
          Essential only
        </button>
        <button
          className="rounded-full px-4 py-1.5 text-sm font-semibold text-muted"
          onClick={async () => {
            try {
              localStorage.setItem("playtube-cookies", "all");
            } catch {}
            await api("/api/me", { method: "PATCH", json: { cookieConsent: true } }).catch(() => undefined);
            setVisible(false);
          }}
        >
          Accept &amp; save to account
        </button>
      </div>
    </div>
  );
}
