<%- include('../partials/head', { title, bodyClass: 'app-page affiliate-dashboard-page' }) %>
<%- include('../partials/app-header') %>

<%
  const profile = dashboard.profile;
  const summary = dashboard.summary || {};
  const referralsPage = dashboard.referrals || { rows: [], page: 1, totalPages: 1, total: 0 };
  const commissionsPage = dashboard.commissions || { rows: [], page: 1, totalPages: 1, total: 0 };
  const clicksPage = dashboard.clicks || { rows: [], page: 1, totalPages: 1, total: 0 };
  const selectedDays = Number(dashboard.dailyDays || 30);
  const activeReferrals = Number(summary.activeReferrals || 0);
  const tiers = [
    { range: '1 à 3 PRO actifs', rate: 20, min: 1 },
    { range: '4 à 9 PRO actifs', rate: 25, min: 4 },
    { range: '10 à 19 PRO actifs', rate: 30, min: 10 },
    { range: '20+ PRO actifs', rate: 40, min: 20 }
  ];
  const currentTier = tiers.slice().reverse().find((tier) => activeReferrals >= tier.min) || null;
  const nextTier = tiers.find((tier) => activeReferrals < tier.min);
  const link = profile ? `${baseUrl}/r/${profile.slug}` : '';
  const affiliateUrl = (params = {}) => {
    const query = {
      jours: selectedDays,
      filleuls_page: referralsPage.page || 1,
      commissions_page: commissionsPage.page || 1,
      clics_page: clicksPage.page || 1,
      ...params
    };
    const search = Object.entries(query)
      .filter((entry) => entry[1] !== null && typeof entry[1] !== 'undefined' && entry[1] !== '')
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');
    return `/affiliation${search ? `?${search}` : ''}`;
  };
  const pageLabel = (page) => `Page ${page.page || 1} / ${page.totalPages || 1}`;
  const percent = (value) => `${Number(value || 0).toLocaleString('es-ES', { maximumFractionDigits: 1 })}%`;
  const shortHash = (value) => value ? `${String(value).slice(0, 8)}...` : 'Non identifié';
  const cleanSource = (value) => {
    if (!value) return 'Accès direct';
    try {
      const parsed = new URL(value);
      return parsed.hostname.replace(/^www\./, '');
    } catch (error) {
      return String(value).slice(0, 42);
    }
  };
  const deviceLabel = (ua) => {
    const text = String(ua || '').toLowerCase();
    if (!text) return 'Inconnu';
    if (text.includes('iphone') || text.includes('android') || text.includes('mobile')) return 'Mobile';
    if (text.includes('ipad') || text.includes('tablet')) return 'Tablette';
    return 'Desktop';
  };
  const statusLabel = (status, isProActive) => {
    if (isProActive) return 'PRO actif';
    if (status === 'active') return 'PRO actif';
    return 'Gratis';
  };
  const commissionStatusLabel = (status) => ({
    payable: 'À payer',
    paid: 'Payé',
    reversed: 'Annulé'
  }[status] || 'À suivre');
%>

<main class="app-main affiliate-page affiliate-dashboard-shell">
  <% if (!profile) { %>
    <section class="affiliate-hero affiliate-hero-card">
      <div>
        <p class="eyebrow">Affiliation TopStats</p>
        <h1>Transformez vos recommandations en revenus récurrents.</h1>
        <p>Créez votre lien personnalisé, partagez votre code promo et touchez une commission sur les abonnements de vos filleuls actifs.</p>
      </div>
      <span class="affiliate-status-pill">Ouvert à tous les membres</span>
    </section>

    <section class="affiliate-primer">
      <article>
        <span>01</span>
        <strong>Vous choisissez votre code</strong>
        <p>Exemple : ALLAN devient le lien /r/ALLAN et le code promo ALLAN10.</p>
      </article>
      <article>
        <span>02</span>
        <strong>TopStats rattache les inscrits</strong>
        <p>Le dernier clic avant inscription est retenu pour attribuer le filleul correctement.</p>
      </article>
      <article>
        <span>03</span>
        <strong>Vous suivez vos gains</strong>
        <p>Clics, inscriptions, PRO actifs, revenus générés et commissions sont centralisés ici.</p>
      </article>
    </section>

    <section class="affiliate-tier-card glass-panel">
      <div class="affiliate-tier-head">
        <div>
          <p class="eyebrow">Taux évolutif</p>
          <h2>Plus vos filleuls actifs grandissent, plus votre commission augmente.</h2>
        </div>
        <p>Le taux est calculé sur le nombre total de filleuls PRO actifs. Les commissions sont calculées sur le net encaissé, puis payées le 5 du mois suivant.</p>
      </div>
      <div class="affiliate-tier-grid">
        <% tiers.forEach((tier) => { %>
          <article>
            <small><%= tier.range %></small>
            <strong><%= tier.rate %>%</strong>
            <span>sur les abonnements actifs</span>
          </article>
        <% }) %>
      </div>
    </section>

    <section class="affiliate-create-card glass-panel">
      <div>
        <p class="eyebrow">Crear mi espacio</p>
        <h2>Votre dashboard affilié sera prêt immédiatement.</h2>
        <p>Choisissez un code court, lisible et facile à partager. Si le code est déjà pris, TopStats vous demandera d’en choisir un autre.</p>
      </div>
      <form method="post" action="/affiliation/profile" class="affiliate-create-form">
        <label for="affiliate_code">Code souhaité</label>
        <div>
          <input id="affiliate_code" type="text" name="code" placeholder="ALLAN" minlength="3" maxlength="24" autocomplete="off" required>
          <button class="btn btn-primary" type="submit">Crear mi enlace</button>
        </div>
      </form>
    </section>
  <% } else { %>
    <section class="affiliate-hero affiliate-hero-card">
      <div>
        <p class="eyebrow">Dashboard affiliation</p>
        <h1>Pilotez vos clics, filleuls et commissions.</h1>
        <p>Suivez chaque étape du tunnel : clics, inscriptions, passages PRO, revenus encaissés et commissions à recevoir.</p>
      </div>
      <span class="affiliate-status-pill"><%= summary.rate || 0 %>% de commission actuelle</span>
    </section>

    <section class="affiliate-kpi-grid" aria-label="Indicateurs affiliation">
      <article class="affiliate-kpi-card">
        <span>Clics</span>
        <strong><%= Number(summary.clicks || 0).toLocaleString('es-ES') %></strong>
        <small><%= Number(summary.uniqueClicks || 0).toLocaleString('es-ES') %> visiteurs identifiés</small>
      </article>
      <article class="affiliate-kpi-card">
        <span>Inscrits</span>
        <strong><%= Number(summary.totalReferrals || 0).toLocaleString('es-ES') %></strong>
        <small><%= percent(summary.conversionRate) %> de conversion clic → compte</small>
      </article>
      <article class="affiliate-kpi-card">
        <span>PRO actifs</span>
        <strong><%= activeReferrals.toLocaleString('es-ES') %></strong>
        <small><%= nextTier ? `${Math.max(0, nextTier.min - activeReferrals)} avant ${nextTier.rate}%` : 'Palier maximum atteint' %></small>
      </article>
      <article class="affiliate-kpi-card">
        <span>Revenu généré</span>
        <strong><%= formatEuroCents(summary.totalRevenueCents || 0) %></strong>
        <small>Net encaissé par TopStats</small>
      </article>
      <article class="affiliate-kpi-card">
        <span>Ce mois-ci</span>
        <strong><%= formatEuroCents(summary.monthCents || 0) %></strong>
        <small>Commission estimée du mois</small>
      </article>
      <article class="affiliate-kpi-card">
        <span>Total commissions</span>
        <strong><%= formatEuroCents(summary.totalCents || 0) %></strong>
        <small><%= formatEuroCents(summary.paidCents || 0) %> déjà payé</small>
      </article>
    </section>

    <section class="affiliate-dashboard-layout">
      <article class="affiliate-share-card glass-panel">
        <p class="eyebrow">Votre lien</p>
        <h2><%= profile.slug %></h2>
        <div class="affiliate-copy-row">
          <div class="affiliate-copy-box" data-affiliate-link><%= link %></div>
          <button class="btn btn-primary btn-small" type="button" data-copy-affiliate="<%= link %>">Copier</button>
        </div>
        <div class="affiliate-code-row">
          <span>Code promo</span>
          <strong><%= profile.promo_code %></strong>
          <small>-10% sur le premier paiement du filleul</small>
        </div>
      </article>

      <article class="affiliate-progress-card glass-panel">
        <p class="eyebrow">Palier actuel</p>
        <h2><%= currentTier ? currentTier.rate : 0 %>%</h2>
        <p><%= currentTier ? currentTier.range : 'Activez votre premier filleul PRO' %></p>
        <div class="affiliate-progress-bar">
          <span style="width: <%= Math.min(100, Math.max(6, activeReferrals >= 20 ? 100 : (activeReferrals / 20) * 100)) %>%"></span>
        </div>
        <small><%= nextTier ? `${nextTier.min} PRO actifs pour passer à ${nextTier.rate}%` : 'Vous êtes sur le meilleur palier.' %></small>
      </article>
    </section>

    <section class="affiliate-panel glass-panel">
      <div class="affiliate-panel-head">
        <div>
          <p class="eyebrow">Stats par jour</p>
          <h2>Performance quotidienne</h2>
          <p>Clics, inscriptions, passages PRO et commissions sur la période choisie.</p>
        </div>
        <div class="affiliate-range-tabs" aria-label="Période">
          <% [7, 30, 90].forEach((days) => { %>
            <a class="<%= selectedDays === days ? 'active' : '' %>" href="<%= affiliateUrl({ jours: days }) %>"><%= days %> jours</a>
          <% }) %>
        </div>
      </div>

      <div class="affiliate-table-wrap affiliate-daily-table">
        <table>
          <thead>
            <tr>
              <th>Jour</th>
              <th>Clics</th>
              <th>Visiteurs</th>
              <th>Inscrits</th>
              <th>PRO</th>
              <th>Revenu généré</th>
              <th>Commission</th>
            </tr>
          </thead>
          <tbody>
            <% if (!(dashboard.dailyStats || []).length) { %>
              <tr><td colspan="7">No hay datos en este periodo.</td></tr>
            <% } %>
            <% (dashboard.dailyStats || []).forEach((day) => { %>
              <tr>
                <td><strong><%= formatDate(day.day) %></strong></td>
                <td><%= day.clicks || 0 %></td>
                <td><%= day.uniqueClicks || 0 %></td>
                <td><%= day.signups || 0 %></td>
                <td><%= day.newPros || 0 %></td>
                <td><%= formatEuroCents(day.revenueCents || 0) %></td>
                <td><strong><%= formatEuroCents(day.commissionCents || 0) %></strong></td>
              </tr>
            <% }) %>
          </tbody>
        </table>
      </div>
    </section>

    <section class="affiliate-panel glass-panel">
      <div class="affiliate-panel-head">
        <div>
          <p class="eyebrow">Clics</p>
          <h2>Trafic affilié</h2>
          <p>Chaque visite sur votre lien est enregistrée pour comprendre vos sources et votre conversion.</p>
        </div>
        <span class="affiliate-table-count"><%= clicksPage.total || 0 %> clic<%= Number(clicksPage.total || 0) > 1 ? 's' : '' %></span>
      </div>

      <% if ((clicksPage.rows || []).length) { %>
        <div class="affiliate-table-wrap affiliate-desktop-table">
          <table>
            <thead>
              <tr>
                <th>Date</th>
                <th>Source</th>
                <th>Page</th>
                <th>Visiteur</th>
                <th>Appareil</th>
              </tr>
            </thead>
            <tbody>
              <% clicksPage.rows.forEach((click) => { %>
                <tr>
                  <td><%= formatDateTime(click.clicked_at) %></td>
                  <td><%= cleanSource(click.referer) %></td>
                  <td><%= click.landing_path || '/r/' + profile.slug %></td>
                  <td><%= shortHash(click.ip_hash) %></td>
                  <td><%= deviceLabel(click.user_agent) %></td>
                </tr>
              <% }) %>
            </tbody>
          </table>
        </div>
        <div class="affiliate-mobile-list">
          <% clicksPage.rows.forEach((click) => { %>
            <article>
              <div>
                <strong><%= cleanSource(click.referer) %></strong>
                <span><%= formatDateTime(click.clicked_at) %></span>
              </div>
              <p><%= click.landing_path || '/r/' + profile.slug %></p>
              <small><%= deviceLabel(click.user_agent) %> · <%= shortHash(click.ip_hash) %></small>
            </article>
          <% }) %>
        </div>
        <nav class="affiliate-pagination" aria-label="Pagination clics">
          <% if (clicksPage.page > 1) { %>
            <a class="btn btn-soft btn-small" href="<%= affiliateUrl({ clics_page: clicksPage.page - 1 }) %>">Précédent</a>
          <% } %>
          <span><%= pageLabel(clicksPage) %></span>
          <% if (clicksPage.page < clicksPage.totalPages) { %>
            <a class="btn btn-soft btn-small" href="<%= affiliateUrl({ clics_page: clicksPage.page + 1 }) %>">Suivant</a>
          <% } %>
        </nav>
      <% } else { %>
        <p class="affiliate-empty">No hay clics guardados por ahora.</p>
      <% } %>
    </section>

    <section class="affiliate-panel glass-panel">
      <div class="affiliate-panel-head">
        <div>
          <p class="eyebrow">Filleuls</p>
          <h2>Cuentas referidas</h2>
          <p>Suivez les inscrits rattachés à votre lien ou à votre code promo.</p>
        </div>
        <span class="affiliate-table-count"><%= referralsPage.total || 0 %> inscrit<%= Number(referralsPage.total || 0) > 1 ? 's' : '' %></span>
      </div>

      <% if ((referralsPage.rows || []).length) { %>
        <div class="affiliate-table-wrap affiliate-desktop-table">
          <table>
            <thead>
              <tr>
                <th>Client</th>
                <th>Statut</th>
                <th>Source</th>
                <th>Registro</th>
                <th>Commission totale</th>
              </tr>
            </thead>
            <tbody>
              <% referralsPage.rows.forEach((referral) => { %>
                <tr>
                  <td>
                    <strong><%= referral.referred_name || 'Client TopStats' %></strong><br>
                    <small><%= referral.referred_email %></small>
                  </td>
                  <td><span class="affiliate-status-badge <%= referral.is_pro_active ? 'is-pro' : 'is-free' %>"><%= statusLabel(referral.subscription_status, referral.is_pro_active) %></span></td>
                  <td><%= referral.source || 'Lien' %></td>
                  <td><%= formatDate(referral.created_at) %></td>
                  <td><%= formatEuroCents(referral.total_commission_cents || 0) %></td>
                </tr>
              <% }) %>
            </tbody>
          </table>
        </div>
        <div class="affiliate-mobile-list">
          <% referralsPage.rows.forEach((referral) => { %>
            <article>
              <div>
                <strong><%= referral.referred_name || 'Client TopStats' %></strong>
                <span class="affiliate-status-badge <%= referral.is_pro_active ? 'is-pro' : 'is-free' %>"><%= statusLabel(referral.subscription_status, referral.is_pro_active) %></span>
              </div>
              <p><%= referral.referred_email %></p>
              <small><%= formatDate(referral.created_at) %> · <%= formatEuroCents(referral.total_commission_cents || 0) %></small>
            </article>
          <% }) %>
        </div>
        <nav class="affiliate-pagination" aria-label="Pagination filleuls">
          <% if (referralsPage.page > 1) { %>
            <a class="btn btn-soft btn-small" href="<%= affiliateUrl({ filleuls_page: referralsPage.page - 1 }) %>">Précédent</a>
          <% } %>
          <span><%= pageLabel(referralsPage) %></span>
          <% if (referralsPage.page < referralsPage.totalPages) { %>
            <a class="btn btn-soft btn-small" href="<%= affiliateUrl({ filleuls_page: referralsPage.page + 1 }) %>">Suivant</a>
          <% } %>
        </nav>
      <% } else { %>
        <p class="affiliate-empty">No hay referidos por ahora.</p>
      <% } %>
    </section>

    <section class="affiliate-panel glass-panel">
      <div class="affiliate-panel-head">
        <div>
          <p class="eyebrow">Commissions</p>
          <h2>Paiements et renouvellements</h2>
          <p>Chaque paiement affilié, nouveau ou renouvelé, apparaît ici avec le taux appliqué.</p>
        </div>
        <span class="affiliate-table-count"><%= commissionsPage.total || 0 %> ligne<%= Number(commissionsPage.total || 0) > 1 ? 's' : '' %></span>
      </div>

      <% if ((commissionsPage.rows || []).length) { %>
        <div class="affiliate-table-wrap affiliate-desktop-table">
          <table>
            <thead>
              <tr>
                <th>Date</th>
                <th>Client</th>
                <th>Pack</th>
                <th>Revenu net</th>
                <th>Taux</th>
                <th>Commission</th>
                <th>Statut</th>
              </tr>
            </thead>
            <tbody>
              <% commissionsPage.rows.forEach((commission) => { %>
                <tr>
                  <td><%= formatDate(commission.created_at) %></td>
                  <td><%= commission.referred_name || commission.referred_email || 'Client TopStats' %></td>
                  <td><%= commission.plan || 'PRO' %></td>
                  <td><%= formatEuroCents(commission.net_amount_cents || 0) %></td>
                  <td><%= commission.commission_rate || 0 %>%</td>
                  <td><strong><%= formatEuroCents(commission.commission_amount_cents || 0) %></strong></td>
                  <td><span class="affiliate-status-badge"><%= commissionStatusLabel(commission.status) %></span></td>
                </tr>
              <% }) %>
            </tbody>
          </table>
        </div>
        <div class="affiliate-mobile-list">
          <% commissionsPage.rows.forEach((commission) => { %>
            <article>
              <div>
                <strong><%= formatEuroCents(commission.commission_amount_cents || 0) %></strong>
                <span><%= commissionStatusLabel(commission.status) %></span>
              </div>
              <p><%= commission.referred_name || commission.referred_email || 'Client TopStats' %> · <%= commission.plan || 'PRO' %></p>
              <small><%= formatDate(commission.created_at) %> · <%= commission.commission_rate || 0 %>% sur <%= formatEuroCents(commission.net_amount_cents || 0) %></small>
            </article>
          <% }) %>
        </div>
        <nav class="affiliate-pagination" aria-label="Pagination commissions">
          <% if (commissionsPage.page > 1) { %>
            <a class="btn btn-soft btn-small" href="<%= affiliateUrl({ commissions_page: commissionsPage.page - 1 }) %>">Précédent</a>
          <% } %>
          <span><%= pageLabel(commissionsPage) %></span>
          <% if (commissionsPage.page < commissionsPage.totalPages) { %>
            <a class="btn btn-soft btn-small" href="<%= affiliateUrl({ commissions_page: commissionsPage.page + 1 }) %>">Suivant</a>
          <% } %>
        </nav>
      <% } else { %>
        <p class="affiliate-empty">No hay comisiones guardadas por ahora.</p>
      <% } %>
    </section>

    <section class="affiliate-payout-card glass-panel">
      <div>
        <p class="eyebrow">Paiement</p>
        <h2>Coordonnées de virement</h2>
        <p>Les commissions validées sont payées le 5 du mois suivant. Les informations bancaires restent limitées côté affichage client.</p>
        <% if (dashboard.payoutMethod) { %>
          <p class="affiliate-bank-preview"><%= dashboard.payoutMethod.account_holder || 'Titulaire enregistré' %> · <%= dashboard.payoutMethod.iban_masked %></p>
        <% } %>
      </div>
      <form method="post" action="/affiliation/payout" class="form-grid">
        <label>
          Titulaire du compte
          <input type="text" name="account_holder" value="<%= dashboard.payoutMethod?.account_holder || '' %>" autocomplete="name" required>
        </label>
        <label>
          IBAN
          <input type="text" name="iban" value="" placeholder="<%= dashboard.payoutMethod?.iban_masked || 'ES91...' %>" autocomplete="off">
        </label>
        <label>
          BIC
          <input type="text" name="bic" value="<%= dashboard.payoutMethod?.bic || '' %>" autocomplete="off">
        </label>
        <label>
          Pays
          <input type="text" name="country" value="<%= dashboard.payoutMethod?.country || '' %>" autocomplete="country-name">
        </label>
        <label class="span-2">
          Adresse
          <textarea name="address" rows="3"><%= dashboard.payoutMethod?.address || '' %></textarea>
        </label>
        <button class="btn btn-primary span-2" type="submit">Enregistrer mes informations</button>
      </form>
    </section>
  <% } %>
</main>

<script>
  document.querySelectorAll('[data-copy-affiliate]').forEach((button) => {
    button.addEventListener('click', async () => {
      const value = button.getAttribute('data-copy-affiliate') || '';
      try {
        await navigator.clipboard.writeText(value);
        const previous = button.textContent;
        button.textContent = 'Copié';
        button.disabled = true;
        setTimeout(() => {
          button.textContent = previous;
          button.disabled = false;
        }, 1400);
      } catch (error) {
        button.textContent = 'À copier';
      }
    });
  });
</script>

<%- include('../partials/bottom-nav', { active: 'profil' }) %>
<%- include('../partials/footer') %>
