'use client';

/**
 * BNPLPriceDisplay Component
 * 
 * High-converting "Buy Now, Pay Later" price widget for ShineCode PDP & Checkout.
 * Supports Tabby and Tamara with 4 interest-free split calculations,
 * 100% SEO-safe microdata markup (`itemProp="price"`),
 * desktop hover card and mobile-optimized modal drawer with full dark mode support.
 */

import React, { useState, useRef, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Info, X, ShieldCheck } from 'lucide-react';
import { PriceDisplay } from '@/components/PriceDisplay';
import { cn } from '@/lib/utils';

export interface BNPLPriceDisplayProps {
  totalAmount: number;
  originalPrice?: number;
  locale?: string;
  className?: string;
}

export function TabbyBadge() {
  return (
    <span
      className="inline-flex items-center px-1.5 py-0.5 rounded bg-[#3EEDBF] text-zinc-950 font-black text-[10px] tracking-tighter shadow-2xs select-none"
      aria-label="Tabby"
    >
      tabby
    </span>
  );
}

export function TamaraBadge() {
  return (
    <span
      className="inline-flex items-center px-1.5 py-0.5 rounded bg-[#FF8C68] text-zinc-950 font-black text-[10px] tracking-tighter shadow-2xs select-none"
      aria-label="Tamara"
    >
      tamara
    </span>
  );
}

export function BNPLPriceDisplay({
  totalAmount,
  originalPrice,
  locale = 'en',
  className,
}: BNPLPriceDisplayProps) {
  const isAr = locale === 'ar';
  const splitAmount = (totalAmount / 4).toFixed(2);
  const numSplit = parseFloat(splitAmount);

  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  // Close popup on click outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  return (
    <div ref={containerRef} className={cn('space-y-2', className)}>
      {/* ── 2. Visual Layout: Price + BNPL Badge ── */}
      <div className="flex items-center gap-3 flex-wrap">
        {/* Full Price with SEO Microdata fallback */}
        <div className="flex items-baseline gap-2">
          <span itemProp="price" content={String(totalAmount)}>
            <PriceDisplay
              amount={totalAmount}
              className="text-3xl font-extrabold text-zinc-900 dark:text-white tracking-tight"
            />
          </span>
          {originalPrice && (
            <PriceDisplay
              amount={originalPrice}
              className="text-sm text-zinc-400 line-through font-medium"
            />
          )}
        </div>

        {/* BNPL Hover Badge Trigger */}
        <div className="relative">
          <button
            type="button"
            onClick={() => setIsOpen((prev) => !prev)}
            onMouseEnter={() => setIsOpen(true)}
            className="group flex items-center gap-1.5 px-3 py-1 bg-zinc-50 dark:bg-zinc-800 border border-zinc-200/90 dark:border-zinc-700 rounded-full text-xs font-medium text-zinc-600 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-700 hover:border-zinc-300 dark:hover:border-zinc-600 transition-all cursor-pointer select-none shadow-2xs"
            aria-expanded={isOpen}
            aria-haspopup="dialog"
          >
            <span className="font-bold text-zinc-900 dark:text-white">
              {isAr
                ? `${splitAmount} د.إ × 4`
                : `AED ${splitAmount} x 4`}
            </span>
            <span className="text-zinc-500 dark:text-zinc-400 font-normal">
              {isAr ? 'مع' : 'with'}
            </span>
            <div className="flex items-center gap-1">
              <TabbyBadge />
              <TamaraBadge />
            </div>
            <Info className="w-3 h-3 text-zinc-400 dark:text-zinc-500 group-hover:text-zinc-700 dark:group-hover:text-zinc-300 transition-colors shrink-0" />
          </button>

          {/* ── 3. Desktop HoverCard & Mobile Popup ── */}
          <AnimatePresence>
            {isOpen && (
              <motion.div
                initial={{ opacity: 0, y: 8, scale: 0.96 }}
                animate={{ opacity: 1, y: 0, scale: 1 }}
                exit={{ opacity: 0, y: 6, scale: 0.96 }}
                transition={{ duration: 0.18, ease: 'easeOut' }}
                onMouseLeave={() => setIsOpen(false)}
                className="absolute start-0 md:start-auto md:end-0 mt-2 w-80 sm:w-88 p-5 bg-white dark:bg-zinc-900 rounded-3xl shadow-xl border border-zinc-200 dark:border-zinc-800 z-50 text-start space-y-4"
                role="dialog"
                aria-label="BNPL Details"
              >
                {/* Header */}
                <div className="flex items-start justify-between gap-2">
                  <div>
                    <h4 className="text-sm font-bold text-zinc-900 dark:text-white leading-snug">
                      {isAr
                        ? 'قسّميها على 4 دفعات بدون فوائد'
                        : 'Split into 4 interest-free payments'}
                    </h4>
                    <div className="flex items-center gap-1.5 mt-1">
                      <TabbyBadge />
                      <TamaraBadge />
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      setIsOpen(false);
                    }}
                    className="p-1 text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 rounded-full hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>

                {/* Description */}
                <p className="text-xs text-zinc-500 dark:text-zinc-400 leading-relaxed">
                  {isAr
                    ? `ادفع ${splitAmount} د.إ اليوم، والمتبقي على 3 أشهر. بدون أي فوائد أو رسوم مخفية. اختر Tabby أو Tamara عند الدفع.`
                    : `Pay AED ${splitAmount} today, and the rest over 3 months. Zero interest, zero hidden fees. Select Tabby or Tamara at checkout.`}
                </p>

                {/* Visual 4-Step Timeline */}
                <div className="pt-2">
                  <div className="relative flex items-center justify-between">
                    {/* Connecting Line */}
                    <div className="absolute top-3.5 start-3 end-3 h-0.5 bg-zinc-200 dark:bg-zinc-700 -z-0" />

                    {/* Timeline Nodes */}
                    {[
                      { labelEn: 'Today', labelAr: 'اليوم', active: true },
                      { labelEn: 'Month 1', labelAr: 'الشهر 1', active: false },
                      { labelEn: 'Month 2', labelAr: 'الشهر 2', active: false },
                      { labelEn: 'Month 3', labelAr: 'الشهر 3', active: false },
                    ].map((step, idx) => (
                      <div key={idx} className="relative z-10 flex flex-col items-center text-center">
                        <div
                          className={cn(
                            'w-7 h-7 rounded-full flex items-center justify-center text-[10px] font-bold border transition-all',
                            step.active
                              ? 'bg-zinc-900 dark:bg-white text-white dark:text-zinc-950 border-zinc-900 dark:border-white ring-4 ring-zinc-900/10 dark:ring-white/10'
                              : 'bg-white dark:bg-zinc-800 text-zinc-600 dark:text-zinc-300 border-zinc-300 dark:border-zinc-700'
                          )}
                        >
                          {idx + 1}
                        </div>
                        <span className="text-[10px] font-semibold text-zinc-700 dark:text-zinc-300 mt-1.5">
                          {isAr ? step.labelAr : step.labelEn}
                        </span>
                        <span className="text-[10px] text-zinc-400 font-mono font-medium">
                          AED {numSplit}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Trust Footer */}
                <div className="pt-3 border-t border-zinc-100 dark:border-zinc-800 flex items-center justify-between text-[11px] text-zinc-500 dark:text-zinc-400">
                  <div className="flex items-center gap-1 text-emerald-700 dark:text-emerald-400 font-medium">
                    <ShieldCheck className="w-3.5 h-3.5 text-emerald-600 dark:text-emerald-400" />
                    <span>{isAr ? 'متوافق مع الشريعة' : 'Sharia-compliant'}</span>
                  </div>
                  <span className="text-zinc-400">{isAr ? 'الموافقة فورية' : 'Instant approval'}</span>
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>
    </div>
  );
}

export default BNPLPriceDisplay;
