'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Crown } from 'lucide-react';
import { usePlanFeatures } from '@client/contexts/PlanFeaturesContext';
import { useLanguage } from '@client/contexts/LanguageContext';

interface FeatureGuardProps {
  feature: string;
  featureName?: string;
  children: React.ReactNode;
}

function LockedPlaceholder() {
  return (
    <div className="p-6 space-y-5" aria-hidden="true">
      <div className="flex items-center gap-3">
        <div className="h-8 w-8 rounded-lg bg-gray-200" />
        <div className="h-6 w-40 rounded bg-gray-200" />
        <div className="ml-auto h-9 w-28 rounded-lg bg-gray-200" />
      </div>
      <div className="h-4 w-72 rounded bg-gray-200" />
      <div className="rounded-xl border border-gray-100 bg-gray-50 p-4 space-y-3">
        <div className="h-5 w-1/3 rounded bg-gray-200" />
        <div className="h-4 w-full rounded bg-gray-200" />
        <div className="h-4 w-5/6 rounded bg-gray-200" />
        <div className="h-4 w-4/6 rounded bg-gray-200" />
      </div>
      <div className="rounded-xl border border-gray-100 bg-gray-50 p-4 space-y-3">
        <div className="h-5 w-1/4 rounded bg-gray-200" />
        <div className="h-4 w-full rounded bg-gray-200" />
        <div className="h-4 w-3/4 rounded bg-gray-200" />
      </div>
      <div className="rounded-xl border border-gray-100 bg-gray-50 p-4 space-y-3">
        <div className="h-5 w-1/2 rounded bg-gray-200" />
        <div className="h-4 w-full rounded bg-gray-200" />
        <div className="h-4 w-2/3 rounded bg-gray-200" />
        <div className="h-4 w-3/4 rounded bg-gray-200" />
      </div>
    </div>
  );
}

export default function FeatureGuard({ feature, featureName, children }: FeatureGuardProps) {
  const { hasFeature, loading } = usePlanFeatures();
  const { t } = useLanguage();
  const allowed = hasFeature(feature);

  // Phase 1: wait 1.5 s before mounting the overlay card at all.
  const [overlayMounted, setOverlayMounted] = useState(false);
  // Phase 2: one rAF after mount, flip to opacity:1 so CSS transition runs.
  const [overlayOpaque, setOverlayOpaque] = useState(false);

  useEffect(() => {
    if (loading || allowed) {
      setOverlayMounted(false);
      setOverlayOpaque(false);
      return;
    }
    const mountTimer = setTimeout(() => {
      setOverlayMounted(true);
    }, 1500);
    return () => clearTimeout(mountTimer);
  }, [loading, allowed]);

  useEffect(() => {
    if (!overlayMounted) {
      setOverlayOpaque(false);
      return;
    }
    const raf = requestAnimationFrame(() => setOverlayOpaque(true));
    return () => cancelAnimationFrame(raf);
  }, [overlayMounted]);

  // Show the blurred skeleton while plan data is loading so the page isn't
  // a blank white flash — the overlay will appear once loading resolves.
  if (loading) {
    return (
      <div className="relative w-full min-h-[60vh] overflow-hidden">
        <div className="pointer-events-none select-none animate-pulse" style={{ opacity: 0.35 }}>
          <LockedPlaceholder />
        </div>
      </div>
    );
  }

  if (!allowed) {
    const label = featureName ?? t('featureGuard.thisFeature', 'This feature');
    return (
      <div className="relative w-full min-h-[60vh] overflow-hidden">
        {/* Blurred skeleton backdrop — visible for ~1.5 s before card appears */}
        <div
          className="pointer-events-none select-none"
          style={{ filter: 'blur(6px)', opacity: 0.45 }}
        >
          <LockedPlaceholder />
        </div>

        {/* Upgrade card — conditionally mounted after delay, fades in via CSS transition */}
        {overlayMounted && (
          <div
            className="absolute inset-0 flex items-center justify-center z-10"
            style={{
              opacity: overlayOpaque ? 1 : 0,
              transition: 'opacity 0.4s ease',
            }}
          >
            <div
              className="bg-white rounded-2xl shadow-2xl p-8 flex flex-col items-center text-center max-w-sm w-full mx-4"
              style={{ border: '1px solid hsl(var(--border))' }}
            >
              {/* Crown icon */}
              <div
                className="w-16 h-16 rounded-full flex items-center justify-center mb-5"
                style={{ backgroundColor: '#FEF3C7' }}
              >
                <Crown size={28} style={{ color: '#D97706' }} />
              </div>

              {/* Heading */}
              <h2 className="text-xl font-bold mb-2" style={{ color: 'hsl(var(--foreground))' }}>
                {t('featureGuard.heading', 'Upgrade Your Plan')}
              </h2>

              {/* Description */}
              <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {t(
                  'featureGuard.description',
                  `${label} is not included in your current plan. Upgrade to unlock it.`,
                  { feature: label }
                )}
              </p>

              {/* CTA */}
              <Link
                href="/billing"
                className="inline-flex items-center justify-center rounded-lg px-6 py-2.5 text-sm font-semibold text-white bg-orange-500 hover:bg-orange-600 transition-colors"
              >
                {t('featureGuard.cta', 'Upgrade Now')}
              </Link>
            </div>
          </div>
        )}
      </div>
    );
  }

  return <>{children}</>;
}
