// My Links
function LinksPage(){
  const { LINKS, PRODUCTS, USER } = window.KYOUDAI;
  const isMobile = window.useIsMobile();

  const totalClicks = LINKS.reduce((s,l) => s+l.clicks, 0);
  const totalConv   = LINKS.reduce((s,l) => s+l.conversions, 0);
  const totalEarn   = LINKS.reduce((s,l) => s+l.earnings, 0);
  const avgCvr      = totalClicks > 0 ? (totalConv/totalClicks*100) : 0;

  function openLink(url) {
    window.open(url, '_blank', 'noopener,noreferrer');
  }

  return (
    <div className="page-enter" style={{padding: isMobile ? "14px 14px 80px" : "26px 32px 48px"}}>
      <div style={{display:"grid", gridTemplateColumns: isMobile ? "repeat(2,1fr)" : "repeat(4, 1fr)", gap: isMobile ? 10 : 16, marginBottom: isMobile ? 10 : 20}}>
        <StatTile label="Links activos" value={LINKS.length} tone="#5B8CFF" icon={<I.link style={{width:16,height:16}}/>}/>
        <StatTile label="Total clicks" value={totalClicks} tone="#8A5BFF" icon={<I.eye style={{width:16,height:16}}/>}/>
        <StatTile label="Conversiones" value={totalConv} tone="#00E0A4" icon={<I.trend style={{width:16,height:16}}/>}/>
        <StatTile label="CVR medio" value={avgCvr} suffix="%" decimals={1} tone="#F6C56B" icon={<I.sparkle style={{width:16,height:16}}/>}/>
      </div>

      <div className="glass" style={{padding:16, marginBottom:20, display:"flex", alignItems:"center", gap:12}}>
        <div style={{
          width:36, height:36, borderRadius:10, display:"grid", placeItems:"center",
          background:"rgba(91,140,255,0.12)", border:"1px solid rgba(91,140,255,0.3)", color:"#8AB0FF"
        }}>
          <I.plus style={{width:16, height:16}}/>
        </div>
        <div style={{flex:1}}>
          <div style={{fontSize:13, fontWeight:600}}>Genera un link de afiliado</div>
          <div style={{fontSize:11, color:"var(--sub)", marginTop:2}}>
            Cada producto ya tiene tu link único con el código <span className="mono" style={{color:"#8AB0FF"}}>{USER.referral}</span>
          </div>
        </div>
        <button className="btn btn-primary" onClick={() => window.kyoudaiNav && window.kyoudaiNav('products')}>
          Ver productos<I.chevron style={{width:11, height:11}}/>
        </button>
      </div>

      <div className="glass" style={{overflow:"hidden"}}>
        <div style={{overflowX:"auto", WebkitOverflowScrolling:"touch"}}>
        <table style={{minWidth: isMobile ? 520 : undefined}}>
          <thead><tr>
            <th>Producto</th>
            <th>Link</th>
            <th style={{textAlign:"right"}}>Clicks</th>
            <th style={{textAlign:"right"}}>Conv.</th>
            <th style={{textAlign:"right"}}>CVR</th>
            <th style={{textAlign:"right"}}>Ganancias</th>
            <th></th>
          </tr></thead>
          <tbody>
            {LINKS.map(l => {
              const p = PRODUCTS.find(x => x.id === l.productId);
              if (!p) return null;
              const url = l.url || `${window.KYOUDAI_CONFIG.shopUrl}/products/${p.slug}?ref=${USER.referral}`;
              const displayUrl = l.displayUrl || url;
              const cvr = l.clicks > 0 ? (l.conversions/l.clicks*100).toFixed(1) : "0.0";
              return (
                <tr key={l.id}>
                  <td>
                    <div style={{display:"flex", alignItems:"center", gap:10}}>
                      <div style={{width:36, flexShrink:0}}><CardArt product={p}/></div>
                      <div>
                        <div style={{fontSize:13, fontWeight:600}}>{p.name}</div>
                        <div className="mono" style={{fontSize:10, color:"var(--sub)", marginTop:2}}>Creado {l.created}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{maxWidth:260}}>
                    <div className="mono" style={{
                      fontSize:11, color:"var(--sub)",
                      padding:"7px 10px", borderRadius:8,
                      background:"rgba(255,255,255,0.02)", border:"1px solid var(--line)",
                      overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap",
                    }}>
                      {displayUrl}
                    </div>
                  </td>
                  <td className="mono" style={{textAlign:"right"}}>{l.clicks.toLocaleString()}</td>
                  <td className="mono" style={{textAlign:"right"}}>{l.conversions}</td>
                  <td className="mono" style={{textAlign:"right", color: parseFloat(cvr) > 3 ? "#3EE8BE" : "var(--sub)"}}>{cvr}%</td>
                  <td style={{textAlign:"right", fontWeight:700, color:"#3EE8BE"}}>€{l.earnings.toFixed(2)}</td>
                  <td style={{textAlign:"right"}}>
                    <div style={{display:"inline-flex", gap:6}}>
                      <CopyButton text={url} label="" icon={true} toastMsg="Link copiado"/>
                      <button className="btn btn-sm" title="Abrir en Shopify" onClick={() => openLink(url)}>
                        <I.external style={{width:13, height:13}}/>
                      </button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        </div>
        {LINKS.length === 0 && (
          <div style={{padding:40, textAlign:"center", color:"var(--sub)", fontSize:13}}>
            Aún no hay links generados. Los links se crean automáticamente al activar tu cuenta.
          </div>
        )}
      </div>
    </div>
  );
}

window.LinksPage = LinksPage;
