import React, { useState, useEffect, useCallback } from 'react';

// ── Types ──────────────────────────────────────────────────────────────────────
interface SpendRow {
  spend: number; impressions: number; clicks: number;
  ctr: number; cpc: number; purchases: number; roas: number;
}
interface SummaryAll {
  today?: SpendRow | null;
  this_month?: SpendRow | null;
  this_year?: SpendRow | null;
  last_7d?: SpendRow | null;
  last_30d?: SpendRow | null;
}
interface Campaign {
  id: string; name: string; status: string; objective: string;
  spend: number; impressions: number; clicks: number;
  ctr: number; cpc: number; purchases: number; roas: number; cps: number | null;
}
interface AdItem {
  id: string; name: string; status: string; adset_name: string;
  spend: number; impressions: number; clicks: number;
  purchases: number; cps: number | null; roas: number;
  thumbnail: string | null; creative_name: string;
}
type Preset = 'today' | 'last_7d' | 'this_month' | 'last_30d' | 'this_year';

const LS_TOKEN   = 'fb_ads_token';
const LS_ACCOUNT = 'fb_ads_account';
const LS_RATE    = 'fb_exchange_rate';
const API        = '/api/facebook';

const PRESETS: { key: Preset; label: string }[] = [
  { key: 'today',      label: 'আজ' },
  { key: 'last_7d',    label: '৭ দিন' },
  { key: 'this_month', label: 'এই মাস' },
  { key: 'last_30d',   label: '৩০ দিন' },
  { key: 'this_year',  label: 'এই বছর' },
];

const fmt  = (n: number, d = 2) => n.toFixed(d);
const fmtK = (n: number) => n >= 1_000_000 ? `${(n/1_000_000).toFixed(1)}M` : n >= 1_000 ? `${(n/1_000).toFixed(1)}K` : String(n);

function roasBadge(roas?: number | null) {
  if (!roas || roas === 0) return null;
  if (roas >= 10) return { label: '⭐ Excellent', c: '#10b981', bg: 'rgba(16,185,129,0.14)',  br: 'rgba(16,185,129,0.32)' };
  if (roas >= 8)  return { label: '✅ Good',       c: '#4ade80', bg: 'rgba(74,222,128,0.12)',  br: 'rgba(74,222,128,0.28)' };
  if (roas >= 5)  return { label: '⚠️ Average',    c: '#fbbf24', bg: 'rgba(251,191,36,0.12)', br: 'rgba(251,191,36,0.28)' };
  return            { label: '❌ Low ROAS',  c: '#f87171', bg: 'rgba(248,113,113,0.12)', br: 'rgba(248,113,113,0.28)' };
}

/* ─── Shared Styles ─────────────────────────────────────────────────────────── */
const INP: React.CSSProperties = {
  background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)',
  borderRadius: 12, padding: '10px 14px', color: '#f1f5f9', fontSize: 13,
  outline: 'none', width: '100%', fontFamily: 'inherit', boxSizing: 'border-box',
};
const PILL = (active: boolean): React.CSSProperties => ({
  padding: '6px 13px', borderRadius: 9, border: 'none', cursor: 'pointer', fontSize: 11,
  fontWeight: 800, transition: 'all 0.2s',
  background: active ? 'rgba(99,102,241,0.9)' : 'transparent',
  color: active ? '#fff' : 'rgba(199,210,254,0.55)',
});

/* ─── Stat Card ─────────────────────────────────────────────────────────────── */
function KPI({ icon, label, value, sub, color, bg, border }: {
  icon: string; label: string; value: string; sub: string;
  color: string; bg: string; border: string;
}) {
  return (
    <div style={{ background: bg, border: `1px solid ${border}`, borderRadius: 18, padding: '16px 18px' }}>
      <p style={{ margin: '0 0 8px', fontSize: 10, fontWeight: 800, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.6px' }}>{icon} {label}</p>
      <p style={{ margin: '0 0 4px', fontSize: 22, fontWeight: 900, color, lineHeight: 1 }}>{value}</p>
      <p style={{ margin: 0, fontSize: 11, color: '#64748b' }}>{sub}</p>
    </div>
  );
}

/* ─── Section wrapper ────────────────────────────────────────────────────────── */
function Section({ title, border = 'rgba(99,102,241,0.18)', children }: {
  title: React.ReactNode; border?: string; children: React.ReactNode;
}) {
  return (
    <div style={{ background: '#0f172a', border: `1px solid ${border}`, borderRadius: 22, padding: '22px 24px', marginBottom: 18 }}>
      <h3 style={{ margin: '0 0 16px', fontSize: 14, fontWeight: 900, color: '#e2e8f0', display: 'flex', alignItems: 'center', gap: 8 }}>{title}</h3>
      {children}
    </div>
  );
}

/* ─── Empty / Skeleton ───────────────────────────────────────────────────────── */
function EmptyBox({ msg }: { msg: string }) {
  return (
    <div style={{ textAlign: 'center', padding: '36px 20px', color: '#334155' }}>
      <div style={{ fontSize: 36, marginBottom: 10, opacity: 0.5 }}>📭</div>
      <p style={{ margin: 0, fontSize: 13, fontWeight: 600 }}>{msg}</p>
    </div>
  );
}

/* ══════════════════════════════════════════════════════════════════════════════
   Main Component
══════════════════════════════════════════════════════════════════════════════ */
export default function FacebookAdsPanel({
  showToast,
}: { products?: any[]; showToast: (m: string, t?: 'success' | 'error') => void }) {

  /* credentials */
  const [token,   setToken]   = useState(localStorage.getItem(LS_TOKEN)   || '');
  const [account, setAccount] = useState(localStorage.getItem(LS_ACCOUNT) || '');
  const [rate,    setRate]    = useState(parseFloat(localStorage.getItem(LS_RATE) || '110'));
  const [connected,    setConnected]    = useState(!!localStorage.getItem(LS_TOKEN));
  const [accountName,  setAccountName]  = useState('');
  const [showSetup,    setShowSetup]    = useState(!localStorage.getItem(LS_TOKEN));
  const [showTokenRaw, setShowTokenRaw] = useState(false);
  const [verifying,    setVerifying]    = useState(false);

  /* data */
  const [summary,   setSummary]   = useState<SummaryAll>({});
  const [campaigns, setCampaigns] = useState<Campaign[]>([]);
  const [ads,       setAds]       = useState<AdItem[]>([]);

  /* ui */
  const [preset,      setPreset]      = useState<Preset>('today');
  const [loading,     setLoading]     = useState(false);
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const [tab,         setTab]         = useState<'campaigns' | 'ads'>('campaigns');

  const bdt = parseFloat(localStorage.getItem(LS_RATE) || String(rate)) || 110;

  /* ── fetch ─────────────────────────────────────────────────────────────── */
  const fetchAll = useCallback(async (p: Preset) => {
    const t = localStorage.getItem(LS_TOKEN);
    const a = localStorage.getItem(LS_ACCOUNT);
    if (!t || !a) return;
    setLoading(true);
    try {
      const [sumR, camR, adsR] = await Promise.all([
        fetch(`${API}/summary?token=${encodeURIComponent(t)}&account=${encodeURIComponent(a)}&date_preset=${p}`).then(r => r.json()),
        fetch(`${API}/campaigns?token=${encodeURIComponent(t)}&account=${encodeURIComponent(a)}&date_preset=${p}`).then(r => r.json()),
        fetch(`${API}/top-ads?token=${encodeURIComponent(t)}&account=${encodeURIComponent(a)}&date_preset=${p}`).then(r => r.json()),
      ]);
      if (sumR.success) {
        setSummary(sumR.data);
        // ── Cache the current preset's metrics so AdminDashboard overview can read them ──
        const pData = (sumR.data as any)[p];
        const rate = parseFloat(localStorage.getItem(LS_RATE) || '110');
        if (pData && pData.spend !== undefined) {
          localStorage.setItem('fb_ads_summary_cache', JSON.stringify({
            spend_usd:   pData.spend || 0,
            spend_bdt:   Math.round((pData.spend || 0) * rate),
            purchases:   pData.purchases || 0,
            roas:        pData.roas || 0,
            clicks:      pData.clicks || 0,
            impressions: pData.impressions || 0,
            ctr:         pData.ctr || 0,
            cpc:         pData.cpc || 0,
            rate,
            preset:      p,
            updatedAt:   Date.now(),
          }));
          window.dispatchEvent(new Event('fb_ads_cache_updated'));
        }
      }
      if (camR.success) setCampaigns(camR.data);
      if (adsR.success) setAds(adsR.data);
      setLastUpdated(new Date());
    } catch { showToast('ডেটা লোড করতে সমস্যা।', 'error'); }
    setLoading(false);
  }, []);

  useEffect(() => {
    if (connected) fetchAll(preset);
  }, [preset, connected]);

  /* ── connect ───────────────────────────────────────────────────────────── */
  const handleConnect = async () => {
    if (!token || !account) { showToast('Token ও Account ID দিন।', 'error'); return; }
    setVerifying(true);
    try {
      const r = await fetch(`${API}/verify?token=${encodeURIComponent(token)}&account=${encodeURIComponent(account)}`);
      const d = await r.json();
      if (d.success) {
        localStorage.setItem(LS_TOKEN,   token);
        localStorage.setItem(LS_ACCOUNT, account);
        localStorage.setItem(LS_RATE,    String(rate));
        setAccountName(d.account_name || account);
        setConnected(true);
        setShowSetup(false);
        showToast('✅ সংযুক্ত! ডেটা লোড হচ্ছে...', 'success');
      } else {
        showToast('❌ ' + (d.error || 'Invalid credentials'), 'error');
      }
    } catch { showToast('সংযোগ ব্যর্থ।', 'error'); }
    setVerifying(false);
  };

  const disconnect = () => {
    ['fb_ads_token','fb_ads_account'].forEach(k => localStorage.removeItem(k));
    setConnected(false); setShowSetup(true);
    setSummary({}); setCampaigns([]); setAds([]);
  };

  const cur = summary[preset];

  /* ════════════════════════════════════════════════════════════════════════
     RENDER
  ════════════════════════════════════════════════════════════════════════ */
  return (
    <div style={{ fontFamily: "'Inter','Hind Siliguri',sans-serif", paddingBottom: 48 }}>

      {/* ── TOP HEADER BAR ─────────────────────────────────────────────────── */}
      <div style={{
        background: 'linear-gradient(135deg,#1e1b4b 0%,#312e81 60%,#1e3a8a 100%)',
        borderRadius: 24, padding: '18px 22px', marginBottom: 18,
        border: '1px solid rgba(99,102,241,0.25)', boxShadow: '0 16px 48px rgba(79,70,229,0.2)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
          <div style={{ width: 44, height: 44, borderRadius: 14, background: 'linear-gradient(135deg,#1877f2,#0d5bbd)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, boxShadow: '0 6px 18px rgba(24,119,242,0.4)' }}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="white"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
          </div>
          <div>
            <h2 style={{ margin: 0, fontSize: 16, fontWeight: 900, color: '#fff' }}>Facebook Ads Dashboard</h2>
            <p style={{ margin: '2px 0 0', fontSize: 11, color: 'rgba(199,210,254,0.65)' }}>
              {connected ? `${accountName || localStorage.getItem(LS_ACCOUNT)} · $1=৳${bdt}` : 'সংযুক্ত নয় — নিচে setup করুন'}
              {lastUpdated && ` · ${lastUpdated.toLocaleTimeString('bn-BD')}`}
            </p>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          {connected && (
            <>
              <div style={{ display: 'flex', background: 'rgba(0,0,0,0.28)', borderRadius: 12, padding: 3, gap: 1 }}>
                {PRESETS.map(({ key, label }) => (
                  <button key={key} onClick={() => setPreset(key)} style={PILL(preset === key)}>{label}</button>
                ))}
              </div>
              <button onClick={() => fetchAll(preset)} disabled={loading}
                style={{ background: 'rgba(99,102,241,0.25)', border: '1px solid rgba(99,102,241,0.4)', borderRadius: 10, padding: '7px 14px', color: '#c7d2fe', fontSize: 11, fontWeight: 700, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5 }}>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" style={{ animation: loading ? 'fbSpin 1s linear infinite' : 'none' }}><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
                {loading ? '...' : 'Refresh'}
              </button>
              <button onClick={() => setShowSetup(s => !s)} style={{ background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 10, padding: '7px 12px', color: '#94a3b8', fontSize: 11, fontWeight: 700, cursor: 'pointer' }}>
                ⚙️ Settings
              </button>
              <button onClick={disconnect} style={{ background: 'rgba(248,113,113,0.1)', border: '1px solid rgba(248,113,113,0.2)', borderRadius: 10, padding: '7px 12px', color: '#f87171', fontSize: 11, fontWeight: 700, cursor: 'pointer' }}>
                ⏏ Disconnect
              </button>
            </>
          )}
          {!connected && (
            <button onClick={() => setShowSetup(s => !s)} style={{ background: 'linear-gradient(135deg,#6366f1,#4f46e5)', border: 'none', borderRadius: 12, padding: '9px 18px', color: '#fff', fontSize: 12, fontWeight: 800, cursor: 'pointer', boxShadow: '0 6px 18px rgba(99,102,241,0.4)' }}>
              🔗 Connect করুন
            </button>
          )}
        </div>
      </div>

      {/* ── SETUP PANEL (collapsible) ───────────────────────────────────────── */}
      {showSetup && (
        <div style={{ background: '#0f172a', border: '1px solid rgba(99,102,241,0.25)', borderRadius: 22, padding: '22px 24px', marginBottom: 18 }}>
          <p style={{ margin: '0 0 16px', fontSize: 13, fontWeight: 900, color: '#c7d2fe', display: 'flex', alignItems: 'center', gap: 8 }}>
            🔐 Facebook Ads API সংযুক্ত করুন
          </p>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(220px,1fr))', gap: 14 }}>
            <div>
              <label style={{ fontSize: 10, fontWeight: 800, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.5px', display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                <span>Access Token</span>
                <a href="https://developers.facebook.com/tools/explorer/" target="_blank" rel="noopener noreferrer" style={{ color: '#818cf8', fontWeight: 600 }}>→ পাবেন কোথায়?</a>
              </label>
              <div style={{ position: 'relative' }}>
                <input style={INP} type={showTokenRaw ? 'text' : 'password'} placeholder="EAAB…" value={token} onChange={e => setToken(e.target.value)} />
                <button onClick={() => setShowTokenRaw(s => !s)} style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', color: '#475569', cursor: 'pointer', fontSize: 13 }}>
                  {showTokenRaw ? '🙈' : '👁'}
                </button>
              </div>
              <p style={{ margin: '4px 0 0', fontSize: 10, color: '#334155' }}>Business Manager → System Users → Generate Token (ads_read)</p>
            </div>
            <div>
              <label style={{ fontSize: 10, fontWeight: 800, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.5px', display: 'block', marginBottom: 6 }}>Ad Account ID</label>
              <input style={INP} placeholder="act_1234567890 বা শুধু নম্বর" value={account} onChange={e => setAccount(e.target.value)} />
              <p style={{ margin: '4px 0 0', fontSize: 10, color: '#334155' }}>Business Manager → Ad Accounts</p>
            </div>
            <div>
              <label style={{ fontSize: 10, fontWeight: 800, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.5px', display: 'block', marginBottom: 6 }}>Dollar Rate (৳)</label>
              <input style={INP} type="number" placeholder="110" value={rate} onChange={e => setRate(parseFloat(e.target.value) || 110)} />
            </div>
          </div>
          <button onClick={handleConnect} disabled={verifying || !token || !account}
            style={{ marginTop: 16, background: verifying ? 'rgba(99,102,241,0.45)' : 'linear-gradient(135deg,#6366f1,#4f46e5)', border: 'none', borderRadius: 14, padding: '12px 28px', color: '#fff', fontSize: 13, fontWeight: 900, cursor: verifying ? 'wait' : 'pointer', boxShadow: '0 8px 24px rgba(99,102,241,0.3)', transition: 'all 0.25s' }}>
            {verifying ? '⏳ যাচাই হচ্ছে...' : '🔗 Connect করুন'}
          </button>
        </div>
      )}

      {/* ── MULTI-PERIOD SPEND STRIP ───────────────────────────────────────── */}
      <div style={{ display: 'flex', gap: 10, marginBottom: 18, flexWrap: 'wrap' }}>
        {PRESETS.map(({ key, label }) => {
          const d = summary[key];
          const active = preset === key;
          return (
            <div key={key} onClick={() => connected && setPreset(key)} style={{ flex: 1, minWidth: 110, background: active ? 'rgba(99,102,241,0.14)' : 'rgba(255,255,255,0.03)', border: `1px solid ${active ? 'rgba(99,102,241,0.35)' : 'rgba(255,255,255,0.06)'}`, borderRadius: 16, padding: '14px 16px', cursor: connected ? 'pointer' : 'default', transition: 'all 0.2s' }}>
              <p style={{ margin: '0 0 6px', fontSize: 10, fontWeight: 700, color: '#64748b', textTransform: 'uppercase' }}>{label}</p>
              <p style={{ margin: '0 0 3px', fontSize: 20, fontWeight: 900, color: active ? '#818cf8' : (d ? '#f1f5f9' : '#334155') }}>{d ? `$${fmt(d.spend)}` : connected ? '—' : '···'}</p>
              {d ? <p style={{ margin: 0, fontSize: 11, color: '#475569' }}>≈ ৳{Math.round((d.spend || 0) * bdt).toLocaleString()}</p> : null}
              {d && (d.purchases || 0) > 0 ? <p style={{ margin: '3px 0 0', fontSize: 11, fontWeight: 700, color: '#4ade80' }}>{d.purchases} sales · ROAS {fmt(d.roas || 0,1)}x</p> : null}
              {!d && connected && !loading && <p style={{ margin: 0, fontSize: 10, color: '#334155' }}>No data</p>}
              {!connected && <p style={{ margin: 0, fontSize: 10, color: '#334155' }}>Not connected</p>}
            </div>
          );
        })}
      </div>

      {/* ── KPI CARDS ──────────────────────────────────────────────────────── */}
      {loading && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(145px,1fr))', gap: 12, marginBottom: 18 }}>
          {[1,2,3,4,5].map(i => <div key={i} style={{ background: '#1e293b', borderRadius: 18, height: 90, animation: `fbPulse 1.5s ease-in-out ${i*0.1}s infinite` }} />)}
        </div>
      )}

      {!loading && cur && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(145px,1fr))', gap: 12, marginBottom: 18 }}>
          <KPI icon="💸" label="Spend" value={`$${fmt(cur.spend)}`} sub={`≈ ৳${Math.round(cur.spend*bdt).toLocaleString()}`} color="#f87171" bg="rgba(248,113,113,0.1)" border="rgba(248,113,113,0.2)" />
          <KPI icon="🛍" label="Purchases" value={String(cur.purchases || 0)} sub={cur.purchases>0 ? `$${fmt(cur.spend/cur.purchases)}/sale` : 'No sales'} color="#4ade80" bg="rgba(74,222,128,0.1)" border="rgba(74,222,128,0.2)" />
          <KPI icon="📈" label="ROAS" value={cur.roas > 0 ? `${fmt(cur.roas,1)}x` : '—'} sub={roasBadge(cur.roas)?.label || 'N/A'} color={roasBadge(cur.roas)?.c || '#64748b'} bg={roasBadge(cur.roas)?.bg || 'rgba(255,255,255,0.04)'} border={roasBadge(cur.roas)?.br || 'rgba(255,255,255,0.08)'} />
          <KPI icon="👁" label="Impressions" value={fmtK(cur.impressions)} sub={`CTR ${fmt(cur.ctr)}%`} color="#818cf8" bg="rgba(129,140,248,0.1)" border="rgba(129,140,248,0.2)" />
          <KPI icon="🖱" label="Clicks" value={fmtK(cur.clicks)} sub={`CPC $${fmt(cur.cpc)}`} color="#38bdf8" bg="rgba(56,189,248,0.1)" border="rgba(56,189,248,0.2)" />
        </div>
      )}

      {!connected && !loading && (
        <div style={{ background: 'rgba(99,102,241,0.06)', border: '1px dashed rgba(99,102,241,0.25)', borderRadius: 20, padding: '28px', marginBottom: 18, textAlign: 'center' }}>
          <p style={{ margin: '0 0 4px', fontSize: 28 }}>📡</p>
          <p style={{ margin: '0 0 8px', fontSize: 15, fontWeight: 800, color: '#818cf8' }}>Facebook Ads সংযুক্ত করুন</p>
          <p style={{ margin: 0, fontSize: 13, color: '#475569' }}>উপরে "Connect করুন" বাটনে click করে Access Token ও Account ID দিন।</p>
        </div>
      )}

      {/* ── TAB SELECTOR ───────────────────────────────────────────────────── */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 16, background: 'rgba(255,255,255,0.04)', borderRadius: 14, padding: 4, width: 'fit-content' }}>
        {([['campaigns','📦 Campaigns'],['ads','🏆 Top Ads']] as const).map(([k,l]) => (
          <button key={k} onClick={() => setTab(k)} style={{ padding: '9px 20px', borderRadius: 10, border: 'none', cursor: 'pointer', fontSize: 12, fontWeight: 800, transition: 'all 0.2s', background: tab === k ? 'linear-gradient(135deg,#6366f1,#4f46e5)' : 'transparent', color: tab === k ? '#fff' : '#64748b', boxShadow: tab === k ? '0 4px 12px rgba(99,102,241,0.3)' : 'none' }}>
            {l}
          </button>
        ))}
      </div>

      {/* ── CAMPAIGNS TABLE ─────────────────────────────────────────────────── */}
      {tab === 'campaigns' && (
        <Section title={<><span>📦</span> Campaign Breakdown — {campaigns.length} টি Campaign</>}>
          {!connected ? <EmptyBox msg="Connect করলে campaign data দেখা যাবে" /> :
           loading     ? <EmptyBox msg="লোড হচ্ছে..." /> :
           campaigns.length === 0 ? <EmptyBox msg="এই সময়ের জন্য কোনো campaign নেই" /> : (
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                <thead>
                  <tr>
                    {['Campaign', 'Status', 'Spend', 'Purchases', 'CPS', 'ROAS', 'Clicks', 'CTR'].map(h => (
                      <th key={h} style={{ padding: '8px 12px', textAlign: 'left', fontSize: 10, fontWeight: 800, color: '#475569', textTransform: 'uppercase', letterSpacing: '0.5px', borderBottom: '1px solid rgba(255,255,255,0.06)', whiteSpace: 'nowrap' }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {campaigns.map((c, i) => {
                    const b = roasBadge(c.roas);
                    return (
                      <tr key={c.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.04)', background: i%2===0 ? 'rgba(255,255,255,0.01)' : 'transparent' }}>
                        <td style={{ padding: '11px 12px', maxWidth: 220 }}>
                          <div style={{ color: '#e2e8f0', fontWeight: 700, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 210 }}>{c.name}</div>
                          <div style={{ fontSize: 10, color: '#475569', marginTop: 1 }}>{c.objective}</div>
                        </td>
                        <td style={{ padding: '11px 12px' }}>
                          <span style={{ fontSize: 10, fontWeight: 800, padding: '3px 7px', borderRadius: 6, background: c.status==='ACTIVE' ? 'rgba(74,222,128,0.14)' : 'rgba(100,116,139,0.1)', color: c.status==='ACTIVE' ? '#4ade80' : '#64748b' }}>{c.status}</span>
                        </td>
                        <td style={{ padding: '11px 12px' }}>
                          <div style={{ fontWeight: 800, color: '#f87171' }}>${fmt(c.spend)}</div>
                          <div style={{ fontSize: 10, color: '#475569' }}>৳{Math.round(c.spend*bdt).toLocaleString()}</div>
                        </td>
                        <td style={{ padding: '11px 12px', fontWeight: 800, color: '#4ade80', textAlign: 'center' }}>{c.purchases||'—'}</td>
                        <td style={{ padding: '11px 12px', fontWeight: 700, color: c.cps!==null && c.cps<2 ? '#4ade80' : '#e2e8f0' }}>{c.cps!==null ? `$${c.cps}` : '—'}</td>
                        <td style={{ padding: '11px 12px' }}>
                          {b ? <div style={{ display:'flex', alignItems:'center', gap:5 }}>
                            <span style={{ fontSize: 14, fontWeight: 900, color: b.c }}>{fmt(c.roas,1)}x</span>
                            <span style={{ fontSize: 10, padding: '2px 7px', borderRadius: 6, background: b.bg, color: b.c, border: `1px solid ${b.br}`, fontWeight: 700, whiteSpace: 'nowrap' }}>{b.label}</span>
                          </div> : '—'}
                        </td>
                        <td style={{ padding: '11px 12px', color: '#94a3b8' }}>{fmtK(c.clicks)}</td>
                        <td style={{ padding: '11px 12px', color: '#94a3b8' }}>{fmt(c.ctr)}%</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </Section>
      )}

      {/* ── TOP ADS ─────────────────────────────────────────────────────────── */}
      {tab === 'ads' && (
        <Section title={<><span>🏆</span> Top Performing Ads (সবচেয়ে কম Cost per Sale)</>} border="rgba(16,185,129,0.2)">
          {!connected ? <EmptyBox msg="Connect করলে ads data দেখা যাবে" /> :
           loading     ? <EmptyBox msg="লোড হচ্ছে..." /> :
           ads.length === 0 ? <EmptyBox msg="এই সময়ের জন্য কোনো active ads নেই" /> : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {ads.map((ad, i) => {
                const b = roasBadge(ad.roas);
                const first = i === 0;
                return (
                  <div key={ad.id} style={{ background: first ? 'rgba(16,185,129,0.07)' : 'rgba(255,255,255,0.02)', border: `1px solid ${first ? 'rgba(16,185,129,0.24)' : 'rgba(255,255,255,0.06)'}`, borderRadius: 16, padding: '13px 16px', display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                    {/* rank */}
                    <div style={{ width: 32, height: 32, borderRadius: 10, background: first ? 'rgba(16,185,129,0.18)' : 'rgba(99,102,241,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: first ? 16 : 12, fontWeight: 900, color: first ? '#4ade80' : '#818cf8', flexShrink: 0 }}>
                      {first ? '🏆' : `#${i+1}`}
                    </div>
                    {/* thumb */}
                    {ad.thumbnail
                      ? <img src={ad.thumbnail} alt="" style={{ width: 44, height: 44, borderRadius: 10, objectFit: 'cover', flexShrink: 0, border: '1px solid rgba(255,255,255,0.08)' }} />
                      : <div style={{ width: 44, height: 44, borderRadius: 10, background: 'rgba(99,102,241,0.1)', border: '1px solid rgba(99,102,241,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, flexShrink: 0 }}>🖼</div>
                    }
                    {/* info */}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <p style={{ margin: '0 0 3px', fontSize: 13, fontWeight: 800, color: '#e2e8f0', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ad.name}</p>
                      <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                        <span style={{ fontSize: 10, color: '#475569' }}>{ad.adset_name}</span>
                        <span style={{ fontSize: 10, padding: '2px 6px', borderRadius: 5, background: ad.status==='ACTIVE' ? 'rgba(74,222,128,0.12)' : 'rgba(100,116,139,0.1)', color: ad.status==='ACTIVE' ? '#4ade80' : '#64748b', fontWeight: 700 }}>{ad.status}</span>
                      </div>
                    </div>
                    {/* metrics */}
                    <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', flexShrink: 0, alignItems: 'center' }}>
                      {[
                        { l: 'Spend',   v: `$${fmt(ad.spend)}`,                  s: `৳${Math.round(ad.spend*bdt).toLocaleString()}`, c: '#f87171' },
                        { l: 'Sales',   v: String(ad.purchases || '—'),           s: `${fmtK(ad.clicks)} clicks`,                     c: '#4ade80' },
                        { l: 'CPS',     v: ad.cps!==null ? `$${ad.cps}` : '—',  s: 'cost/sale',                                      c: ad.cps!==null && ad.cps<2 ? '#4ade80' : '#fbbf24' },
                        { l: 'Impressions', v: fmtK(ad.impressions), s: `CTR —`, c: '#818cf8' },
                      ].map(m => (
                        <div key={m.l} style={{ textAlign: 'center', minWidth: 50 }}>
                          <p style={{ margin: '0 0 1px', fontSize: 14, fontWeight: 900, color: m.c, lineHeight: 1 }}>{m.v}</p>
                          <p style={{ margin: 0, fontSize: 9, color: '#475569', textTransform: 'uppercase', fontWeight: 700 }}>{m.l}</p>
                          <p style={{ margin: 0, fontSize: 9, color: '#334155' }}>{m.s}</p>
                        </div>
                      ))}
                      {b && (
                        <div style={{ background: b.bg, border: `1px solid ${b.br}`, borderRadius: 10, padding: '6px 12px', textAlign: 'center' }}>
                          <p style={{ margin: '0 0 1px', fontSize: 15, fontWeight: 900, color: b.c, lineHeight: 1 }}>{fmt(ad.roas,1)}x</p>
                          <p style={{ margin: 0, fontSize: 9, fontWeight: 800, color: b.c, textTransform: 'uppercase' }}>ROAS</p>
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </Section>
      )}

      {/* ── ROAS GUIDE ──────────────────────────────────────────────────────── */}
      <Section title={<><span>⚡</span> Optimization Guide</>} border="rgba(245,158,11,0.18)">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(190px,1fr))', gap: 10 }}>
          {[
            { r: 'ROAS ≥ 10x', l: '⭐ Excellent', d: 'Budget দ্বিগুণ করুন!',         c:'#10b981', bg:'rgba(16,185,129,0.08)',  br:'rgba(16,185,129,0.2)'  },
            { r: 'ROAS 8–10x', l: '✅ Good',       d: 'ধীরে Scale করুন',              c:'#4ade80', bg:'rgba(74,222,128,0.08)', br:'rgba(74,222,128,0.2)' },
            { r: 'ROAS 5–8x',  l: '⚠️ Average',   d: 'Creative বা Audience বদলান',  c:'#fbbf24', bg:'rgba(251,191,36,0.08)',  br:'rgba(251,191,36,0.2)'  },
            { r: 'ROAS < 5x',  l: '❌ Low',        d: 'Ad বন্ধ করুন, নতুন test করুন', c:'#f87171', bg:'rgba(248,113,113,0.08)', br:'rgba(248,113,113,0.2)' },
          ].map(g => (
            <div key={g.r} style={{ background: g.bg, border: `1px solid ${g.br}`, borderRadius: 14, padding: '13px 15px' }}>
              <p style={{ margin: '0 0 3px', fontSize: 11, fontWeight: 900, color: g.c }}>{g.r}</p>
              <p style={{ margin: '0 0 5px', fontSize: 13, fontWeight: 900, color: '#e2e8f0' }}>{g.l}</p>
              <p style={{ margin: 0, fontSize: 11, color: '#64748b' }}>{g.d}</p>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 14, display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(160px,1fr))', gap: 8 }}>
          <p style={{ gridColumn: '1/-1', margin: '0 0 8px', fontSize: 11, fontWeight: 800, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.5px' }}>🎯 Cost Per Sale Target</p>
          {[['৳৫০০','$0.50'],['৳১,০০০','$1.00'],['৳১,৫০০','$1.50'],['৳২,০০০','$2.00'],['৳৩,০০০','$3.00']].map(([p,t]) => (
            <div key={p} style={{ background: 'rgba(99,102,241,0.07)', border: '1px solid rgba(99,102,241,0.14)', borderRadius: 12, padding: '10px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: '#94a3b8' }}>{p}</span>
              <span style={{ fontSize: 15, fontWeight: 900, color: '#4ade80' }}>{t}</span>
            </div>
          ))}
        </div>
      </Section>

      <style>{`
        @keyframes fbSpin  { to { transform: rotate(360deg); } }
        @keyframes fbPulse { 0%,100% { opacity:.35 } 50% { opacity:.7 } }
      `}</style>
    </div>
  );
}
