"use client";

import { useEffect, useState } from "react";
import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import { ArrowUpRight, Megaphone, X } from "lucide-react";
import {
  BROADCAST_DISMISSED_KEY,
  accentVar,
  type BroadcastStripData,
} from "@/lib/homeBroadcast";

interface Props {
  data: BroadcastStripData | null | undefined;
  version: string; // the broadcast.json top-level version — bumping it re-shows
}

// BroadcastStrip — the full-width announcement Luke pushes to every install.
// Dismiss remembers THIS version only; a new version in the hosted JSON brings
// the strip back for everyone.
export default function BroadcastStrip({ data, version }: Props) {
  const [dismissed, setDismissed] = useState<boolean | null>(null); // null = not decided yet
  const reduceMotion = useReducedMotion();

  useEffect(() => {
    if (!data?.show) return;
    try {
      setDismissed(localStorage.getItem(BROADCAST_DISMISSED_KEY) === version);
    } catch {
      setDismissed(false);
    }
  }, [data, version]);

  const dismiss = () => {
    setDismissed(true);
    try { localStorage.setItem(BROADCAST_DISMISSED_KEY, version); } catch { /* private mode */ }
  };

  const visible = Boolean(data?.show) && dismissed === false;
  const accent = accentVar(data?.accent);

  return (
    <AnimatePresence initial={false}>
      {visible && data && (
        <motion.section
          key={`broadcast-${version}`}
          initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: -8 }}
          animate={{ opacity: 1, y: 0 }}
          exit={reduceMotion ? { opacity: 0 } : { opacity: 0, y: -6 }}
          transition={{ duration: reduceMotion ? 0.01 : 0.3 }}
          aria-label="Announcement"
          className="relative overflow-hidden rounded-lg border"
          style={{
            borderColor: `color-mix(in srgb, ${accent} 28%, transparent)`,
            background: `linear-gradient(100deg, color-mix(in srgb, ${accent} 9%, var(--bg-card)), var(--bg-card) 55%)`,
            boxShadow: `var(--shadow-1), 0 12px 40px -22px color-mix(in srgb, ${accent} 55%, transparent)`,
          }}
        >
          {/* accent edge */}
          <span aria-hidden className="absolute left-0 top-0 bottom-0 w-[3px]" style={{ background: accent, boxShadow: `0 0 14px ${accent}` }} />

          <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-5 px-4 sm:px-6 py-4 pr-12">
            <div className="flex items-center gap-3 shrink-0">
              <span
                className="grid place-items-center w-8 h-8 rounded-md"
                style={{ background: `color-mix(in srgb, ${accent} 14%, transparent)`, color: accent, border: `1px solid color-mix(in srgb, ${accent} 30%, transparent)` }}
              >
                <Megaphone size={14} />
              </span>
              {data.badge && (
                <span
                  className="pill"
                  style={{ color: accent, borderColor: `color-mix(in srgb, ${accent} 35%, transparent)`, background: `color-mix(in srgb, ${accent} 8%, transparent)` }}
                >
                  {data.badge}
                </span>
              )}
            </div>

            <div className="min-w-0 flex-1">
              {data.headline && (
                <h3 className="text-[15.5px] leading-snug" style={{ letterSpacing: "-0.015em" }}>
                  {data.headline}
                </h3>
              )}
              {data.body && (
                <p className="mt-0.5 text-[13px] leading-relaxed" style={{ color: "var(--cream-soft)" }}>
                  {data.body}
                </p>
              )}
            </div>

            {data.ctaUrl && data.ctaLabel && (
              <a
                href={data.ctaUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="focus-ring shrink-0 inline-flex items-center justify-center gap-1.5 rounded-full px-4 py-2 text-[11px] font-bold uppercase tracking-[0.16em] transition-transform hover:-translate-y-px active:translate-y-0"
                style={{ background: accent, color: "var(--bg-deep)", boxShadow: `0 6px 18px -8px ${accent}` }}
              >
                {data.ctaLabel} <ArrowUpRight size={13} />
              </a>
            )}
          </div>

          <button
            onClick={dismiss}
            aria-label="Dismiss announcement"
            className="focus-ring absolute top-3 right-3 grid place-items-center w-7 h-7 rounded-md transition-colors"
            style={{ color: "var(--cream-mute)" }}
            onMouseEnter={(e) => { e.currentTarget.style.color = "var(--cream)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.color = "var(--cream-mute)"; }}
          >
            <X size={14} />
          </button>
        </motion.section>
      )}
    </AnimatePresence>
  );
}
