// Admin panel — affiliates, payments, overview
function AdminPage() {
  const [tab, setTab] = React.useState('overview');
  const [tick, setTick] = React.useState(0);

  const reload = async () => {
    await window.loadAdminData(window.KYOUDAI.USER.id);
    setTick(t => t + 1);
  };

  return (
    <div className="page-enter" style={{ padding:'26px 32px 48px' }} key={tick}>
      {/* Tab bar */}
      <div style={{ display:'flex', gap:6, marginBottom:24 }}>
        {[
          { k:'overview',   l:'Overview' },
          { k:'affiliates', l:'Afiliados' },
          { k:'payments',   l:'Pagos pendientes' },
          { k:'history',    l:'Historial pagos' },
          { k:'create',     l:'+ Nuevo afiliado' },
          { k:'content',    l:'Content Hub' },
        ].map(t => (
          <button key={t.k} onClick={() => setTab(t.k)}
            className={`btn ${tab===t.k ? 'btn-primary' : ''}`}
            style={tab===t.k ? {} : { background:'rgba(255,255,255,0.03)' }}>
            {t.l}
          </button>
        ))}
        <button className="btn btn-sm" style={{ marginLeft:'auto' }} onClick={reload}>
          ↻ Recargar
        </button>
      </div>

      {tab === 'overview'   && <AdminOverview/>}
      {tab === 'affiliates' && <AdminAffiliates reload={reload}/>}
      {tab === 'payments'   && <AdminPayments   reload={reload}/>}
      {tab === 'history'    && <AdminPayHistory/>}
      {tab === 'create'     && <AdminCreateAffiliate reload={reload}/>}
      {tab === 'content'    && <AdminContent reload={reload}/>}
    </div>
  );
}

// ── Overview ──────────────────────────────────────────────────────
function AdminOverview() {
  const { ADMIN, PRODUCTS } = window.KYOUDAI;
  if (!ADMIN) return <AdminNoData/>;

  const affCount    = ADMIN.affiliates.length;
  const activeAff   = ADMIN.affiliates.filter(a => a.salesCount > 0).length;
  const totalGMV    = ADMIN.pendingTx.reduce((s,t) => s + (t.commission / 0.05), 0); // rough estimate
  const stats = [
    { label:'Afiliados activos', value: `${activeAff}/${affCount}`,  sub:'con alguna venta',    color:'#5B8CFF' },
    { label:'Comisiones pendientes', value: `€${ADMIN.totalPending.toFixed(2)}`, sub:'a pagar este mes', color:'#FF8FA5' },
    { label:'Ganancias totales',  value: `€${ADMIN.totalEarnings.toFixed(2)}`, sub:'historial completo', color:'#3EE8BE' },
    { label:'Transacciones',  value: ADMIN.pendingTx.length,        sub:'pendientes/aprobadas', color:'#F6C56B' },
  ];

  return (
    <div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:24 }}>
        {stats.map((s,i) => (
          <div key={i} className="glass" style={{ padding:'18px 20px' }}>
            <div className="mono" style={{ fontSize:10, color:'var(--sub)', letterSpacing:'0.1em', marginBottom:8 }}>{s.label.toUpperCase()}</div>
            <div style={{ fontSize:26, fontWeight:800, color:s.color, letterSpacing:'-0.03em' }}>{s.value}</div>
            <div style={{ fontSize:11, color:'var(--sub)', marginTop:4 }}>{s.sub}</div>
          </div>
        ))}
      </div>

      {/* Top performers */}
      <div className="glass" style={{ padding:24 }}>
        <div style={{ fontWeight:600, fontSize:14, marginBottom:16 }}>Top afiliados</div>
        <table>
          <thead><tr>
            <th>#</th><th>Afiliado</th><th>Tier</th><th>Total ganado</th><th>Pendiente</th><th>Ventas</th><th>Pago</th>
          </tr></thead>
          <tbody>
            {ADMIN.affiliates.slice(0,10).map((a,i) => (
              <tr key={a.id}>
                <td><div className={`rank-ring rank-${i<3?i+1:'n'}`}>{i+1}</div></td>
                <td>
                  <div style={{ fontWeight:600, fontSize:13 }}>{a.name}</div>
                  <div className="mono" style={{ fontSize:10, color:'var(--sub)' }}>@{a.handle}</div>
                </td>
                <td><TierBadge tier={a.tier}/></td>
                <td className="mono" style={{ color:'#3EE8BE', fontWeight:700 }}>€{a.totalEarnings.toFixed(2)}</td>
                <td className="mono" style={{ color: a.pendingEarnings > 0 ? '#FF8FA5' : 'var(--sub)' }}>€{a.pendingEarnings.toFixed(2)}</td>
                <td className="mono">{a.salesCount}</td>
                <td style={{ fontSize:12, color:'var(--sub)' }}>{a.payoutLine}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Affiliates ─────────────────────────────────────────────────────
function AdminAffiliates({ reload }) {
  const { ADMIN } = window.KYOUDAI;
  if (!ADMIN) return <AdminNoData/>;
  const [editing, setEditing] = React.useState(null);

  return (
    <div>
      {editing && <EditAffiliateModal affiliate={editing} onClose={saved => { setEditing(null); if(saved) reload(); }}/>}
      <div className="glass" style={{ overflow:'hidden' }}>
        <table>
          <thead><tr>
            <th>Afiliado</th><th>Tier</th><th>Total €</th><th>Pendiente €</th><th>Ventas</th><th>Método de pago</th><th>Desde</th><th></th>
          </tr></thead>
          <tbody>
            {ADMIN.affiliates.map(a => (
              <tr key={a.id}>
                <td>
                  <div style={{ fontWeight:600 }}>{a.name}</div>
                  <div className="mono" style={{ fontSize:10, color:'var(--sub)' }}>@{a.handle}</div>
                </td>
                <td><TierBadge tier={a.tier}/></td>
                <td className="mono" style={{ color:'#3EE8BE', fontWeight:600 }}>€{a.totalEarnings.toFixed(2)}</td>
                <td className="mono" style={{ color: a.pendingEarnings>0?'#FF8FA5':'var(--sub)' }}>€{a.pendingEarnings.toFixed(2)}</td>
                <td className="mono">{a.salesCount}</td>
                <td style={{ fontSize:12 }}>
                  <div>{a.payoutMethod}</div>
                  <div className="mono" style={{ fontSize:10, color:'var(--sub)' }}>{a.payoutLine}</div>
                </td>
                <td className="mono" style={{ fontSize:11, color:'var(--sub)' }}>{a.joined}</td>
                <td style={{ textAlign:'right' }}>
                  <button className="btn btn-sm" onClick={() => setEditing(a)}>Editar</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function EditAffiliateModal({ affiliate, onClose }) {
  const [tier, setTier] = React.useState(affiliate.tier || 'Starter');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  async function save(e) {
    e.preventDefault();
    setLoading(true); setError('');
    const { error: err } = await window.SUPABASE.from('affiliates')
      .update({ tier })
      .eq('id', affiliate.id);
    setLoading(false);
    if (err) { setError(err.message); return; }
    onClose(true);
  }

  return (
    <div style={{ position:'fixed', inset:0, zIndex:999, display:'flex', alignItems:'center', justifyContent:'center', background:'rgba(0,0,0,0.72)', backdropFilter:'blur(4px)' }}
      onClick={e => { if(e.target===e.currentTarget) onClose(false); }}>
      <div className="glass-strong" style={{ width:380, padding:28, borderRadius:16 }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:20 }}>
          <div style={{ fontSize:15, fontWeight:700 }}>Editar — {affiliate.name}</div>
          <button onClick={() => onClose(false)} style={{ background:'none', border:'none', color:'var(--sub)', cursor:'pointer', fontSize:22 }}>&times;</button>
        </div>
        <form onSubmit={save} style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <div>
            <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Tier</label>
            <select className="field" value={tier} onChange={e => setTier(e.target.value)} style={{ width:'100%' }}>
              <option value="Starter">Starter — 3%</option>
              <option value="Collector">Collector — 5%</option>
              <option value="Godpack">Godpack — 7%</option>
            </select>
          </div>
          {error && <div style={{ fontSize:12, color:'#FF8FA5', padding:'8px 12px', background:'rgba(255,107,138,0.08)', borderRadius:8 }}>{error}</div>}
          <div style={{ display:'flex', gap:10, justifyContent:'flex-end' }}>
            <button type="button" className="btn" onClick={() => onClose(false)}>Cancelar</button>
            <button type="submit" className="btn btn-primary" disabled={loading}>{loading ? 'Guardando…' : 'Guardar'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Payments pending ───────────────────────────────────────────────
function AdminPayments({ reload }) {
  const { ADMIN } = window.KYOUDAI;
  if (!ADMIN) return <AdminNoData/>;

  const withPending = ADMIN.affiliates.filter(a => a.pendingEarnings > 0);
  if (withPending.length === 0) {
    return (
      <div className="glass" style={{ padding:48, textAlign:'center' }}>
        <div style={{ fontSize:32, marginBottom:12 }}>✅</div>
        <div style={{ fontSize:15, fontWeight:600 }}>Sin pagos pendientes</div>
        <div style={{ fontSize:13, color:'var(--sub)', marginTop:6 }}>Todos los afiliados están al día.</div>
      </div>
    );
  }

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      <div style={{ fontSize:13, color:'var(--sub)' }}>
        {withPending.length} afiliados con comisiones pendientes — total <span style={{ color:'#FF8FA5', fontWeight:700 }}>€{ADMIN.totalPending.toFixed(2)}</span>
      </div>
      {withPending.map(a => (
        <PaymentCard key={a.id} affiliate={a} txs={ADMIN.pendingByAffiliate[a.id] || []} reload={reload}/>
      ))}
    </div>
  );
}

function PaymentCard({ affiliate, txs, reload }) {
  const [expanded, setExpanded] = React.useState(false);
  const [paying, setPaying] = React.useState(false);
  const [ref, setRef] = React.useState('');
  const [note, setNote] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  async function markPaid(e) {
    e.preventDefault();
    setLoading(true); setError('');
    const { error: err } = await window.SUPABASE.from('payouts').insert({
      affiliate_id: affiliate.id,
      amount:       affiliate.pendingEarnings,
      method:       affiliate.payoutMethod,
      reference:    ref || null,
      note:         note || null,
    });
    setLoading(false);
    if (err) { setError(err.message); return; }
    setPaying(false);
    await reload();
  }

  return (
    <div className="glass" style={{ padding:'18px 20px', border:'1px solid rgba(255,107,138,0.2)' }}>
      <div style={{ display:'flex', alignItems:'center', gap:14 }}>
        <Avatar initials={affiliate.name.split(' ').map(n=>n[0]).join('').slice(0,2)} size={40} tone="#FF6B8A"/>
        <div style={{ flex:1 }}>
          <div style={{ display:'flex', alignItems:'center', gap:8 }}>
            <span style={{ fontWeight:700, fontSize:14 }}>{affiliate.name}</span>
            <TierBadge tier={affiliate.tier}/>
          </div>
          <div className="mono" style={{ fontSize:11, color:'var(--sub)', marginTop:3 }}>
            @{affiliate.handle} · {affiliate.payoutMethod} · {affiliate.payoutLine}
          </div>
        </div>
        <div style={{ textAlign:'right' }}>
          <div style={{ fontSize:24, fontWeight:800, color:'#FF8FA5', letterSpacing:'-0.03em' }}>€{affiliate.pendingEarnings.toFixed(2)}</div>
          <div style={{ fontSize:11, color:'var(--sub)' }}>{txs.length} transacciones</div>
        </div>
        <div style={{ display:'flex', gap:8, flexDirection:'column', alignItems:'flex-end' }}>
          <button className="btn btn-sm" onClick={() => setExpanded(e => !e)}>
            {expanded ? 'Ocultar' : 'Ver txs'}
          </button>
          <button className="btn btn-sm btn-primary" style={{ marginTop:4 }} onClick={() => setPaying(p => !p)}>
            {paying ? 'Cancelar' : 'Marcar pagado'}
          </button>
        </div>
      </div>

      {/* Pay form */}
      {paying && (
        <form onSubmit={markPaid} style={{ marginTop:16, paddingTop:16, borderTop:'1px solid var(--line)', display:'flex', gap:10, flexWrap:'wrap', alignItems:'flex-end' }}>
          <div style={{ flex:1, minWidth:200 }}>
            <label style={{ fontSize:11, color:'var(--sub)', display:'block', marginBottom:4 }}>Referencia de pago (opcional)</label>
            <input className="field" placeholder="SEPA ref, PayPal TX ID…" value={ref} onChange={e=>setRef(e.target.value)} style={{ width:'100%' }}/>
          </div>
          <div style={{ flex:1, minWidth:200 }}>
            <label style={{ fontSize:11, color:'var(--sub)', display:'block', marginBottom:4 }}>Nota (opcional)</label>
            <input className="field" placeholder="Ej: pago enero 2026" value={note} onChange={e=>setNote(e.target.value)} style={{ width:'100%' }}/>
          </div>
          <button type="submit" className="btn btn-primary" disabled={loading} style={{ height:36 }}>
            {loading ? 'Procesando…' : `✓ Confirmar €${affiliate.pendingEarnings.toFixed(2)}`}
          </button>
          {error && <div style={{ width:'100%', fontSize:12, color:'#FF8FA5' }}>{error}</div>}
        </form>
      )}

      {/* Transactions list */}
      {expanded && txs.length > 0 && (
        <div style={{ marginTop:14, paddingTop:14, borderTop:'1px solid var(--line)' }}>
          <table>
            <thead><tr><th>Orden</th><th>Producto</th><th>Fecha</th><th>Estado</th><th>Comisión</th></tr></thead>
            <tbody>
              {txs.map(t => (
                <tr key={t.id}>
                  <td className="mono" style={{ fontSize:11 }}>{t.orderId || '—'}</td>
                  <td style={{ fontSize:12 }}>{t.product}</td>
                  <td className="mono" style={{ fontSize:11, color:'var(--sub)' }}>{t.date}</td>
                  <td>
                    <span style={{
                      padding:'2px 8px', borderRadius:99, fontSize:10, fontWeight:600,
                      background: t.status==='approved' ? 'rgba(0,224,164,0.1)' : 'rgba(246,197,107,0.1)',
                      color: t.status==='approved' ? '#3EE8BE' : '#F6C56B',
                    }}>{t.status}</span>
                  </td>
                  <td className="mono" style={{ color:'#3EE8BE', fontWeight:700 }}>€{t.commission.toFixed(2)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// ── Payment history ────────────────────────────────────────────────
function AdminPayHistory() {
  const { ADMIN } = window.KYOUDAI;
  if (!ADMIN || ADMIN.recentPayouts.length === 0) {
    return (
      <div className="glass" style={{ padding:48, textAlign:'center' }}>
        <div style={{ fontSize:13, color:'var(--sub)' }}>Sin historial de pagos todavía.</div>
      </div>
    );
  }

  const affMap = {};
  ADMIN.affiliates.forEach(a => { affMap[a.id] = a; });

  return (
    <div className="glass" style={{ overflow:'hidden' }}>
      <table>
        <thead><tr>
          <th>Fecha</th><th>Afiliado</th><th>Importe</th><th>Método</th><th>Referencia</th><th>Nota</th>
        </tr></thead>
        <tbody>
          {ADMIN.recentPayouts.map(p => {
            const a = affMap[p.affiliateId];
            return (
              <tr key={p.id}>
                <td className="mono" style={{ fontSize:11 }}>{p.paidAt}</td>
                <td>
                  <div style={{ fontWeight:600, fontSize:13 }}>{a ? a.name : '—'}</div>
                  <div className="mono" style={{ fontSize:10, color:'var(--sub)' }}>{a ? '@'+a.handle : ''}</div>
                </td>
                <td className="mono" style={{ color:'#3EE8BE', fontWeight:700, fontSize:16 }}>€{p.amount.toFixed(2)}</td>
                <td style={{ fontSize:12 }}>{p.method || '—'}</td>
                <td className="mono" style={{ fontSize:11, color:'var(--sub)' }}>{p.reference || '—'}</td>
                <td style={{ fontSize:12, color:'var(--sub)' }}>{p.note || '—'}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ── Create affiliate ───────────────────────────────────────────────
function AdminCreateAffiliate({ reload }) {
  const [name,     setName]     = React.useState('');
  const [handle,   setHandle]   = React.useState('');
  const [email,    setEmail]    = React.useState('');
  const [password, setPassword] = React.useState('');
  const [tier,     setTier]     = React.useState('Starter');
  const [refCode,  setRefCode]  = React.useState('');
  const [loading,  setLoading]  = React.useState(false);
  const [error,    setError]    = React.useState('');
  const [success,  setSuccess]  = React.useState('');

  function generateRef() {
    const code = handle.toUpperCase().slice(0,6) + '-' + Math.random().toString(36).slice(2,6).toUpperCase();
    setRefCode(code);
  }

  async function create(e) {
    e.preventDefault();
    setLoading(true); setError(''); setSuccess('');

    // 1. Create auth user via admin API... but we only have anon key.
    // Instead: create the affiliate row without auth user (admin creates, user sets password later)
    // Use Supabase Admin to create user
    const { data: authData, error: authErr } = await window.SUPABASE.auth.signUp({
      email, password,
      options: { data: { name } }
    });

    if (authErr) {
      setLoading(false);
      setError('Auth error: ' + authErr.message);
      return;
    }

    const userId = authData.user?.id;
    if (!userId) { setLoading(false); setError('No user ID returned'); return; }

    const finalRef = refCode || (handle.toUpperCase() + '-' + Math.random().toString(36).slice(2,5).toUpperCase());
    const { data: affData, error: affErr } = await window.SUPABASE.from('affiliates').insert({
      user_id:      userId,
      name,
      handle,
      referral_code: finalRef,
      tier,
    }).select('id').single();

    if (affErr) { setLoading(false); setError('Affiliate create error: ' + affErr.message); return; }

    // Auto-create tracking links for every active product
    const { data: prods } = await window.SUPABASE.from('products').select('id, handle').eq('active', true);
    if (prods && prods.length > 0) {
      const linkRows = prods.map(p => ({
        affiliate_id: affData.id,
        product_id:   p.id,
        slug:         handle + '-' + p.handle,
        clicks:       0,
        conversions:  0,
        earnings:     0,
      }));
      await window.SUPABASE.from('affiliate_links').insert(linkRows);
    }

    setLoading(false);
    setSuccess(`✓ Afiliado "${name}" creado con ${prods ? prods.length : 0} links de tracking. Email: ${email}`);
    setName(''); setHandle(''); setEmail(''); setPassword(''); setRefCode('');
    await reload();
  }

  return (
    <div style={{ maxWidth:520 }}>
      <div className="glass" style={{ padding:28 }}>
        <div style={{ fontSize:15, fontWeight:700, marginBottom:20 }}>Crear nuevo afiliado</div>
        <form onSubmit={create} style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <div>
              <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Nombre completo</label>
              <input className="field" required value={name} onChange={e=>setName(e.target.value)} placeholder="Miguel López" style={{ width:'100%' }}/>
            </div>
            <div>
              <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Handle</label>
              <input className="field" required value={handle} onChange={e=>setHandle(e.target.value.toLowerCase().replace(/\s/g,''))} placeholder="miguellopez" style={{ width:'100%' }}/>
            </div>
          </div>
          <div>
            <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Email</label>
            <input className="field" type="email" required value={email} onChange={e=>setEmail(e.target.value)} placeholder="miguel@email.com" style={{ width:'100%' }}/>
          </div>
          <div>
            <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Contraseña inicial</label>
            <input className="field" type="password" required minLength={8} value={password} onChange={e=>setPassword(e.target.value)} placeholder="mín. 8 caracteres" style={{ width:'100%' }}/>
          </div>
          <div>
            <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Tier inicial</label>
            <select className="field" value={tier} onChange={e=>setTier(e.target.value)} style={{ width:'100%' }}>
              <option value="Starter">Starter — 3%</option>
              <option value="Collector">Collector — 5%</option>
              <option value="Godpack">Godpack — 7%</option>
            </select>
          </div>
          <div>
            <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Código de referido</label>
            <div style={{ display:'flex', gap:8 }}>
              <input className="field" value={refCode} onChange={e=>setRefCode(e.target.value.toUpperCase())} placeholder="AUTO si vacío" style={{ flex:1 }}/>
              <button type="button" className="btn btn-sm" onClick={generateRef}>Generar</button>
            </div>
          </div>
          {error && <div style={{ fontSize:12, color:'#FF8FA5', padding:'8px 12px', background:'rgba(255,107,138,0.08)', borderRadius:8 }}>{error}</div>}
          {success && <div style={{ fontSize:12, color:'#3EE8BE', padding:'8px 12px', background:'rgba(0,224,164,0.08)', borderRadius:8 }}>{success}</div>}
          <button type="submit" className="btn btn-primary" disabled={loading} style={{ height:42, justifyContent:'center', marginTop:4 }}>
            {loading ? 'Creando…' : 'Crear afiliado'}
          </button>
        </form>
      </div>
    </div>
  );
}

// ── Content Hub admin ─────────────────────────────────────────────
function AdminContent({ reload }) {
  const { ADMIN, PRODUCTS } = window.KYOUDAI;
  const [editing,  setEditing]  = React.useState(null);
  const [creating, setCreating] = React.useState(false);
  const assets = (ADMIN && ADMIN.contentAssets) || [];

  async function toggleActive(a) {
    await window.SUPABASE.from('content_assets').update({ active: !a.active }).eq('id', a.id);
    reload();
  }
  async function del(id) {
    if (!confirm('¿Eliminar este asset de contenido?')) return;
    await window.SUPABASE.from('content_assets').delete().eq('id', id);
    reload();
  }

  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
        <div style={{ fontSize:13, color:'var(--sub)' }}>{assets.length} assets de contenido</div>
        <button className="btn btn-primary btn-sm" onClick={() => setCreating(true)}>+ Nuevo asset</button>
      </div>
      {(editing || creating) && (
        <ContentModal
          asset={editing}
          products={PRODUCTS || []}
          onClose={saved => { setEditing(null); setCreating(false); if (saved) reload(); }}
        />
      )}
      {assets.length === 0 ? (
        <div className="glass" style={{ padding:48, textAlign:'center' }}>
          <div style={{ fontSize:13, color:'var(--sub)' }}>Sin assets todavía. Crea el primero arriba.</div>
        </div>
      ) : (
        <div className="glass" style={{ overflow:'hidden' }}>
          <table>
            <thead><tr>
              <th>Producto</th><th>Hook</th><th>Tipo</th><th>Views</th><th>Engage</th><th>Duración</th><th>Estado</th><th></th>
            </tr></thead>
            <tbody>
              {assets.map(a => (
                <tr key={a.id}>
                  <td style={{ fontSize:12 }}>{a.productName}</td>
                  <td style={{ fontSize:12, maxWidth:240, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }} title={a.hook}>{a.hook || '—'}</td>
                  <td className="mono" style={{ fontSize:10 }}>{a.type || '—'}</td>
                  <td className="mono" style={{ fontSize:11 }}>{(a.views||0).toLocaleString()}</td>
                  <td className="mono" style={{ fontSize:11 }}>{a.engagementRate}%</td>
                  <td className="mono" style={{ fontSize:11 }}>{a.duration || '—'}</td>
                  <td>
                    <button className="btn btn-sm" onClick={() => toggleActive(a)}
                      style={{ background: a.active ? 'rgba(0,224,164,0.1)' : 'rgba(255,107,138,0.1)',
                               color: a.active ? '#3EE8BE' : '#FF8FA5' }}>
                      {a.active ? '✓ Activo' : '✗ Oculto'}
                    </button>
                  </td>
                  <td style={{ textAlign:'right' }}>
                    <div style={{ display:'flex', gap:6, justifyContent:'flex-end' }}>
                      <button className="btn btn-sm" onClick={() => setEditing(a)}>Editar</button>
                      <button className="btn btn-sm" style={{ color:'#FF8FA5' }} onClick={() => del(a.id)}>×</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

function ContentModal({ asset, products, onClose }) {
  const isEdit = !!asset;
  const [productId,    setProductId]    = React.useState(asset ? asset.productId    : '');
  const [hook,         setHook]         = React.useState(asset ? asset.hook         : '');
  const [caption,      setCaption]      = React.useState(asset ? asset.caption      : '');
  const [type,         setType]         = React.useState(asset ? asset.type         : 'hooks');
  const [duration,     setDuration]     = React.useState(asset ? asset.duration     : '');
  const [views,        setViews]        = React.useState(asset ? String(asset.views) : '0');
  const [engagement,   setEngagement]   = React.useState(asset ? String(asset.engagementRate) : '0');
  const [color,        setColor]        = React.useState(asset ? asset.color        : '#5B8CFF');
  const [videoUrl,     setVideoUrl]     = React.useState(asset ? asset.videoUrl     : '');
  const [thumbnailUrl, setThumbnailUrl] = React.useState(asset ? asset.thumbnailUrl : '');
  const [loading, setLoading] = React.useState(false);
  const [error,   setError]   = React.useState('');

  const COLORS = ['#5B8CFF','#B89BFF','#3EE8BE','#F6C56B','#FF6B8A','#D6DAE3'];

  async function save(e) {
    e.preventDefault();
    setLoading(true); setError('');
    const payload = {
      product_id:      productId || null,
      hook,
      caption,
      type,
      duration,
      views:           parseInt(views) || 0,
      engagement_rate: parseFloat(engagement) || 0,
      color,
      video_url:       videoUrl || null,
      thumbnail_url:   thumbnailUrl || null,
      active:          true,
    };
    let err;
    if (isEdit) {
      ({ error: err } = await window.SUPABASE.from('content_assets').update(payload).eq('id', asset.id));
    } else {
      ({ error: err } = await window.SUPABASE.from('content_assets').insert(payload));
    }
    setLoading(false);
    if (err) { setError(err.message); return; }
    onClose(true);
  }

  return (
    <div style={{ position:'fixed', inset:0, zIndex:999, display:'flex', alignItems:'center', justifyContent:'center', background:'rgba(0,0,0,0.72)', backdropFilter:'blur(4px)' }}
      onClick={e => { if (e.target === e.currentTarget) onClose(false); }}>
      <div className="glass-strong" style={{ width:560, maxHeight:'88vh', overflow:'auto', padding:28, borderRadius:16 }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:20 }}>
          <div style={{ fontSize:15, fontWeight:700 }}>{isEdit ? 'Editar asset' : 'Nuevo asset de contenido'}</div>
          <button onClick={() => onClose(false)} style={{ background:'none', border:'none', color:'var(--sub)', cursor:'pointer', fontSize:22 }}>&times;</button>
        </div>
        <form onSubmit={save} style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <div>
              <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Producto asociado</label>
              <select className="field" value={productId} onChange={e => setProductId(e.target.value)} style={{ width:'100%' }}>
                <option value="">— Sin producto específico —</option>
                {products.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
              </select>
            </div>
            <div>
              <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Tipo de contenido</label>
              <select className="field" value={type} onChange={e => setType(e.target.value)} style={{ width:'100%' }}>
                <option value="hooks">Hooks</option>
                <option value="unboxings">Unboxings</option>
                <option value="reviews">Reviews</option>
              </select>
            </div>
          </div>
          <div>
            <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Hook (título del vídeo)</label>
            <input className="field" required value={hook} onChange={e => setHook(e.target.value)}
              placeholder="Ej: El PSA 10 más caro de mi colección..." style={{ width:'100%' }}/>
          </div>
          <div>
            <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Caption / copy para redes</label>
            <textarea value={caption} onChange={e => setCaption(e.target.value)}
              placeholder="Texto listo para copiar en Instagram, TikTok..."
              style={{ width:'100%', height:90, padding:'8px 12px', borderRadius:10,
                background:'rgba(255,255,255,0.03)', border:'1px solid var(--line)',
                color:'var(--text)', font:'400 13px/1.55 Sora,sans-serif', outline:'none', resize:'vertical' }}/>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12 }}>
            <div>
              <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Duración</label>
              <input className="field" value={duration} onChange={e => setDuration(e.target.value)} placeholder="0:45" style={{ width:'100%' }}/>
            </div>
            <div>
              <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Vistas</label>
              <input className="field" type="number" min="0" value={views} onChange={e => setViews(e.target.value)} style={{ width:'100%' }}/>
            </div>
            <div>
              <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Engagement %</label>
              <input className="field" type="number" step="0.1" min="0" value={engagement} onChange={e => setEngagement(e.target.value)} style={{ width:'100%' }}/>
            </div>
          </div>
          <div>
            <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>URL del vídeo (TikTok / Reels / YouTube)</label>
            <input className="field" value={videoUrl} onChange={e => setVideoUrl(e.target.value)} placeholder="https://..." style={{ width:'100%' }}/>
          </div>
          <div>
            <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>URL del thumbnail</label>
            <input className="field" value={thumbnailUrl} onChange={e => setThumbnailUrl(e.target.value)} placeholder="https://..." style={{ width:'100%' }}/>
          </div>
          <div>
            <label style={{ fontSize:12, color:'var(--sub)', display:'block', marginBottom:6 }}>Color de acento</label>
            <div style={{ display:'flex', gap:8, alignItems:'center' }}>
              {COLORS.map(c => (
                <button key={c} type="button" onClick={() => setColor(c)}
                  style={{ width:26, height:26, borderRadius:6, background:c, cursor:'pointer',
                           border: color===c ? '2px solid white' : '2px solid transparent' }}/>
              ))}
              <input type="color" value={color} onChange={e => setColor(e.target.value)}
                style={{ width:32, height:32, borderRadius:6, border:'1px solid var(--line)', background:'none', cursor:'pointer' }}/>
            </div>
          </div>
          {error && <div style={{ fontSize:12, color:'#FF8FA5', padding:'8px 12px', background:'rgba(255,107,138,0.08)', borderRadius:8 }}>{error}</div>}
          <div style={{ display:'flex', gap:10, justifyContent:'flex-end' }}>
            <button type="button" className="btn" onClick={() => onClose(false)}>Cancelar</button>
            <button type="submit" className="btn btn-primary" disabled={loading}>
              {loading ? 'Guardando…' : isEdit ? 'Guardar cambios' : 'Crear asset'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Helpers ───────────────────────────────────────────────────────
function TierBadge({ tier }) {
  const t = (tier||'starter').toLowerCase();
  const map = {
    starter:   { color:'#5B8CFF', bg:'rgba(91,140,255,0.12)' },
    collector: { color:'#B89BFF', bg:'rgba(138,91,255,0.12)' },
    godpack:   { color:'#F6C56B', bg:'rgba(246,197,107,0.12)' },
  };
  const s = map[t] || map.starter;
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', gap:4,
      padding:'2px 8px', borderRadius:99,
      background: s.bg, color: s.color,
      fontSize:10, fontWeight:700, fontFamily:'JetBrains Mono, monospace', letterSpacing:'0.08em',
    }}>
      {(tier||'Starter').toUpperCase()}
    </span>
  );
}

function AdminNoData() {
  return (
    <div className="glass" style={{ padding:48, textAlign:'center' }}>
      <div style={{ fontSize:13, color:'var(--sub)' }}>Cargando datos de admin…</div>
    </div>
  );
}

window.AdminPage = AdminPage;
