// Earnings page
function EarningsPage(){
  const { TRANSACTIONS, PRODUCTS, USER } = window.KYOUDAI;
  const isMobile = window.useIsMobile();
  const [filter, setFilter] = React.useState("all");

  const paid    = TRANSACTIONS.filter(t => t.status === "Paid").reduce((s,t) => s + t.commission, 0);
  const pending = TRANSACTIONS.filter(t => t.status === "Pending").reduce((s,t) => s + t.commission, 0);
  const rows    = TRANSACTIONS.filter(t => filter === "all" || t.status.toLowerCase() === filter);

  function exportCSV() {
    const headers = ['Order ID','Product','Date','Commission (EUR)','Status'];
    const data = TRANSACTIONS.map(t => [
      t.id, t.product, t.date, t.commission.toFixed(2), t.status
    ]);
    const csv = [headers, ...data].map(r => r.map(c => `"${String(c).replace(/"/g,'""')}"`).join(',')).join('\n');
    const blob = new Blob(['﻿'+csv], {type:'text/csv;charset=utf-8'});
    const url  = URL.createObjectURL(blob);
    const a    = Object.assign(document.createElement('a'), {href:url, download:'kyoudai_ganancias.csv'});
    document.body.appendChild(a); a.click();
    document.body.removeChild(a); URL.revokeObjectURL(url);
  }

  return (
    <div className="page-enter" style={{padding: isMobile ? "14px 14px 80px" : "26px 32px 48px"}}>
      <div style={{display:"grid", gridTemplateColumns: isMobile ? "1fr 1fr" : "repeat(3, 1fr)", gap: isMobile ? 10 : 16, marginBottom: isMobile ? 10 : 20}}>
        <StatTile
          label="Total ganado (lifetime)"
          value={USER.totalEarnings || 0} prefix="€" decimals={2}
          tone="#5B8CFF"
          icon={<I.cash style={{width:16,height:16}}/>}
          sub={`${TRANSACTIONS.length} pedidos registrados`}
        />
        <StatTile
          label="Pendiente de cobro"
          value={pending} prefix="€" decimals={2}
          tone="#F6C56B"
          icon={<I.calendar style={{width:16,height:16}}/>}
          sub={`Disponible el ${USER.nextPayout || '1 del mes'}`}
        />
        <StatTile
          label="Pagado"
          value={paid} prefix="€" decimals={2}
          tone="#00E0A4"
          icon={<I.check style={{width:16,height:16}}/>}
          sub={`Vía ${USER.payoutMethod}`}
        />
      </div>

      {pending > 0 && (
        <div className="glass" style={{
          padding:18, marginBottom:20, display:"flex", alignItems:"center", gap:16,
          background:"linear-gradient(135deg, rgba(91,140,255,0.1), rgba(138,91,255,0.06))",
          border:"1px solid rgba(91,140,255,0.25)",
        }}>
          <div style={{
            width:44, height:44, borderRadius:12, display:"grid", placeItems:"center",
            background:"linear-gradient(135deg, #5B8CFF, #8A5BFF)",
            boxShadow:"0 8px 24px -8px rgba(91,140,255,0.6)"
          }}>
            <I.bolt style={{width:20, height:20, color:"#fff"}}/>
          </div>
          <div style={{flex:1}}>
            <div style={{fontSize:14, fontWeight:600}}>Próximo pago</div>
            <div style={{fontSize:12, color:"var(--sub)", marginTop:3}}>
              €{pending.toFixed(2)} se transferirán a {USER.payoutMethod} el {USER.nextPayout || 'día 1 del próximo mes'}.
              Los pedidos se confirman tras 14 días sin devolución.
            </div>
          </div>
        </div>
      )}

      {TRANSACTIONS.length === 0 && (
        <div className="glass" style={{padding:48, textAlign:"center", marginBottom:20}}>
          <div style={{fontSize:40, marginBottom:12}}>📦</div>
          <div style={{fontSize:16, fontWeight:600, marginBottom:8}}>Aún no hay ventas registradas</div>
          <div style={{fontSize:13, color:"var(--sub)", lineHeight:1.6, marginBottom:20}}>
            Cuando alguien compre usando tu link de afiliado, la comisión aparecerá aquí automáticamente.
          </div>
          <button className="btn btn-primary" onClick={() => window.kyoudaiNav && window.kyoudaiNav('products')}>
            <I.bolt style={{width:13,height:13}}/>Ir a productos
          </button>
        </div>
      )}

      {TRANSACTIONS.length > 0 && (
        <div className="glass" style={{overflow:"hidden"}}>
          <div style={{padding: isMobile ? "12px 14px" : "16px 20px", borderBottom:"1px solid var(--line)", display:"flex", flexDirection: isMobile ? "column" : "row", justifyContent:"space-between", alignItems: isMobile ? "flex-start" : "center", gap: isMobile ? 10 : 0}}>
            <div>
              <div style={{fontSize:14, fontWeight:600}}>Transacciones</div>
              <div style={{fontSize:12, color:"var(--sub)", marginTop:2}}>Cada venta vinculada a tu código de referido</div>
            </div>
            <div style={{display:"flex", gap:8, alignItems:"center", flexWrap:"wrap"}}>
              <div className="seg">
                {[{k:"all",l:"Todas"},{k:"pending",l:"Pendiente"},{k:"paid",l:"Pagado"}].map(f => (
                  <button key={f.k} className={filter===f.k?"active":""} onClick={() => setFilter(f.k)}>{f.l}</button>
                ))}
              </div>
              <button className="btn btn-sm" onClick={exportCSV}>
                <I.download style={{width:13, height:13}}/>CSV
              </button>
            </div>
          </div>
          <div style={{overflowX:"auto", WebkitOverflowScrolling:"touch"}}>
          <table>
            <thead><tr>
              <th>Pedido</th><th>Producto</th><th>Fecha</th><th>Comprador</th><th>Comisión</th><th>Estado</th>
            </tr></thead>
            <tbody>
              {rows.map(t => {
                const p = PRODUCTS.find(x => x.id === t.productId);
                return (
                  <tr key={t.id}>
                    <td className="mono" style={{color:"var(--sub)", fontSize:12}}>{t.id}</td>
                    <td>
                      <div style={{display:"flex", alignItems:"center", gap:10}}>
                        <div style={{width:32, flexShrink:0}}>{p && <CardArt product={p}/>}</div>
                        <span style={{fontSize:13}}>{t.product}</span>
                      </div>
                    </td>
                    <td style={{color:"var(--sub)"}}>{t.date}</td>
                    <td className="mono" style={{color:"var(--sub)", fontSize:12}}>{t.buyer}</td>
                    <td><span style={{color:"#3EE8BE", fontWeight:700}}>+€{t.commission.toFixed(2)}</span></td>
                    <td>
                      {t.status === "Paid" ? (
                        <span className="badge" style={{background:"rgba(0,224,164,0.1)", color:"#3EE8BE", border:"1px solid rgba(0,224,164,0.25)"}}>
                          <I.check style={{width:10,height:10}}/>PAGADO
                        </span>
                      ) : (
                        <span className="badge" style={{background:"rgba(246,197,107,0.1)", color:"#F6C56B", border:"1px solid rgba(246,197,107,0.25)"}}>
                          <span style={{width:6, height:6, borderRadius:99, background:"#F6C56B", display:"inline-block", marginRight:4}}/>PENDIENTE
                        </span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          </div>
        </div>
      )}
    </div>
  );
}

window.EarningsPage = EarningsPage;
