import React, { useState, useEffect, useMemo } from 'react';
import {
  X,
  Upload,
  Trophy,
  ArrowRight,
  ShieldCheck,
  CheckCircle2,
  AlertCircle,
  Loader2,
  Sparkles,
  Smartphone,
  CreditCard,
  Building2
} from 'lucide-react';
import { useApp } from '../context/AppContext';
import { isValidFacebookUrl, isValidWebsiteUrl, normalizeUrl, normalizeFacebookUrl } from '../utils/urlValidation';

export const OutbidModal: React.FC = () => {
  const {
    state,
    categories,
    listings,
    rankedListings,
    settings,
    texts,
    gateways,
    t,
    tCategory,
    tNum,
    closeOutbidModal,
    processOutbidPayment,
  } = useApp();

  const target = state.liveListingTarget;
  const currentBid = target ? target.current_bid : settings.initial_minimum_bid;
  const minNextBid = target ? currentBid + settings.minimum_bid_increment : settings.initial_minimum_bid;

  // Form State
  const [name, setName] = useState('');
  const [facebookUrl, setFacebookUrl] = useState('');
  const [websiteUrl, setWebsiteUrl] = useState('');
  const [categoryId, setCategoryId] = useState('cat_biz');
  const [imageUrl, setImageUrl] = useState('https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=200&auto=format&fit=crop&q=80');
  const [bidAmount, setBidAmount] = useState<number | string>(minNextBid);
  // Active enabled gateways list
  const activeGateways = useMemo(() => {
    const enabledList = gateways.filter(g => g.is_enabled);
    if (enabledList.length > 0) return enabledList;
    return gateways;
  }, [gateways]);

  const [selectedGateway, setSelectedGateway] = useState<'bkash' | 'nagad' | 'rocket' | 'sslcommerz' | 'shurjopay' | 'aamarpay'>(() => {
    if (settings.default_payment_gateway && gateways.some(g => g.id === settings.default_payment_gateway && g.is_enabled)) {
      return settings.default_payment_gateway;
    }
    return (gateways.find(g => g.is_enabled)?.id as any) || 'bkash';
  });
  
  // Submission & Payment Step State
  const [isProcessing, setIsProcessing] = useState(false);
  const [paymentStep, setPaymentStep] = useState<'form' | 'gateway_sim' | 'success' | 'failed'>('form');
  const [statusMessage, setStatusMessage] = useState('');
  const [txnResult, setTxnResult] = useState<string>('');
  const [errorMessage, setErrorMessage] = useState('');

  // Preset Avatar suggestions for convenience
  const avatarPresets = [
    'https://images.unsplash.com/photo-1542838132-92c53300491e?w=200&auto=format&fit=crop&q=80',
    'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=200&auto=format&fit=crop&q=80',
    'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200&auto=format&fit=crop&q=80',
    'https://images.unsplash.com/photo-1526367790999-0150786686a2?w=200&auto=format&fit=crop&q=80',
    'https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=200&auto=format&fit=crop&q=80',
  ];

  // Auto-fill default bid amount when modal opens, leaving name/url ready for new bidder
  useEffect(() => {
    setName('');
    setFacebookUrl('');
    setWebsiteUrl('');
    setCategoryId(target?.category_id || categories.find(c => c.slug !== 'all')?.id || 'cat_biz');
    setImageUrl('https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=200&auto=format&fit=crop&q=80');

    const nextBid = target ? target.current_bid + settings.minimum_bid_increment : settings.initial_minimum_bid;
    setBidAmount(nextBid);
    setPaymentStep('form');
    setErrorMessage('');

    // Pre-select default enabled gateway
    const preferred = settings.default_payment_gateway;
    if (preferred && gateways.some(g => g.id === preferred && g.is_enabled)) {
      setSelectedGateway(preferred);
    } else {
      const firstEnabled = gateways.find(g => g.is_enabled);
      if (firstEnabled) setSelectedGateway(firstEnabled.id as any);
    }
  }, [target, state.isOutbidModalOpen, categories, settings.minimum_bid_increment, settings.initial_minimum_bid, settings.default_payment_gateway, gateways]);

  // Parse entered numeric bid amount
  const parsedBidAmount = typeof bidAmount === 'number' ? bidAmount : (Number(bidAmount) || 0);
  const isBidBelowMin = parsedBidAmount < minNextBid;
  const targetName = target ? target.name : (t('hero_leader_label', undefined, 'current leader'));

  // Live Position Calculation based on the exact ranking rules:
  // 1. Higher current_bid -> higher rank
  // 2. Same current_bid -> older listing first (all existing listings with same bid rank ahead of this new bid)
  // 3. Newer same-amount bids go below older same-amount bids
  const projectedRank = useMemo(() => {
    const enteredBid = parsedBidAmount;
    if (enteredBid <= 0) return (rankedListings?.length || 0) + 1;

    const activeListings = listings.filter(item => item.is_active);

    // Count existing active listings that rank ahead:
    // - Listings with higher bid (current_bid > enteredBid)
    // - Listings with equal bid (current_bid === enteredBid) are older, so they rank ahead of this new bid
    const aheadCount = activeListings.filter(item => item.current_bid >= enteredBid).length;
    return aheadCount + 1;
  }, [parsedBidAmount, listings, rankedListings]);

  if (!state.isOutbidModalOpen) return null;

  const handleImageFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 3 * 1024 * 1024) {
        setErrorMessage('Image file must be under 3MB');
        return;
      }
      
      // Set instant local preview
      const previewUrl = URL.createObjectURL(file);
      setImageUrl(previewUrl);

      // Attempt upload to hosting server upload endpoint
      try {
        const formData = new FormData();
        formData.append('image', file);
        const res = await fetch('/api/upload.php', {
          method: 'POST',
          body: formData,
        });
        if (res.ok) {
          const data = await res.json();
          if (data.success && data.image_url) {
            setImageUrl(data.image_url);
            return;
          }
        }
      } catch {
        // Fallback for static client preview: read as persistent data URL
        const reader = new FileReader();
        reader.onloadend = () => {
          if (typeof reader.result === 'string') {
            setImageUrl(reader.result);
          }
        };
        reader.readAsDataURL(file);
      }
    }
  };

  const handleFormSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage('');

    if (!name.trim()) {
      setErrorMessage('Please enter a business, product, or personal name.');
      return;
    }

    const normalizedFb = normalizeFacebookUrl(facebookUrl);
    const normalizedWeb = websiteUrl.trim() ? normalizeUrl(websiteUrl) : '';

    if (!normalizedFb) {
      setErrorMessage('Please enter your Facebook Page or Profile URL.');
      return;
    }

    if (!isValidFacebookUrl(normalizedFb)) {
      setErrorMessage('Please enter a valid Facebook page or profile URL (e.g., facebook.com/yourpage).');
      return;
    }

    if (normalizedWeb && !isValidWebsiteUrl(normalizedWeb)) {
      setErrorMessage('Please enter a valid website URL (e.g., toolyfie.com or https://yourwebsite.com).');
      return;
    }

    if (parsedBidAmount < minNextBid) {
      setErrorMessage(`Bid amount must be at least ${settings.currency_symbol}${minNextBid.toLocaleString()}.`);
      return;
    }

    // Move to payment verification
    setIsProcessing(true);
    setPaymentStep('gateway_sim');
    setStatusMessage(`Connecting securely to ${selectedGateway.toUpperCase()} verification server...`);

    try {
      const result = await processOutbidPayment({
        targetListingId: target?.id,
        name: name.trim(),
        facebook_url: normalizedFb,
        website_url: normalizedWeb,
        url: normalizedWeb || normalizedFb,
        imageUrl: imageUrl,
        categoryId: categoryId,
        bidAmount: parsedBidAmount,
        additionalAmount: Math.max(0, parsedBidAmount - minNextBid),
        gateway: selectedGateway,
      });

      if (result.success) {
        setTxnResult(result.transactionId || 'TXN-OK');
        setStatusMessage(result.message);
        setPaymentStep('success');
      } else {
        setErrorMessage(result.message);
        setPaymentStep('failed');
      }
    } catch (err: any) {
      setErrorMessage(err.message || 'Payment verification failed.');
      setPaymentStep('failed');
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <div
      id="outbid-modal-backdrop"
      className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 md:p-6 bg-black/80 backdrop-blur-sm animate-in fade-in duration-150"
      onClick={closeOutbidModal}
    >
      <div
        id="outbid-modal-dialog"
        onClick={(e) => e.stopPropagation()}
        className="w-full max-w-lg rounded-2xl border shadow-2xl overflow-hidden text-left flex flex-col max-h-[92dvh] sm:max-h-[88dvh] relative transform transition-all duration-200"
        style={{
          backgroundColor: 'var(--card-color, #13181D)',
          borderColor: 'var(--border-color, #2A3440)'
        }}
      >
        {/* Modal Header */}
        <div
          className="px-4 sm:px-5 py-3.5 sm:py-4 border-b flex items-center justify-between shrink-0"
          style={{
            backgroundColor: 'var(--sub-card-bg, #0E1317)',
            borderColor: 'var(--border-color, #222A33)'
          }}
        >
          <div className="flex items-center gap-2">
            <Trophy className="w-5 h-5 text-amber-400 shrink-0" />
            <h2
              className="font-bold text-base sm:text-lg truncate"
              style={{ color: 'var(--heading-color, #FFFFFF)' }}
            >
              {target ? t('outbid_modal_title', undefined, 'Outbid Listing') : t('claim_spot_modal_title', undefined, 'Claim Live Spot')}
            </h2>
          </div>
          <button
            onClick={closeOutbidModal}
            disabled={isProcessing}
            className="p-1.5 rounded-lg text-slate-400 hover:text-slate-200 dark:hover:text-white cursor-pointer shrink-0 transition-colors"
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        {/* STEP 1: FORM */}
        {paymentStep === 'form' && (
          <form onSubmit={handleFormSubmit} className="p-3.5 sm:p-5 space-y-3.5 sm:space-y-4 overflow-y-auto flex-1 overscroll-contain touch-pan-y">
            {/* Target Details Header Block with Editable Min Next Bid Input & Live Projected Rank */}
            <div
              className="p-3 sm:p-3.5 rounded-xl border space-y-3"
              style={{
                backgroundColor: 'var(--sub-card-bg, #0A0D0F)',
                borderColor: 'var(--border-color, #222A33)'
              }}
            >
              <div className="flex flex-col sm:grid sm:grid-cols-2 gap-2.5 sm:gap-3 sm:items-center">
                {/* Target Name */}
                <div className="min-w-0">
                  <div
                    className="text-[10px] uppercase font-bold tracking-wider"
                    style={{ color: 'var(--muted-text-color, #8A99A8)' }}
                  >
                    {t('modal_target_label', undefined, texts.modal_target_label || 'TARGET')}:
                  </div>
                  <div
                    className="text-sm font-bold truncate"
                    style={{ color: 'var(--heading-color, #FFFFFF)' }}
                  >
                    {target ? target.name : t('claim_hero_title_prefix', undefined, '#1 Leaderboard Spot')}
                  </div>
                </div>

                {/* Current Bid */}
                <div
                  className="text-left sm:text-right sm:border-l sm:pl-3"
                  style={{ borderColor: 'var(--border-color, #222A33)' }}
                >
                  <div
                    className="text-[10px] uppercase font-bold tracking-wider"
                    style={{ color: 'var(--muted-text-color, #8A99A8)' }}
                  >
                    {t('current_bid_label', undefined, texts.current_bid_label || 'CURRENT BID')}:
                  </div>
                  <div
                    className="text-sm font-mono font-bold whitespace-nowrap"
                    style={{ color: 'var(--heading-color, #FFFFFF)' }}
                  >
                    {settings.currency_symbol}{tNum(currentBid)}
                  </div>
                </div>
              </div>

              {/* Editable Min Next Bid Input & Live Projected Position */}
              <div
                className="pt-2.5 border-t space-y-2"
                style={{ borderColor: 'var(--border-color, #222A33)' }}
              >
                <div className="flex items-center justify-between gap-3">
                  <div className="min-w-0">
                    <label htmlFor="modal-bid-amount-input" className="block text-[11px] uppercase font-bold tracking-wider text-emerald-500">
                      {t('next_bid_label', undefined, texts.next_bid_label || 'MIN NEXT BID')}:
                    </label>
                    <span
                      className="text-[10px] block truncate"
                      style={{ color: 'var(--muted-text-color, #8A99A8)' }}
                    >
                      {t('required_to_outbid', { amount: `${settings.currency_symbol}${tNum(minNextBid)}` }, `Required to outbid: ${settings.currency_symbol}${minNextBid.toLocaleString()}`)}
                    </span>
                  </div>
                  <div className="relative w-36 sm:w-44 shrink-0">
                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-emerald-500 font-mono font-bold text-sm">
                      {settings.currency_symbol}
                    </span>
                    <input
                      id="modal-bid-amount-input"
                      type="number"
                      step="1"
                      value={bidAmount}
                      onChange={e => setBidAmount(e.target.value)}
                      className={`w-full pl-7 pr-3 py-1.5 sm:py-2 border rounded-lg text-sm sm:text-base font-mono font-bold text-right focus:outline-none focus:ring-1 transition-colors ${
                        isBidBelowMin
                          ? 'border-amber-500/80 focus:border-amber-400 focus:ring-amber-400'
                          : 'border-emerald-500/60 focus:border-emerald-400 focus:ring-emerald-400'
                      }`}
                      style={{
                        backgroundColor: 'var(--input-bg, #13181D)',
                        color: 'var(--heading-color, #FFFFFF)'
                      }}
                      placeholder={minNextBid.toString()}
                      required
                    />
                  </div>
                </div>

                {/* Dynamic Live Notification: Warning if below minimum OR Projected Rank if sufficient */}
                {isBidBelowMin ? (
                  <div className="flex items-center justify-between px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 text-xs animate-in fade-in text-amber-700 dark:text-amber-300">
                    <span className="font-medium flex items-center gap-1.5">
                      <AlertCircle className="w-3.5 h-3.5 text-amber-500 shrink-0" />
                      <span>{t('bid_below_min_warning', { amount: `${settings.currency_symbol}${tNum(minNextBid)}`, target: targetName }, `${settings.currency_symbol}${minNextBid.toLocaleString()} is required to outbid ${targetName}`)}</span>
                    </span>
                  </div>
                ) : (
                  <div className="flex items-center justify-between px-3 py-2 rounded-lg bg-emerald-500/10 border border-emerald-500/30 text-xs animate-in fade-in">
                    <span
                      className="font-medium flex items-center gap-1.5"
                      style={{ color: 'var(--muted-text-color, #8A99A8)' }}
                    >
                      <Trophy className="w-3.5 h-3.5 text-amber-400 shrink-0" />
                      <span>{t('live_placement_label', undefined, 'Live Placement:')}</span>
                    </span>
                    <span className="font-bold text-emerald-500 font-mono text-xs sm:text-sm">
                      {t('position_will_be', { rank: tNum(projectedRank) }, `Your position will be #${projectedRank}`)}
                    </span>
                  </div>
                )}
              </div>
            </div>

            {/* Field 1: 1:1 Profile Image */}
            <div className="space-y-1.5">
              <label
                className="block text-xs font-semibold"
                style={{ color: 'var(--heading-color, #FFFFFF)' }}
              >
                {t('field_avatar_label', undefined, '1. Profile Avatar (1:1 Square)')}
              </label>
              <div className="flex items-center gap-3">
                <img
                  src={imageUrl}
                  alt="Preview"
                  className="w-12 h-12 sm:w-14 sm:h-14 rounded-xl object-cover border shadow-sm shrink-0"
                  style={{
                    borderColor: 'var(--border-color, #222A33)',
                    backgroundColor: 'var(--sub-card-bg, #0A0D0F)'
                  }}
                />
                <div className="flex-1 space-y-1.5 min-w-0">
                  <label
                    className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg border text-xs font-medium cursor-pointer transition-colors"
                    style={{
                      backgroundColor: 'var(--sub-card-bg, #182028)',
                      borderColor: 'var(--border-color, #2A3744)',
                      color: 'var(--text-color, #F0F4F8)'
                    }}
                  >
                    <Upload className="w-3.5 h-3.5 text-emerald-500 shrink-0" />
                    <span>{t('upload_image_btn', undefined, 'Upload Image')}</span>
                    <input
                      type="file"
                      accept="image/png, image/jpeg, image/webp"
                      onChange={handleImageFileChange}
                      className="hidden"
                    />
                  </label>
                  <div className="flex items-center gap-1.5 flex-wrap">
                    <span
                      className="text-[10px]"
                      style={{ color: 'var(--muted-text-color, #8A99A8)' }}
                    >
                      {t('presets_label', undefined, 'Presets:')}
                    </span>
                    {avatarPresets.map((p, i) => (
                      <button
                        type="button"
                        key={i}
                        onClick={() => setImageUrl(p)}
                        className="w-5 h-5 rounded-md overflow-hidden border hover:border-emerald-500 shrink-0 cursor-pointer"
                        style={{ borderColor: 'var(--border-color, #222A33)' }}
                      >
                        <img src={p} alt={`preset ${i}`} className="w-full h-full object-cover" />
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* Field 2: Name */}
            <div className="space-y-1">
              <label
                className="block text-xs font-semibold"
                style={{ color: 'var(--heading-color, #FFFFFF)' }}
              >
                {t('field_name_label', undefined, '2. Name')}
              </label>
              <input
                type="text"
                required
                value={name}
                onChange={e => setName(e.target.value)}
                placeholder={t('modal_name_placeholder', undefined, texts.modal_name_placeholder || 'Business, product or personal name')}
                className="w-full px-3.5 py-2 border focus:border-emerald-500 rounded-xl text-sm placeholder-slate-500 focus:outline-none transition-colors"
                style={{
                  backgroundColor: 'var(--input-bg, #0A0D0F)',
                  borderColor: 'var(--border-color, #222A33)',
                  color: 'var(--heading-color, #FFFFFF)'
                }}
              />
            </div>

            {/* Field 3A: Facebook Page or Profile URL (Required) */}
            <div className="space-y-1">
              <label
                className="block text-xs font-semibold"
                style={{ color: 'var(--heading-color, #FFFFFF)' }}
              >
                Facebook Page or Profile URL <span className="text-emerald-500">*</span>
              </label>
              <input
                type="text"
                required
                value={facebookUrl}
                onChange={e => setFacebookUrl(e.target.value)}
                placeholder="Enter your Facebook page or profile URL"
                className="w-full px-3.5 py-2 border focus:border-emerald-500 rounded-xl text-sm placeholder-slate-500 focus:outline-none transition-colors"
                style={{
                  backgroundColor: 'var(--input-bg, #0A0D0F)',
                  borderColor: 'var(--border-color, #222A33)',
                  color: 'var(--heading-color, #FFFFFF)'
                }}
              />
            </div>

            {/* Field 3B: Website URL (Optional) */}
            <div className="space-y-1">
              <label
                className="block text-xs font-semibold"
                style={{ color: 'var(--heading-color, #FFFFFF)' }}
              >
                Website URL <span className="text-slate-400 font-normal">(Optional)</span>
              </label>
              <input
                type="text"
                value={websiteUrl}
                onChange={e => setWebsiteUrl(e.target.value)}
                placeholder="Enter your website URL (Optional)"
                className="w-full px-3.5 py-2 border focus:border-emerald-500 rounded-xl text-sm placeholder-slate-500 focus:outline-none transition-colors"
                style={{
                  backgroundColor: 'var(--input-bg, #0A0D0F)',
                  borderColor: 'var(--border-color, #222A33)',
                  color: 'var(--heading-color, #FFFFFF)'
                }}
              />
              <span
                className="text-[10px] block"
                style={{ color: 'var(--muted-text-color, #8A99A8)' }}
              >
                {t('url_update_hint', undefined, 'If this profile or website already exists, its ranking will be updated without creating a duplicate.')}
              </span>
            </div>

            {/* Field 4: Category Dropdown */}
            <div className="space-y-1">
              <label
                className="block text-xs font-semibold"
                style={{ color: 'var(--heading-color, #FFFFFF)' }}
              >
                {t('field_category_label', undefined, '4. Category')}
              </label>
              <select
                value={categoryId}
                onChange={e => setCategoryId(e.target.value)}
                className="w-full px-3.5 py-2 border focus:border-emerald-500 rounded-xl text-sm focus:outline-none cursor-pointer"
                style={{
                  backgroundColor: 'var(--input-bg, #0A0D0F)',
                  borderColor: 'var(--border-color, #222A33)',
                  color: 'var(--heading-color, #FFFFFF)'
                }}
              >
                {categories
                  .filter(c => c.slug !== 'all' && c.is_active)
                  .map(cat => (
                    <option key={cat.id} value={cat.id}>
                      {tCategory(cat.slug || cat.id, cat.name)}
                    </option>
                  ))}
              </select>
            </div>

            {/* Total Final Bid Amount Summary */}
            <div
              className="p-3 rounded-xl border flex items-center justify-between"
              style={{
                backgroundColor: 'var(--sub-card-bg, #0F1419)',
                borderColor: 'var(--border-color, #222A33)'
              }}
            >
              <span
                className="text-xs font-bold"
                style={{ color: 'var(--heading-color, #FFFFFF)' }}
              >
                {t('total_bid_amount_label', undefined, 'Total Final Bid Amount:')}
              </span>
              <span className="text-base sm:text-lg font-black font-mono text-emerald-500 whitespace-nowrap">
                {settings.currency_symbol}{tNum(parsedBidAmount)}
              </span>
            </div>

            {/* Payment Method Selector */}
            <div className="space-y-1.5">
              <div className="flex items-center justify-between">
                <label
                  className="block text-xs font-semibold"
                  style={{ color: 'var(--heading-color, #FFFFFF)' }}
                >
                  {t('payment_method_label', undefined, texts.payment_method_label || 'Select Payment Gateway')}
                </label>
                <span className="text-[10px] text-emerald-500 font-mono flex items-center gap-1">
                  <ShieldCheck className="w-3 h-3" /> Sandbox / Live Active
                </span>
              </div>

              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-1.5 sm:gap-2">
                {activeGateways.map(gw => {
                  const isSelected = selectedGateway === gw.id;
                  const isTestMode = gw.mode === 'test';
                  return (
                    <button
                      type="button"
                      key={gw.id}
                      onClick={() => setSelectedGateway(gw.id as any)}
                      className={`p-2 rounded-xl border text-center font-bold text-xs transition-all cursor-pointer relative ${
                        isSelected
                          ? 'bg-emerald-600 text-white border-emerald-500 shadow-md'
                          : 'hover:opacity-90'
                      }`}
                      style={
                        isSelected
                          ? {}
                          : {
                              backgroundColor: 'var(--sub-card-bg, #0A0D0F)',
                              borderColor: 'var(--border-color, #222A33)',
                              color: 'var(--muted-text-color, #8A99A8)'
                            }
                      }
                    >
                      <div className="font-mono text-[11px] truncate capitalize">
                        {gw.name?.split(' ')[0] || gw.id}
                      </div>
                      <div className="text-[9px] opacity-75 font-mono">
                        {isTestMode ? 'TEST' : 'LIVE'}
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Error Display */}
            {errorMessage && (
              <div className="p-3 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-600 dark:text-rose-300 text-xs flex items-center gap-2">
                <AlertCircle className="w-4 h-4 shrink-0" />
                <span>{errorMessage}</span>
              </div>
            )}

            {/* Submit / Proceed to Pay Button */}
            <button
              type="submit"
              className="w-full py-3 px-4 rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-white font-bold text-sm sm:text-base shadow-lg shadow-emerald-950/40 flex items-center justify-center gap-2 transition-all cursor-pointer"
            >
              <span>{t('pay_claim_btn', { amount: `${settings.currency_symbol}${tNum(parsedBidAmount)}` }, `Pay ${settings.currency_symbol}${parsedBidAmount.toLocaleString()} & Claim Spot`)}</span>
              <ArrowRight className="w-4 h-4 shrink-0" />
            </button>
          </form>
        )}

        {/* STEP 2: GATEWAY SIMULATION & VERIFICATION */}
        {paymentStep === 'gateway_sim' && (
          <div className="p-8 text-center space-y-5">
            <div className="w-16 h-16 rounded-2xl bg-emerald-500/20 border border-emerald-500/40 flex items-center justify-center mx-auto text-emerald-500 shadow-xl">
              <Loader2 className="w-8 h-8 animate-spin" />
            </div>
            <div className="space-y-1.5">
              <h3
                className="text-lg font-bold"
                style={{ color: 'var(--heading-color, #FFFFFF)' }}
              >
                {t('verifying_txn_title', { gateway: selectedGateway.toUpperCase() }, `Verifying Transaction with ${selectedGateway.toUpperCase()}`)}
              </h3>
              <p
                className="text-xs max-w-sm mx-auto"
                style={{ color: 'var(--muted-text-color, #8A99A8)' }}
              >
                {statusMessage}
              </p>
            </div>
            <div
              className="p-3.5 rounded-xl border max-w-xs mx-auto text-xs space-y-1 font-mono"
              style={{
                backgroundColor: 'var(--sub-card-bg, #0A0D0F)',
                borderColor: 'var(--border-color, #222A33)',
                color: 'var(--text-color, #F0F4F8)'
              }}
            >
              <div className="flex justify-between">
                <span style={{ color: 'var(--muted-text-color, #8A99A8)' }}>Amount:</span>
                <span className="text-emerald-500 font-bold">{settings.currency_symbol}{tNum(parsedBidAmount)}</span>
              </div>
              <div className="flex justify-between">
                <span style={{ color: 'var(--muted-text-color, #8A99A8)' }}>Gateway:</span>
                <span style={{ color: 'var(--heading-color, #FFFFFF)' }}>{selectedGateway.toUpperCase()}</span>
              </div>
              <div className="flex justify-between">
                <span style={{ color: 'var(--muted-text-color, #8A99A8)' }}>Verification:</span>
                <span className="text-amber-500">Server-Side Active</span>
              </div>
            </div>
          </div>
        )}

        {/* STEP 3: SUCCESS & RANK RECALCULATED */}
        {paymentStep === 'success' && (
          <div className="p-8 text-center space-y-5">
            <div className="w-16 h-16 rounded-2xl bg-emerald-500/20 border border-emerald-500/50 flex items-center justify-center mx-auto text-emerald-500 shadow-xl">
              <CheckCircle2 className="w-9 h-9" />
            </div>
            <div className="space-y-1.5">
              <h3
                className="text-xl font-black font-mono"
                style={{ color: 'var(--heading-color, #FFFFFF)' }}
              >
                {t('outbid_success_title', undefined, 'Outbid Successful!')}
              </h3>
              <p
                className="text-xs max-w-md mx-auto"
                style={{ color: 'var(--muted-text-color, #8A99A8)' }}
              >
                {statusMessage}
              </p>
            </div>
            <div
              className="p-3.5 rounded-xl border max-w-xs mx-auto text-xs space-y-1 font-mono text-left"
              style={{
                backgroundColor: 'var(--sub-card-bg, #0A0D0F)',
                borderColor: 'var(--border-color, #222A33)',
                color: 'var(--text-color, #F0F4F8)'
              }}
            >
              <div className="flex justify-between">
                <span style={{ color: 'var(--muted-text-color, #8A99A8)' }}>Txn ID:</span>
                <span style={{ color: 'var(--heading-color, #FFFFFF)' }}>{txnResult}</span>
              </div>
              <div className="flex justify-between">
                <span style={{ color: 'var(--muted-text-color, #8A99A8)' }}>Status:</span>
                <span className="text-emerald-500 font-bold">VERIFIED & LIVE</span>
              </div>
            </div>
            <button
              onClick={closeOutbidModal}
              className="px-6 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-sm shadow-md cursor-pointer"
            >
              {t('view_leaderboard_btn', undefined, 'View Leaderboard')}
            </button>
          </div>
        )}

        {/* STEP 4: FAILURE STATE */}
        {paymentStep === 'failed' && (
          <div className="p-8 text-center space-y-5">
            <div className="w-16 h-16 rounded-2xl bg-rose-500/20 border border-rose-500/40 flex items-center justify-center mx-auto text-rose-500">
              <AlertCircle className="w-8 h-8" />
            </div>
            <div className="space-y-1.5">
              <h3
                className="text-lg font-bold"
                style={{ color: 'var(--heading-color, #FFFFFF)' }}
              >
                {t('payment_unverified_title', undefined, 'Payment Unverified')}
              </h3>
              <p className="text-xs text-rose-500 max-w-sm mx-auto">{errorMessage || 'Could not verify transaction with payment server.'}</p>
            </div>
            <div className="flex items-center justify-center gap-3">
              <button
                onClick={() => setPaymentStep('form')}
                className="px-4 py-2 rounded-xl bg-slate-700 hover:bg-slate-600 text-white text-xs font-semibold cursor-pointer"
              >
                {t('try_again_btn', undefined, 'Try Again')}
              </button>
              <button
                onClick={closeOutbidModal}
                className="px-4 py-2 rounded-xl bg-rose-600 hover:bg-rose-500 text-white text-xs font-semibold cursor-pointer"
              >
                {t('close_btn', undefined, 'Close')}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

