/* Admin - Advertising (ad banner performance, Meta Ads Manager style). */

const AD_NAME_OVERRIDES = {
  'product-banner': 'Predict & Win (Internal)',
};

function prettyBannerName(src) {
  if (!src) return 'Unknown banner';
  const file = src.split('/').pop() || src;
  const base = file.replace(/\.[a-z0-9]+$/i, '');
  const key = base.replace(/-mobile$/i, '');
  if (AD_NAME_OVERRIDES[key]) return AD_NAME_OVERRIDES[key];
  return base
    .replace(/-mobile$/i, '')
    .split(/[-_]/)
    .filter(Boolean)
    .map(w => w.charAt(0).toUpperCase() + w.slice(1))
    .join(' ');
}

function ctr(clicks, impressions) {
  if (!impressions) return 0;
  return (clicks / impressions) * 100;
}

function AdminAdvertising({ ctx }) {
  const [data, setData] = useState(null);
  const [error, setError] = useState('');
  const [materialDevice, setMaterialDevice] = useState('all'); // 'all' | 'Desktop' | 'Mobile'

  useEffect(() => {
    let active = true;
    fetch('/api/get-ad-stats', { headers: { 'x-admin-key': ctx.adminToken } })
      .then(r => r.json())
      .then(d => {
        if (!active) return;
        if (d.totals) { setData(d); setError(''); }
        else { setError(d.error || 'Could not load ad stats.'); }
      })
      .catch(() => { if (active) setError('Network error while loading ad stats.'); });
    return () => { active = false; };
  }, [ctx.adminToken]);

  if (error) {
    return (
      <AdminSection title="Advertising" sub="Ad banner performance across the campaign site.">
        <Panel><div style={{ color: '#b91c1c', fontSize: 13 }}>{error}</div></Panel>
      </AdminSection>
    );
  }

  if (!data) {
    return (
      <AdminSection title="Advertising" sub="Ad banner performance across the campaign site.">
        <Panel><div style={{ color: 'var(--grey-500)', fontSize: 13 }}>Loading ad stats…</div></Panel>
      </AdminSection>
    );
  }

  const { totals, banners, daily, totalEvents } = data;
  const totalImpressions = totals.desktop.impressions + totals.mobile.impressions;
  const totalClicks = totals.desktop.clicks + totals.mobile.clicks;
  const overallCtr = ctr(totalClicks, totalImpressions);

  const rows = [];
  for (const b of banners) {
    if (b.desktop.impressions || b.desktop.clicks) rows.push({ banner: b.banner, device: 'Desktop', ...b.desktop });
    if (b.mobile.impressions || b.mobile.clicks) rows.push({ banner: b.banner, device: 'Mobile', ...b.mobile });
  }
  rows.sort((a, b) => b.impressions - a.impressions);

  const dailyPeak = Math.max(1, ...daily.map(d => d.impressions));

  const materials = [
    ...(window.SPONSOR_ADS || []).map(src => ({ src, device: 'Desktop', link: window.getAdLink ? window.getAdLink(src) : null })),
    ...(window.MOBILE_SPONSOR_ADS || []).map(src => ({ src, device: 'Mobile', link: window.getAdLink ? window.getAdLink(src) : null })),
  ];
  const filteredMaterials = materialDevice === 'all' ? materials : materials.filter(m => m.device === materialDevice);

  return (
    <AdminSection
      title="Advertising"
      sub={`Ad banner performance · ${totalEvents.toLocaleString()} tracked events`}
    >
      <div className="admin-stat-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(130px, 1fr))', gap: 14, marginBottom: 18 }}>
        <StatCard label="Impressions" value={totalImpressions.toLocaleString()} accent="ink" />
        <StatCard label="Clicks" value={totalClicks.toLocaleString()} accent="orange" />
        <StatCard label="Overall CTR" value={`${overallCtr.toFixed(2)}%`} accent="green" />
        <StatCard label="Tracked banners" value={banners.length.toLocaleString()} accent="grey" />
      </div>

      <div className="admin-2col" style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 18, marginBottom: 18 }}>
        <Panel title="Daily performance" action={<span style={{ fontSize: 11, color: 'var(--grey-500)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Last 14 days</span>} padding={18}>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 130 }}>
            {daily.map(d => (
              <div key={d.label} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-end', gap: 4, height: '100%' }}>
                <span className="font-mono" style={{ fontSize: 10, color: 'var(--grey-600)' }}>{d.impressions > 0 ? d.impressions : ''}</span>
                <div className="stripes-bg" style={{ width: '100%', height: Math.max(3, (d.impressions / dailyPeak) * 88) }} />
                <span style={{ fontSize: 9, color: 'var(--grey-500)', whiteSpace: 'nowrap' }}>{d.label}</span>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 16, marginTop: 12, fontSize: 11, color: 'var(--grey-600)' }}>
            <span><span className="stripes-bg" style={{ display: 'inline-block', width: 10, height: 10, marginRight: 5, verticalAlign: 'middle' }} />Impressions</span>
            <span>Clicks: {daily.reduce((s, d) => s + d.clicks, 0).toLocaleString()} (14d)</span>
          </div>
        </Panel>

        <Panel title="Desktop vs Mobile" padding={18}>
          <div style={{ display: 'grid', gap: 14 }}>
            {[
              { label: 'Desktop', t: totals.desktop },
              { label: 'Mobile', t: totals.mobile },
            ].map(row => (
              <div key={row.label}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, marginBottom: 4 }}>
                  <span style={{ fontWeight: 600 }}>{row.label}</span>
                  <span className="font-mono">
                    {row.t.impressions.toLocaleString()} impr · {row.t.clicks.toLocaleString()} clicks · {ctr(row.t.clicks, row.t.impressions).toFixed(2)}% CTR
                  </span>
                </div>
                <div style={{ height: 8, background: 'var(--grey-100)' }}>
                  <div className="stripes-bg" style={{ width: `${totalImpressions ? (row.t.impressions / totalImpressions) * 100 : 0}%`, height: '100%' }} />
                </div>
              </div>
            ))}
          </div>
        </Panel>
      </div>

      <Panel title="Banner performance" padding={0}>
        {rows.length === 0 && <div style={{ padding: '20px 18px', color: 'var(--grey-500)', fontSize: 13 }}>No ad events recorded yet.</div>}
        {rows.length > 0 && (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 600 }}>
              <thead>
                <tr style={{ background: 'var(--grey-50)' }}>
                  <Th>Banner</Th><Th>Device</Th><Th align="right">Impressions</Th><Th align="right">Clicks</Th><Th align="right">CTR</Th>
                </tr>
              </thead>
              <tbody>
                {rows.map((r, i) => (
                  <tr key={`${r.banner}-${r.device}`} style={{ borderTop: '1px solid var(--grey-200)' }}>
                    <Td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <img src={r.banner} alt="" style={{ width: 56, height: 28, objectFit: 'cover', borderRadius: 4, border: '1px solid var(--grey-200)', flexShrink: 0 }} />
                        <span style={{ fontSize: 13, fontWeight: 600 }}>{prettyBannerName(r.banner)}</span>
                      </div>
                    </Td>
                    <Td>{r.device}</Td>
                    <Td align="right"><span className="font-mono">{r.impressions.toLocaleString()}</span></Td>
                    <Td align="right"><span className="font-mono">{r.clicks.toLocaleString()}</span></Td>
                    <Td align="right"><span className="font-mono">{ctr(r.clicks, r.impressions).toFixed(2)}%</span></Td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Panel>

      <div style={{ height: 18 }} />

      <Panel
        title="Advertising materials"
        action={
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ fontSize: 11, color: 'var(--grey-500)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
              {filteredMaterials.length} of {materials.length} banners
            </span>
            <select
              value={materialDevice}
              onChange={e => setMaterialDevice(e.target.value)}
              style={{
                fontSize: 12.5, padding: '5px 10px', borderRadius: 6,
                border: '1px solid var(--grey-300)', background: '#fff', color: 'var(--ink)',
              }}
            >
              <option value="all">All devices</option>
              <option value="Desktop">Desktop</option>
              <option value="Mobile">Mobile</option>
            </select>
          </div>
        }
        padding={0}
      >
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 600 }}>
            <thead>
              <tr style={{ background: 'var(--grey-50)' }}>
                <Th>Banner</Th><Th>Device</Th><Th>Click-through link</Th>
              </tr>
            </thead>
            <tbody>
              {filteredMaterials.length === 0 && (
                <tr><td colSpan="3" style={{ padding: 24, textAlign: 'center', color: 'var(--grey-500)', fontSize: 13 }}>No banners for this device.</td></tr>
              )}
              {filteredMaterials.map(m => (
                <tr key={`${m.src}-${m.device}`} style={{ borderTop: '1px solid var(--grey-200)' }}>
                  <Td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <img src={m.src} alt="" style={{ width: 56, height: 28, objectFit: 'cover', borderRadius: 4, border: '1px solid var(--grey-200)', flexShrink: 0 }} />
                      <span style={{ fontSize: 13, fontWeight: 600 }}>{prettyBannerName(m.src)}</span>
                    </div>
                  </Td>
                  <Td>{m.device}</Td>
                  <Td>
                    {m.link
                      ? <a href={m.link} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--orange)', fontSize: 12.5, wordBreak: 'break-all' }}>{m.link}</a>
                      : <span style={{ color: 'var(--grey-400)', fontSize: 12.5 }}>Not set</span>}
                  </Td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Panel>
    </AdminSection>
  );
}

Object.assign(window, { AdminAdvertising, prettyBannerName });
