// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import React, { useEffect, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useIam } from '../context/IamContext';
import { useCommercial } from '../context/CommercialContext';
import { useI18n } from '../context/I18nContext';
import { useModuleRegistry } from '../context/ModuleRegistryContext';

export default function TenantBillingStats() {
  const { cryptographicKey } = useAuth();
  const { identity } = useIam();
  const { tiers, modulePrices, taxRate, activeGateways, activeCurrency, setActiveCurrency, formatDynamicCurrency } = useCommercial();
  const { t } = useI18n();
  
  const [stats, setStats] = useState({
    quota_used: parseInt(localStorage.getItem('tenant_api_quota') || '0', 10),
    quota_limit: 1000000,
    active_rooms: 0,
    total_bandwidth: '0 TB',
    status: 'ACTIVE',
    health: '100%',
    uptime: '99.999%',
    apiLatency: '0ms'
  });

  const [invoices, setInvoices] = useState([]);
  const [purchaseModal, setPurchaseModal] = useState(null);
  const [selectedGateway, setSelectedGateway] = useState('');
  const [localPackages, setLocalPackages] = useState(() => {
    let pkgs = [...(identity?.packages || [])];
    if (pkgs.includes('JUMPA.ID OMNI-ENGINE') || pkgs.includes('phase-1-to-75')) {
      const allMods = Array.from({length: 99}, (_, i) => 'm' + (i + 1));
      pkgs = [...new Set([...pkgs, ...allMods])];
    }
    return pkgs;
  });  
  const [expandedInvoice, setExpandedInvoice] = useState(null);
  const [hoverTooltip, setHoverTooltip] = useState(null);

  const { allModules } = useModuleRegistry();

  const handlePurchase = () => {
      if (!purchaseModal.isDowngrade && !selectedGateway) {
        alert("PILIH PAYMENT GATEWAY DULU!");
        return;
      }
      if (purchaseModal.isDowngrade) {
        if (purchaseModal.modules) { // If it's a tier bundle downgrade
          setLocalPackages(localPackages.filter(p => !purchaseModal.modules.includes(p)));
        } else { // Singular module downgrade
          setLocalPackages(localPackages.filter(p => p !== purchaseModal.id));
        }
      } else {
        if (purchaseModal.modules) { // If it's a tier bundle upgrade
          // Add all missing modules
          const newPackages = new Set([...localPackages, ...purchaseModal.modules]);
          setLocalPackages(Array.from(newPackages));
        } else if (!localPackages.includes(purchaseModal.id)) {
          setLocalPackages([...localPackages, purchaseModal.id]);
        }
      }
      setPurchaseModal(null);
      setSelectedGateway('');
  };

  // Reactive Ping Engine & Quota Tracker
  useEffect(() => {
    // 1. Quota Tracker Listener
    const handleGlobalClick = () => {
      const currentQuota = parseInt(localStorage.getItem('tenant_api_quota') || '0', 10) + 1;
      localStorage.setItem('tenant_api_quota', currentQuota);
      setStats(prev => ({ ...prev, quota_used: currentQuota }));
    };
    document.addEventListener('click', handleGlobalClick);

    // 2. Real-time Latency Ping
    const pingInterval = setInterval(() => {
      const start = performance.now();
      requestAnimationFrame(() => {
        const latency = (performance.now() - start).toFixed(1);
        setStats(prev => ({ ...prev, apiLatency: `${latency}ms` }));
      });
    }, 2000);

    // 3. Dynamic Hardware Metrics Update
    setStats(prev => ({
      ...prev,
      quota_limit: localPackages.length * 50000,
      active_rooms: (navigator.hardwareConcurrency || 4) * localPackages.length * 12,
      total_bandwidth: `${((navigator.hardwareConcurrency || 4) * 0.8 + localPackages.length * 1.2).toFixed(1)} TB`
    }));

    return () => {
      document.removeEventListener('click', handleGlobalClick);
      clearInterval(pingInterval);
    };
  }, [localPackages]);

  // Dynamic Financial Invoice Generator
  useEffect(() => {
    // Menghitung harga pasti sesuai modul yang dimiliki secara realtime
    let baseCurrent = 0;
    localPackages.forEach(modId => {
      baseCurrent += (modulePrices[modId] || 1500000);
    });
    const currentMonthCost = baseCurrent + (baseCurrent * (taxRate / 100));
    
    // Estimasi bulan lalu (mengurangi 2 modul secara acak jika punya > 2)
    let baseLast = baseCurrent;
    if (localPackages.length > 2) {
      baseLast -= (modulePrices[localPackages[0]] || 1500000);
      baseLast -= (modulePrices[localPackages[1]] || 1500000);
    }
    const lastMonthCost = baseLast + (baseLast * (taxRate / 100));
    
    const dateNow = new Date();
    const currentMonth = dateNow.toISOString().slice(0,7);
    dateNow.setMonth(dateNow.getMonth() - 1);
    const lastMonth = dateNow.toISOString().slice(0,7);

    setInvoices([
      { id: `INV-${identity?.username || 'XCU'}-${currentMonth}-A1`, date: `${currentMonth}-01 00:00:00 UTC`, amount: currentMonthCost },
      { id: `INV-${identity?.username || 'XCU'}-${lastMonth}-B7`, date: `${lastMonth}-01 00:00:00 UTC`, amount: lastMonthCost }
    ]);
  }, [localPackages, identity, modulePrices]);

  return (
    <div style={{animation: 'fadeIn 0.6s ease-out'}}>
      {/* Kinetik System Health Bar */}
      <div className="glass-panel" style={{
        padding: '20px', marginBottom: '30px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        background: 'linear-gradient(90deg, rgba(0, 255, 136, 0.05) 0%, rgba(168, 85, 247, 0.05) 100%)',
        borderLeft: '4px solid var(--accent-green)', borderRight: '4px solid var(--accent-purple)'
      }}>
        <div>
          <div style={{color: '#888', fontSize: '0.8rem', letterSpacing: '2px', textTransform: 'uppercase'}}>Omni-Engine Health</div>
          <div style={{color: 'var(--accent-green)', fontSize: '1.8rem', fontWeight: 'bold', fontFamily: 'monospace'}}>OPERATIONAL</div>
        </div>
        <div style={{textAlign: 'right'}}>
          <div style={{color: '#888', fontSize: '0.8rem', letterSpacing: '2px', textTransform: 'uppercase'}}>Global Edge Uptime</div>
          <div style={{color: 'var(--accent-purple)', fontSize: '1.8rem', fontWeight: 'bold', fontFamily: 'monospace'}}>{stats.uptime}</div>
        </div>
        <div style={{textAlign: 'right'}}>
          <div style={{color: '#888', fontSize: '0.8rem', letterSpacing: '2px', textTransform: 'uppercase'}}>Quantum API Latency</div>
          <div style={{color: 'var(--accent-cyan)', fontSize: '1.8rem', fontWeight: 'bold', fontFamily: 'monospace'}}>{stats.apiLatency}</div>
        </div>
      </div>

      <div className="grid-cards" style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: '20px'}}>
        {/* API Quota Card */}
        <div className="glass-panel stat-card" style={{borderColor: 'var(--accent-purple)', position: 'relative', overflow: 'hidden'}}>
          <div style={{position: 'absolute', top: 0, left: 0, height: '2px', background: 'var(--accent-purple)', width: `${(stats.quota_used/stats.quota_limit)*100}%`, transition: 'width 1s ease-out', boxShadow: '0 0 10px var(--accent-purple)'}}></div>
          <div className="stat-title" style={{color: '#fff'}}>Cryptographic API Quota</div>
          <div className="stat-value" style={{color: 'var(--accent-purple)'}}>
            {stats.quota_used.toLocaleString()} <span style={{fontSize: '1rem', color: 'var(--text-muted)'}}>/ {stats.quota_limit.toLocaleString()} req</span>
          </div>
          <div style={{marginTop: '15px', fontSize: '0.85rem', color: 'var(--text-muted)', fontFamily: 'monospace'}}>
            {((stats.quota_used/stats.quota_limit)*100).toFixed(1)}% Consumed
          </div>
        </div>
        
        {/* Network Flow Card */}
        <div className="glass-panel stat-card" style={{borderColor: 'var(--accent-cyan)'}}>
          <div className="stat-title" style={{color: '#fff'}}>Global Network Flow</div>
          <div className="stat-value" style={{color: 'var(--accent-cyan)'}}>{stats.total_bandwidth}</div>
          <div style={{marginTop: '15px', fontSize: '0.85rem', color: 'var(--text-muted)', display: 'flex', justifyContent: 'space-between'}}>
            <span>Active WebRTC QUIC Rooms:</span>
            <span style={{color: 'var(--accent-cyan)', fontWeight: 'bold'}}>{stats.active_rooms}</span>
          </div>
        </div>

        {/* Status Card */}
        <div className="glass-panel stat-card" style={{borderColor: 'var(--accent-green)'}}>
          <div className="stat-title" style={{color: 'var(--text-main)'}}>Account License Matrix</div>
          <div className="stat-value green">{stats.status}</div>
          <div style={{marginTop: '15px', fontSize: '0.85rem', color: 'var(--accent-green)', fontFamily: 'monospace'}}>
            Identity Role: {identity?.role.toUpperCase()}
          </div>
        </div>
      </div>

      {/* Holographic Invoice History */}
      <div className="glass-panel" style={{padding: '30px', marginTop: '30px', borderColor: 'rgba(168, 85, 247, 0.3)', boxShadow: '0 0 40px rgba(168,85,247,0.05)'}}>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px'}}>
          <h3 style={{color: 'var(--text-main)', margin: 0, textTransform: 'uppercase', letterSpacing: '1px'}}>{t('financial_matrix')}</h3>
          <span style={{fontSize: '0.8rem', color: 'var(--text-muted)', fontFamily: 'monospace'}}>Cycle: 01-MAY to 31-MAY</span>
        </div>
        
        <table className="glass-table" style={{width: '100%', textAlign: 'left', borderCollapse: 'collapse'}}>
          <thead>
            <tr style={{borderBottom: '1px solid var(--table-border)'}}>
              <th style={{padding: '15px 10px', color: 'var(--text-muted)', textTransform: 'uppercase', fontSize: '0.8rem'}}>{t('ledger_id')}</th>
              <th style={{padding: '15px 10px', color: 'var(--text-muted)', textTransform: 'uppercase', fontSize: '0.8rem'}}>{t('timestamp')}</th>
              <th style={{padding: '15px 10px', color: 'var(--text-muted)', textTransform: 'uppercase', fontSize: '0.8rem'}}>{t('amount_extracted')}</th>
              <th style={{padding: '15px 10px', color: 'var(--text-muted)', textTransform: 'uppercase', fontSize: '0.8rem'}}>{t('clearance_status')}</th>
            </tr>
          </thead>
          <tbody>
            {invoices.map((inv, idx) => (
              <React.Fragment key={inv.id}>
                <tr 
                  onClick={() => setExpandedInvoice(expandedInvoice === inv.id ? null : inv.id)}
                  style={{
                    borderBottom: expandedInvoice === inv.id ? 'none' : (idx === invoices.length - 1 ? 'none' : '1px solid var(--table-border-light)'), 
                    transition: 'background 0.3s', cursor: 'pointer', background: expandedInvoice === inv.id ? 'var(--hover-bg)' : 'transparent'
                  }}
                  onMouseEnter={(e) => e.currentTarget.style.background = 'var(--hover-bg)'}
                  onMouseLeave={(e) => e.currentTarget.style.background = expandedInvoice === inv.id ? 'var(--hover-bg)' : 'transparent'}
                >
                  <td style={{padding: '15px 10px', color: 'var(--text-muted)', fontFamily: 'monospace'}}>
                    <span style={{display: 'inline-block', width: '20px', color: 'var(--accent-purple)'}}>{expandedInvoice === inv.id ? 'â–¼' : 'â–¶'}</span>
                    {inv.id}
                  </td>
                  <td style={{padding: '15px 10px', color: 'var(--text-main)'}}>{inv.date}</td>
                  <td style={{padding: '15px 10px', color: 'var(--accent-purple)', fontWeight: 'bold', fontFamily: 'monospace'}}>
                    {formatDynamicCurrency(inv.amount)}
                  </td>
                  <td style={{padding: '15px 10px'}}>
                    <span style={{background: 'rgba(0, 255, 136, 0.1)', color: 'var(--accent-green)', padding: '4px 8px', borderRadius: '4px', fontSize: '0.7rem', border: '1px solid var(--accent-green)'}}>{t('cleared_paid')}</span>
                  </td>
                </tr>
                {expandedInvoice === inv.id && (
                  <tr style={{background: 'var(--hover-bg)', borderBottom: idx === invoices.length - 1 ? 'none' : '1px solid var(--table-border-light)'}}>
                    <td colSpan="4" style={{padding: '20px', paddingLeft: '40px'}}>
                      <div style={{borderLeft: '2px solid var(--accent-purple)', paddingLeft: '20px'}}>
                        <div style={{color: 'var(--text-muted)', fontSize: '0.8rem', textTransform: 'uppercase', marginBottom: '15px', letterSpacing: '1px'}}>{t('itemized_receipt')}</div>
                        <div style={{display: 'grid', gridTemplateColumns: '1fr auto', gap: '10px', maxWidth: '600px', fontFamily: 'monospace', fontSize: '0.9rem'}}>
                          {localPackages.map(pkgId => {
                            const modInfo = allModules.find(m => m.id === pkgId);
                            return (
                              <React.Fragment key={pkgId}>
                                <div style={{color: 'var(--text-main)'}}>{modInfo ? modInfo.name : pkgId.toUpperCase()}</div>
                                <div style={{color: 'var(--accent-purple)'}}>{formatDynamicCurrency(modulePrices[pkgId] || 1500000)}</div>
                              </React.Fragment>
                            );
                          })}
                          <div style={{gridColumn: '1 / -1', height: '1px', background: 'var(--table-border)', margin: '10px 0'}}></div>
                          
                          <div style={{color: 'var(--text-muted)'}}>SUBTOTAL</div>
                          <div style={{color: 'var(--text-muted)'}}>{formatDynamicCurrency(inv.amount / (1 + (taxRate/100)))}</div>
                          
                          <div style={{color: 'var(--accent-red)'}}>DYNAMIC TAX RATE ({taxRate}%)</div>
                          <div style={{color: 'var(--accent-red)'}}>+ {formatDynamicCurrency(inv.amount - (inv.amount / (1 + (taxRate/100))))}</div>
                          
                          <div style={{gridColumn: '1 / -1', height: '1px', background: 'var(--table-border)', margin: '10px 0'}}></div>

                          <div style={{color: 'var(--text-main)', fontWeight: 'bold'}}>{t('total_computed')}</div>
                          <div style={{color: 'var(--accent-green)', fontWeight: 'bold'}}>{formatDynamicCurrency(inv.amount)}</div>
                        </div>
                      </div>
                    </td>
                  </tr>
                )}
              </React.Fragment>
            ))}
          </tbody>
        </table>
      </div>

      {/* COMMERCIAL FORGE (OMNI-STORE) */}
      <div style={{marginTop: '50px'}}>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px'}}>
          <div>
            <h2 style={{color: 'var(--text-main)', textTransform: 'uppercase', letterSpacing: '2px', margin: 0}}>{t('commercial_forge')}</h2>
            <p style={{color: 'var(--text-muted)', margin: '5px 0 0 0'}}>{t('commercial_desc')}</p>
          </div>
          
          {/* Currency Switcher */}
          <div style={{display: 'flex', gap: '10px', background: 'var(--panel-bg)', padding: '5px', borderRadius: '8px', border: '1px solid var(--table-border)'}}>
            {['IDR', 'USD', 'BTC'].map(cur => (
              <button 
                key={cur}
                onClick={() => setActiveCurrency(cur)}
                style={{
                  background: activeCurrency === cur ? 'var(--accent-purple)' : 'transparent',
                  color: activeCurrency === cur ? '#fff' : 'var(--text-muted)',
                  border: 'none', padding: '5px 15px', borderRadius: '4px', cursor: 'pointer',
                  fontFamily: 'monospace', fontWeight: 'bold', transition: 'all 0.3s'
                }}
              >
                {cur}
              </button>
            ))}
          </div>
        </div>

        {/* BUNDLE PACKAGES */}
        <h3 style={{color: 'var(--accent-cyan)', textTransform: 'uppercase', letterSpacing: '1px', marginTop: '30px'}}>{t('omni_bundles')}</h3>
        <div className="grid-cards" style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: '20px', marginBottom: '40px'}}>
          {identity?.packages?.includes('JUMPA.ID OMNI-ENGINE') ? (
            <div className="glass-panel" style={{
              padding: '25px', borderColor: 'var(--accent-green)', background: 'rgba(0,255,136,0.1)',
              gridColumn: '1 / -1', textAlign: 'center', boxShadow: '0 0 30px rgba(0, 255, 136, 0.2)'
            }}>
              <h2 style={{color: 'var(--accent-green)', letterSpacing: '2px', textTransform: 'uppercase', margin: '0 0 10px 0'}}>
                {t('omni_locked_title')}
              </h2>
              <h3 style={{color: 'var(--text-main)', margin: '0 0 15px 0'}}>
                {t('omni_locked_active')}<span style={{color: 'var(--accent-purple)'}}>JUMPA.ID OMNI-ENGINE</span>
              </h3>
              <p style={{color: 'var(--text-muted)', maxWidth: '600px', margin: '0 auto'}}>
                {t('omni_locked_desc')}
              </p>
            </div>
          ) : (
            tiers.map(tier => {
              const isOwned = tier.modules.every(m => localPackages.includes(m)) && localPackages.length === tier.modules.length;
              return (
                <div 
                  key={tier.id} 
                  className="glass-panel" 
                  onMouseEnter={() => setHoverTooltip({ title: tier.name, desc: t('includes_modules').replace('{count}', tier.modules.length)})}
                  onMouseLeave={() => setHoverTooltip(null)}
                  style={{
                    padding: '25px', borderColor: isOwned ? 'var(--accent-green)' : '#333', 
                    background: isOwned ? 'rgba(0,255,136,0.05)' : 'transparent',
                    display: 'flex', flexDirection: 'column', position: 'relative'
                  }}
                >
                  <h3 style={{color: isOwned ? 'var(--accent-green)' : 'var(--text-main)', margin: '0 0 10px 0'}}>{tier.name}</h3>
                  <div style={{fontSize: '0.9rem', color: 'var(--text-muted)', marginBottom: '20px', flex: 1}}>{tier.description}</div>
                  <div style={{color: 'var(--accent-purple)', fontSize: '1.5rem', fontWeight: 'bold', fontFamily: 'monospace', marginBottom: '20px'}}>
                    {formatDynamicCurrency(tier.price)}
                  </div>
                  {isOwned ? (
                    <button 
                      onClick={() => setPurchaseModal({...tier, isDowngrade: true})}
                      style={{width: '100%', padding: '10px', background: 'rgba(255,0,60,0.1)', color: 'var(--accent-red)', border: '1px solid var(--accent-red)', borderRadius: '4px', fontFamily: 'monospace', fontWeight: 'bold', cursor: 'pointer', transition: 'all 0.3s'}}
                      onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--accent-red)'; e.currentTarget.style.color = '#fff'; e.currentTarget.innerText = t('purge_bundle'); }}
                      onMouseLeave={(e) => { e.currentTarget.style.background = 'rgba(255,0,60,0.1)'; e.currentTarget.style.color = 'var(--accent-red)'; e.currentTarget.innerText = t('active_bundle'); }}
                    >
                      {t('active_bundle')}
                    </button>
                  ) : (
                    <button 
                      onClick={() => setPurchaseModal(tier)}
                      style={{width: '100%', padding: '10px', background: 'var(--accent-purple)', color: '#fff', border: 'none', borderRadius: '4px', fontFamily: 'monospace', fontWeight: 'bold', cursor: 'pointer'}}
                    >
                      {t('initiate_handshake')}
                    </button>
                  )}
                </div>
              );
            })
          )}
        </div>

        {/* SINGULAR MODULES */}
        <h3 style={{color: 'var(--accent-yellow)', textTransform: 'uppercase', letterSpacing: '1px'}}>{t('singular_modules')}</h3>
        <div style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '15px'}}>
          {allModules.map(mod => {
            const isOwned = localPackages.includes(mod.id);
            const basePrice = modulePrices[mod.id] || 1500000; // Dynamic IDR price per module
            return (
              <div 
                key={mod.id} 
                className="glass-panel" 
                onMouseEnter={() => setHoverTooltip({ title: mod.name, desc: t('core_desc').replace('{id}', mod.id.toUpperCase())})}
                onMouseLeave={() => setHoverTooltip(null)}
                style={{
                  padding: '15px', borderColor: isOwned ? 'var(--accent-green)' : '#222',
                  background: isOwned ? 'rgba(0,255,136,0.05)' : 'transparent',
                  transition: 'all 0.3s', position: 'relative'
                }}
              >
                <div style={{color: 'var(--text-muted)', fontSize: '0.7rem', fontFamily: 'monospace', marginBottom: '5px'}}>{mod.id.toUpperCase()}</div>
                <div style={{color: isOwned ? 'var(--accent-green)' : 'var(--text-main)', fontWeight: 'bold', fontSize: '0.9rem', marginBottom: '10px', height: '40px'}}>{mod.name}</div>
                <div style={{color: 'var(--accent-yellow)', fontFamily: 'monospace', fontSize: '0.9rem', marginBottom: '15px'}}>
                  {formatDynamicCurrency(basePrice)}
                </div>
                {isOwned ? (
                  <button 
                    onClick={() => setPurchaseModal({id: mod.id, name: mod.name, price: basePrice, isDowngrade: true})}
                    style={{width: '100%', padding: '5px', background: 'rgba(255,0,60,0.1)', color: 'var(--accent-red)', border: '1px solid var(--accent-red)', borderRadius: '4px', fontFamily: 'monospace', fontWeight: 'bold', cursor: 'pointer', fontSize: '0.8rem', transition: 'all 0.3s'}}
                    onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--accent-red)'; e.currentTarget.style.color = '#fff'; e.currentTarget.innerText = t('downgrade'); }}
                    onMouseLeave={(e) => { e.currentTarget.style.background = 'rgba(255,0,60,0.1)'; e.currentTarget.style.color = 'var(--accent-red)'; e.currentTarget.innerText = t('installed'); }}
                  >
                    {t('installed')}
                  </button>
                ) : (
                  <button 
                    onClick={() => setPurchaseModal({id: mod.id, name: mod.name, price: basePrice})}
                    style={{width: '100%', background: 'transparent', color: 'var(--accent-cyan)', border: '1px solid var(--accent-cyan)', padding: '5px', borderRadius: '4px', cursor: 'pointer', fontSize: '0.8rem', fontFamily: 'monospace'}}
                  >
                    {t('unlock')}
                  </button>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* Ultra-Detail Tooltip */}
      {hoverTooltip && (
        <div style={{
          position: 'fixed', bottom: '30px', right: '30px', width: '350px',
          background: 'rgba(5, 3, 10, 0.95)', backdropFilter: 'blur(10px)',
          border: '1px solid var(--accent-cyan)', borderRadius: '8px', padding: '20px',
          boxShadow: '0 0 30px rgba(0, 243, 255, 0.2)', zIndex: 9999,
          animation: 'fadeIn 0.2s ease-out', pointerEvents: 'none'
        }}>
          <div style={{color: 'var(--text-main)', fontSize: '1.2rem', fontWeight: 'bold', marginBottom: '10px'}}>{hoverTooltip.title}</div>
          <div style={{color: 'var(--text-muted)', fontSize: '0.9rem', lineHeight: '1.5'}}>{hoverTooltip.desc}</div>
          <div style={{marginTop: '15px', color: 'var(--accent-green)', fontSize: '0.75rem', fontFamily: 'monospace', textTransform: 'uppercase'}}>{t('zero_latency')}</div>
        </div>
      )}

      {/* Holographic Purchase/Downgrade Modal */}
      {purchaseModal && (
        <div style={{
          position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh', 
          background: purchaseModal.isDowngrade ? 'rgba(50,0,0,0.85)' : 'rgba(0,0,0,0.85)', backdropFilter: 'blur(10px)', zIndex: 9999,
          display: 'flex', alignItems: 'center', justifyContent: 'center', animation: 'fadeIn 0.3s ease-out'
        }}>
          <div className="glass-panel" style={{
            width: '100%', maxWidth: '500px', padding: '40px', borderColor: purchaseModal.isDowngrade ? 'var(--accent-red)' : 'var(--accent-cyan)',
            boxShadow: purchaseModal.isDowngrade ? '0 0 50px rgba(255,0,60,0.2)' : '0 0 50px rgba(0, 243, 255, 0.2)', textAlign: 'center',
            background: '#05030a'
          }}>
            <div style={{color: purchaseModal.isDowngrade ? 'var(--accent-red)' : 'var(--text-main)', fontSize: '2rem', marginBottom: '20px'}}>â¬¢</div>
            <h2 style={{color: 'var(--text-main)', textTransform: 'uppercase', letterSpacing: '2px', marginBottom: '10px'}}>
              {purchaseModal.isDowngrade ? t('warning_destructive') : t('crypto_handshake')}
            </h2>
            <p style={{color: 'var(--text-muted)', marginBottom: '30px'}}>
              {purchaseModal.isDowngrade ? (
                <>{t('about_to_purge').replace('module', purchaseModal.name)}</>
              ) : (
                <>{t('about_to_unlock').replace('this module', purchaseModal.name)}</>
              )}
            </p>
            
            <div style={{
              background: 'var(--hover-bg)', padding: '20px', borderRadius: '8px', border: '1px solid var(--table-border)',
              marginBottom: '20px', fontFamily: 'monospace'
            }}>
              <div style={{color: 'var(--text-muted)', marginBottom: '5px'}}>{purchaseModal.isDowngrade ? t('value_removed') : 'SUBTOTAL TRANSAKSI'}</div>
              <div style={{color: purchaseModal.isDowngrade ? 'var(--accent-red)' : 'var(--text-main)', fontSize: '1.2rem', fontWeight: 'bold'}}>{formatDynamicCurrency(purchaseModal.price)}</div>
              
              {!purchaseModal.isDowngrade && (
                <>
                  <div style={{color: 'var(--accent-red)', marginTop: '10px', fontSize: '0.8rem'}}>+ OMNI-TAX ({taxRate}%)</div>
                  <div style={{color: 'var(--accent-red)', fontSize: '0.9rem'}}>{formatDynamicCurrency(purchaseModal.price * (taxRate/100))}</div>
                  
                  <div style={{height: '1px', background: 'var(--table-border)', margin: '15px 0'}}></div>
                  <div style={{color: 'var(--accent-cyan)', fontSize: '0.9rem'}}>TOTAL DITAGIHKAN</div>
                  <div style={{color: 'var(--accent-purple)', fontSize: '1.8rem', fontWeight: 'bold'}}>{formatDynamicCurrency(purchaseModal.price + (purchaseModal.price * (taxRate/100)))}</div>
                </>
              )}
            </div>

            {!purchaseModal.isDowngrade && (
              <div style={{marginBottom: '30px', textAlign: 'left'}}>
                <div style={{color: 'var(--text-muted)', fontSize: '0.8rem', marginBottom: '10px'}}>PILIH METODE PEMBAYARAN (Diizinkan Supreme Admin)</div>
                <div style={{display: 'flex', flexDirection: 'column', gap: '8px', maxHeight: '150px', overflowY: 'auto'}} className="custom-scrollbar">
                  {Object.keys(activeGateways).filter(k => activeGateways[k]).map(gw => (
                    <div 
                      key={gw} 
                      onClick={() => setSelectedGateway(gw)}
                      style={{
                        padding: '10px', border: `1px solid ${selectedGateway === gw ? 'var(--accent-cyan)' : 'var(--table-border)'}`,
                        borderRadius: '4px', background: selectedGateway === gw ? 'rgba(0,243,255,0.1)' : 'var(--bg-panel)',
                        cursor: 'pointer', fontFamily: 'monospace', color: selectedGateway === gw ? 'var(--accent-cyan)' : 'var(--text-main)',
                        transition: 'all 0.2s'
                      }}
                    >
                      {gw.toUpperCase().replace('_', ' ')}
                    </div>
                  ))}
                  {Object.keys(activeGateways).filter(k => activeGateways[k]).length === 0 && (
                    <div style={{color: 'var(--accent-red)', fontFamily: 'monospace'}}>SUPREME ADMIN MEMBLOKIR SEMUA JALUR PEMBAYARAN.</div>
                  )}
                </div>
              </div>
            )}

            <div style={{display: 'flex', gap: '15px'}}>
              <button 
                onClick={() => setPurchaseModal(null)}
                style={{flex: 1, padding: '15px', background: 'transparent', color: 'var(--text-muted)', border: '1px solid var(--table-border)', borderRadius: '4px', cursor: 'pointer', fontFamily: 'monospace'}}
              >
                {t('abort')}
              </button>
              <button 
                onClick={handlePurchase}
                style={{
                  flex: 1, padding: '15px', 
                  background: purchaseModal.isDowngrade ? 'var(--accent-red)' : 'var(--accent-cyan)', 
                  color: purchaseModal.isDowngrade ? '#fff' : '#000', 
                  border: 'none', borderRadius: '4px', cursor: 'pointer', fontFamily: 'monospace', fontWeight: 'bold', 
                  boxShadow: purchaseModal.isDowngrade ? '0 0 15px rgba(255,0,60,0.5)' : '0 0 15px rgba(0,243,255,0.5)'
                }}
              >
                {purchaseModal.isDowngrade ? t('confirm_purge') : t('confirm_injection')}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
