"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { X, Sparkles } from "lucide-react";
import type { Lang } from "@/lib/config";

const STORAGE_KEY = "mawidi_trial_banner_dismissed";
const DISMISS_DURATION_DAYS = 7;

interface TrialBannerProps {
  lang: Lang;
  variant?: "sticky" | "floating";
  showOnPages?: string[];
  hideOnPages?: string[];
}

const translations = {
  en: {
    message: "Start your 14-day free trial",
    subMessage: "No credit card required",
    cta: "Get Started",
    dismiss: "Dismiss",
  },
  ar: {
    message: "ابدأ تجربتك المجانية لمدة 14 يومًا",
    subMessage: "لا حاجة لبطاقة ائتمان",
    cta: "ابدأ الآن",
    dismiss: "إغلاق",
  },
};

/**
 * TrialBanner Component
 *
 * A persistent promotional banner highlighting the free trial offer.
 * Dismissible with localStorage persistence.
 *
 * Features:
 * - Sticky top banner or floating badge variant
 * - Bilingual support (Arabic/English)
 * - Dismiss persistence via localStorage
 * - Subtle animation for attention
 * - Mobile responsive
 *
 * @example
 * <TrialBanner lang="en" variant="sticky" />
 */
export function TrialBanner({
  lang,
  variant = "sticky",
  showOnPages,
  hideOnPages,
}: TrialBannerProps) {
  const [isVisible, setIsVisible] = useState(false);
  const [isAnimating, setIsAnimating] = useState(false);
  const t = translations[lang];
  const isRTL = lang === "ar";

  useEffect(() => {
    // Check if banner was dismissed
    const dismissedData = localStorage.getItem(STORAGE_KEY);
    if (dismissedData) {
      try {
        const { timestamp } = JSON.parse(dismissedData);
        const dismissedAt = new Date(timestamp);
        const now = new Date();
        const daysSinceDismiss =
          (now.getTime() - dismissedAt.getTime()) / (1000 * 60 * 60 * 24);

        if (daysSinceDismiss < DISMISS_DURATION_DAYS) {
          return; // Keep hidden
        }
      } catch {
        // Invalid data, show banner
      }
    }

    // Check page restrictions
    if (typeof window !== "undefined") {
      const currentPath = window.location.pathname;

      if (hideOnPages?.some((page) => currentPath.includes(page))) {
        return;
      }

      if (
        showOnPages &&
        !showOnPages.some((page) => currentPath.includes(page))
      ) {
        return;
      }
    }

    setIsVisible(true);

    // Start pulse animation after a short delay
    const timer = setTimeout(() => {
      setIsAnimating(true);
    }, 500);

    return () => clearTimeout(timer);
  }, [showOnPages, hideOnPages]);

  const handleDismiss = () => {
    setIsVisible(false);
    localStorage.setItem(
      STORAGE_KEY,
      JSON.stringify({ timestamp: new Date().toISOString() }),
    );
  };

  if (!isVisible) return null;

  if (variant === "floating") {
    return (
      <div
        className={`fixed bottom-4 z-40 transition-all duration-500 ${
          isRTL ? "left-4" : "right-4"
        } ${isAnimating ? "animate-bounce-subtle" : ""}`}
        dir={isRTL ? "rtl" : "ltr"}
      >
        <div className="relative bg-gradient-to-r from-emerald-600 to-teal-600 rounded-2xl shadow-2xl p-4 max-w-xs">
          {/* Close button */}
          <button
            onClick={handleDismiss}
            className={`absolute top-2 ${isRTL ? "left-2" : "right-2"} p-1 text-white/70 hover:text-white transition-colors rounded-full hover:bg-white/10`}
            aria-label={t.dismiss}
          >
            <X className="w-4 h-4" />
          </button>

          <div className="flex items-start gap-3">
            <div className="flex-shrink-0 w-10 h-10 rounded-full bg-white/20 flex items-center justify-center">
              <Sparkles className="w-5 h-5 text-white" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-white font-semibold text-sm leading-tight">
                {t.message}
              </p>
              <p className="text-white/80 text-xs mt-0.5">{t.subMessage}</p>
              <Link
                href={`/${lang}/signup`}
                className="inline-block mt-2 px-4 py-1.5 bg-white text-emerald-700 text-xs font-semibold rounded-full hover:bg-emerald-50 transition-colors"
              >
                {t.cta}
              </Link>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Sticky variant (default)
  return (
    <div
      className={`fixed top-0 left-0 right-0 z-50 bg-gradient-to-r from-emerald-600 via-teal-600 to-emerald-600 text-white py-2.5 px-4 transition-all duration-300 ${
        isAnimating ? "bg-[length:200%_auto] animate-gradient-x" : ""
      }`}
      dir={isRTL ? "rtl" : "ltr"}
    >
      <div className="max-w-7xl mx-auto flex items-center justify-center gap-4 flex-wrap">
        <div className="flex items-center gap-2">
          <Sparkles className="w-4 h-4 animate-pulse" />
          <span className="font-medium text-sm sm:text-base">{t.message}</span>
          <span className="hidden sm:inline text-white/80 text-sm">
            — {t.subMessage}
          </span>
        </div>

        <Link
          href={`/${lang}/signup`}
          className="px-4 py-1.5 bg-white text-emerald-700 text-sm font-semibold rounded-full hover:bg-emerald-50 transition-colors shadow-sm"
        >
          {t.cta}
        </Link>

        <button
          onClick={handleDismiss}
          className={`absolute ${isRTL ? "left-4" : "right-4"} p-1.5 text-white/70 hover:text-white transition-colors rounded-full hover:bg-white/10`}
          aria-label={t.dismiss}
        >
          <X className="w-4 h-4" />
        </button>
      </div>
    </div>
  );
}

export default TrialBanner;
