/* global React */
// =======================================================================
// BlazeConnector Admin v3 — Integraciones pages
// ISP Providers · Pagos
// =======================================================================
const { useState: _is } = React;

function ProviderCard({ p, kind }) {
  const tone = p.status === 'healthy' ? 'success' : p.status === 'degraded' ? 'warn' : 'danger';
  return (
    <div className="card" style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <span style={{ width: 36, height: 36, borderRadius: 8, background: kind === 'pagos' ? 'linear-gradient(135deg, #1E7BFF, #7A3CFF)' : 'linear-gradient(135deg, #FF5A1F, #F000D8)', display: 'grid', placeItems: 'center', fontWeight: 800, color: '#fff', fontSize: 13, fontFamily: 'var(--font-display)' }}>{p.name[0]}</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 14 }}>{p.name}</div>
          <div className="mono" style={{ fontSize: 10.5, color: 'var(--app-fg3)' }}>{p.version}</div>
        </div>
        <window.StatusBadge tone={tone} label={p.status} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, padding: '8px 0', borderTop: '1px solid var(--app-divider)', borderBottom: '1px solid var(--app-divider)' }}>
        <div>
          <div style={{ fontSize: 10, color: 'var(--app-fg3)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.04em' }}>Latencia</div>
          <div style={{ fontSize: 16, fontWeight: 800, color: p.latency > 500 ? 'var(--st-warn-fg)' : 'var(--app-fg1)', fontFamily: 'var(--font-display)', fontVariantNumeric: 'tabular-nums' }}>{p.latency != null ? p.latency + 'ms' : '—'}</div>
        </div>
        <div>
          <div style={{ fontSize: 10, color: 'var(--app-fg3)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.04em' }}>Tenants</div>
          <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--app-fg1)', fontFamily: 'var(--font-display)' }}>{p.tenants}</div>
        </div>
        <div>
          <div style={{ fontSize: 10, color: 'var(--app-fg3)', textTransform: 'uppercase', fontWeight: 700, letterSpacing: '0.04em' }}>{kind === 'pagos' ? 'Moneda' : 'Vendor'}</div>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--app-fg1)' }}>{kind === 'pagos' ? p.currency : p.vendor}</div>
        </div>
      </div>

      <div style={{ fontSize: 11, color: 'var(--app-fg3)', display: 'flex', flexDirection: 'column', gap: 4 }}>
        {p.apiBase && <div className="mono" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.apiBase}</div>}
        {p.authMode && <div>Auth: {p.authMode}</div>}
      </div>

      <div style={{ display: 'flex', gap: 6 }}>
        <button className="btn btn-secondary btn-sm" style={{ flex: 1 }}><window.Icon name="settings-2" size={11} /> Configurar</button>
        <button className="btn btn-ghost btn-sm"><window.Icon name="zap" size={11} /> Test</button>
        <button className="btn btn-ghost btn-sm btn-icon-only"><window.Icon name="more-horizontal" size={13} /></button>
      </div>
    </div>
  );
}

function PageIsps() {
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">ISP Providers</h1>
          <p className="page-sub">{window.PROVIDERS_ISP.length} integraciones billing/OSS · {window.PROVIDERS_ISP.filter(p => p.status === 'healthy').length} sanos · {window.PROVIDERS_ISP.filter(p => p.status === 'degraded').length} degradados</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost btn-sm"><window.Icon name="file-text" size={12} /> Docs adapters</button>
          <button className="btn btn-primary btn-sm"><window.Icon name="plus" size={12} /> Añadir provider</button>
        </div>
      </div>

      <div className="card" style={{ marginBottom: 12 }}>
        <div className="card-head"><div className="card-title"><window.Icon name="activity" /> Health overview · últimas 4h</div></div>
        <div className="card-body">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8 }}>
            {window.PROVIDERS_ISP.map(p => (
              <div key={p.id} style={{ padding: '10px 12px', background: 'var(--app-panel-2)', borderRadius: 8, border: '1px solid var(--app-border)' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ fontWeight: 700, fontSize: 12 }}>{p.name}</span>
                  <span className="sb-dot" style={{ background: p.status === 'healthy' ? 'var(--blaze-green)' : p.status === 'degraded' ? 'var(--warn)' : 'var(--danger)' }}></span>
                </div>
                <window.Sparkline data={Array.from({ length: 30 }, (_, i) => p.latency + Math.sin(i * 0.5) * 40 + (Math.random() - 0.5) * 30)} color={p.status === 'healthy' ? 'green' : p.status === 'degraded' ? 'warn' : 'danger'} />
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--app-fg3)', marginTop: 4 }}>
                  <span>{p.latency}ms avg</span>
                  <span>{p.tenants} tenants</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="grid-3">
        {window.PROVIDERS_ISP.map(p => <ProviderCard key={p.id} p={p} kind="billing" />)}
      </div>

      <window.SectionCard title="Tenants por provider" icon="building-2" sub="Mapeo actual" flush className="" >
        <window.DataTable density="cozy" columns={[
          { label: 'Tenant', render: (t) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><window.TenantAvatar tenant={t} size={20} /> {t.name}</span> },
          { label: 'ID', width: 100, render: (t) => <span className="mono" style={{ color: 'var(--app-fg2)' }}>{t.id}</span> },
          { label: 'Billing provider', width: 160, render: (t) => <span className="pv"><span className="pv-ico">{t.billing[0].toUpperCase()}</span>{(window.PROVIDERS_ISP.find(p => p.id === t.billing) || {}).name}</span> },
          { label: 'Estado provider', width: 140, render: (t) => { const p = window.PROVIDERS_ISP.find(x => x.id === t.billing); return <window.StatusBadge tone={p && p.status === 'healthy' ? 'success' : p && p.status === 'degraded' ? 'warn' : 'danger'} label={p ? p.status : '—'} />; } },
          { label: 'Última sync', width: 130, render: () => <span style={{ fontSize: 11, color: 'var(--app-fg3)' }}>hace {Math.floor(Math.random() * 15) + 1}m</span> },
          { label: 'Diffs pendientes', width: 140, numeric: true, render: () => <span className="mono">{Math.floor(Math.random() * 12)}</span> }
        ]} rows={window.TENANTS.slice(0, 8)} />
      </window.SectionCard>
    </div>
  );
}

function PagePagos() {
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Pagos · Gateways</h1>
          <p className="page-sub">{window.PROVIDERS_PAY.length} gateways · {window.PROVIDERS_PAY.filter(p => p.status === 'healthy').length} OK · {window.PROVIDERS_PAY.filter(p => p.status === 'down').length} caídos</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost btn-sm"><window.Icon name="receipt" size={12} /> Reconciliación</button>
          <button className="btn btn-primary btn-sm"><window.Icon name="plus" size={12} /> Añadir gateway</button>
        </div>
      </div>

      <div className="grid-4" style={{ marginBottom: 12 }}>
        <window.KpiCard label="Transacciones 24h" value={4218} delta={12.4} series={window.DASHBOARD_SERIES.msgsPerMin.slice(0, 30).map(v => v / 3)} color="blue" />
        <window.KpiCard label="Volumen 24h" value="RD$ 8.4M" delta={3.2} color="green" foot="USD$ 142k incluido" />
        <window.KpiCard label="Tasa de éxito" value="96.4%" color="green" delta={-1.2} deltaTone="down" foot="↓ por CyberSource down" />
        <window.KpiCard label="Disputa rate" value="0.18%" color="warn" foot="dentro de threshold" />
      </div>

      <div className="grid-4">
        {window.PROVIDERS_PAY.map(p => <ProviderCard key={p.id} p={p} kind="pagos" />)}
      </div>

      <window.SectionCard title="Transacciones recientes" icon="receipt" flush style={{ marginTop: 12 }}>
        <window.DataTable density="compact" columns={[
          { label: 'Hora', width: 100, render: (r) => <span className="mono" style={{ color: 'var(--app-fg3)' }}>{window.fmtTime(r.ts)}</span> },
          { label: 'Tenant', width: 160, render: (r) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><window.TenantAvatar tenant={{ id: r.tenant, name: r.tenantName }} size={16} /> <span className="truncate" style={{ maxWidth: 130 }}>{r.tenantName}</span></span> },
          { label: 'Gateway', width: 100, render: (r) => <span className="pv"><span className="pv-ico" style={{ background: '#1E7BFF' }}>{r.gateway[0]}</span>{r.gateway}</span> },
          { label: 'Método', width: 90, render: (r) => <span style={{ fontSize: 11 }}>{r.method}</span> },
          { label: 'Cliente', width: 200, render: (r) => <span><span className="mono" style={{ fontSize: 11.5, color: 'var(--app-fg2)' }}>{r.last4}</span> <span style={{ color: 'var(--app-fg3)', marginLeft: 6 }}>{r.contact}</span></span> },
          { label: 'Monto', width: 130, numeric: true, render: (r) => <span className="mono" style={{ fontWeight: 700 }}>{r.currency}$ {r.amount.toLocaleString()}</span> },
          { label: 'Estado', width: 100, render: (r) => <window.StatusBadge status={r.status} tone={r.status === 'captured' ? 'success' : r.status === 'pending' ? 'warn' : r.status === 'failed' ? 'danger' : 'info'} /> },
          { label: 'txn_id', width: 140, render: (r) => <span className="mono" style={{ fontSize: 10.5, color: 'var(--app-fg3)' }}>{r.txnId}</span> }
        ]} rows={genTransactions()} />
      </window.SectionCard>
    </div>
  );
}

function genTransactions() {
  const now = Date.now();
  const out = [];
  const gateways = ['CardNET', 'Azul', 'PayPal'];
  const methods = ['VISA', 'Mastercard', 'Amex', 'OXXO', 'PayPal'];
  const statuses = [{ v: 'captured', wt: 7 }, { v: 'pending', wt: 2 }, { v: 'failed', wt: 1 }];
  for (let i = 0; i < 12; i++) {
    const tnt = window.randomFrom(window.TENANTS.filter(t => t.status === 'active' && t.pagos.length > 0));
    const w = statuses.reduce((a, s) => a + s.wt, 0);
    let r = Math.random() * w; let st = 'captured';
    for (const s of statuses) { r -= s.wt; if (r <= 0) { st = s.v; break; } }
    out.push({
      id: 'tx_' + window.randHex(10),
      ts: new Date(now - i * (Math.random() * 200000 + 30000)).toISOString(),
      tenant: tnt.id, tenantName: tnt.name,
      gateway: window.randomFrom(gateways),
      method: window.randomFrom(methods),
      last4: '•••• ' + (Math.floor(Math.random() * 9000) + 1000),
      contact: window.randomFrom(window.DR_NAMES),
      currency: 'RD',
      amount: Math.floor(Math.random() * 4000) + 350,
      status: st,
      txnId: 'CN' + window.randHex(10).toUpperCase()
    });
  }
  return out;
}

Object.assign(window, { PageIsps, PagePagos });
