<% layout('layouts/main') %>
<% const adminBase = typeof adminBaseUrl !== 'undefined' ? adminBaseUrl : '/admin'; %>
<% const staffBase = typeof staffBaseUrl !== 'undefined' ? staffBaseUrl : '/agenda'; %>
<% const settings = growth.settings || {}; %>
<% const subscription = growth.subscription || {}; %>
<% const onboarding = growth.onboarding || { steps: [], completed: 0, total: 0, progress: 0 }; %>
<% const metrics = growth.metrics || {}; %>
<% const demoReset = growth.demoReset || {}; %>
<% const planLabel = { trial: 'Essai', starter: 'Starter', business: 'Business', premium: 'Premium' }; %>
<% const dnsStatusValue = ({ manuel: 'manual', o2switch_ready: 'dns_assisted', activation_plateforme: 'platform_activation' }[settings.dns_automation_status] || settings.dns_automation_status || 'manual'); %>

<div class="app-shell">
  <%- partial('partials/admin-nav') %>
  <section class="content growth-page">
    <div class="page-head premium-growth-head">
      <div>
        <p class="eyebrow">Suite premium</p>
        <h1>Croissance SaaS</h1>
        <p>Les leviers qui transforment l’espace entreprise en produit premium: onboarding, abonnement, IA, modèles, paiement, PWA, sécurité, démo, domaines et pilotage.</p>
      </div>
      <div class="growth-score">
        <span>Lancement</span>
        <strong><%= onboarding.progress %>%</strong>
      </div>
    </div>

    <section class="growth-overview">
      <article><span>CA mensuel</span><strong><%= ui.money(metrics.monthRevenue) %></strong><small>Factures créées ce mois</small></article>
      <article><span>Encaissement</span><strong><%= ui.money(metrics.paidRevenue) %></strong><small>Paiements enregistrés</small></article>
      <article><span>Conversion devis</span><strong><%= metrics.conversionRate || 0 %>%</strong><small>Devis acceptés / envoyés</small></article>
      <article><span>SLA</span><strong><%= metrics.lateRequests || 0 %></strong><small>Demandes à traiter</small></article>
      <article><span>Terrain</span><strong><%= metrics.fieldHours || 0 %>h</strong><small>Heures terminées ce mois</small></article>
    </section>

    <section class="premium-grid two">
      <article class="panel premium-module" id="onboarding">
        <div class="module-head">
          <span class="module-index">01</span>
          <div><h2>Onboarding guidé</h2><p>Checklist de lancement pour qu’une entreprise démarre sans assistance externe.</p></div>
        </div>
        <div class="progress-track"><span style="width:<%= onboarding.progress %>%"></span></div>
        <div class="launch-checklist">
          <% onboarding.steps.forEach((step) => { %>
            <form method="post" action="<%= adminBase %>/croissance/onboarding" class="launch-step <%= step.done ? 'done' : '' %>">
              <input type="hidden" name="_csrf" value="<%= csrfToken %>">
              <input type="hidden" name="step_id" value="<%= step.id %>">
              <label class="check premium-check">
                <input type="checkbox" name="done" <%= step.done ? 'checked' : '' %> onchange="this.form.submit()">
                <span><strong><%= step.label %></strong><small><%= step.detail %></small></span>
              </label>
              <a class="text-link" href="<%= step.href.replace('/admin', adminBase) %>">Ouvrir</a>
            </form>
          <% }) %>
        </div>
      </article>

      <article class="panel premium-module" id="abonnement">
        <div class="module-head">
          <span class="module-index">02</span>
          <div><h2>Abonnement et paiement</h2><p>Plans, sièges, statut commercial et références de paiement.</p></div>
        </div>
        <div class="subscription-state">
          <strong><%= planLabel[subscription.plan_code] || subscription.plan_code || 'Essai' %></strong>
          <span class="badge"><%= ui.label(subscription.status || 'trialing') %></span>
          <small><%= subscription.monthly_price ? ui.money(subscription.monthly_price) + ' / mois' : 'Essai gratuit' %> · <%= subscription.seats || 3 %> sièges</small>
        </div>
        <form method="post" action="<%= adminBase %>/croissance/abonnement" class="form-grid">
          <input type="hidden" name="_csrf" value="<%= csrfToken %>">
          <div class="form-grid two">
            <label>Plan<select name="plan_code">
              <% ['trial','starter','business','premium'].forEach((plan) => { %><option value="<%= plan %>" <%= subscription.plan_code === plan ? 'selected' : '' %>><%= planLabel[plan] %></option><% }) %>
            </select></label>
            <label>Sièges<input name="seats" inputmode="numeric" value="<%= subscription.seats || 3 %>"></label>
          </div>
          <div class="form-grid two">
            <label>Stripe customer<input name="stripe_customer_id" value="<%= subscription.stripe_customer_id || '' %>" placeholder="cus_..."></label>
            <label>Stripe subscription<input name="stripe_subscription_id" value="<%= subscription.stripe_subscription_id || '' %>" placeholder="sub_..."></label>
          </div>
          <label class="check premium-check"><input type="checkbox" name="status" value="active" <%= subscription.status === 'active' ? 'checked' : '' %>><span><strong>Marquer actif</strong><small>Le statut d’abonnement détermine l’accès aux fonctions premium.</small></span></label>
          <button>Enregistrer l’abonnement</button>
        </form>
      </article>
    </section>

    <section class="premium-grid two">
      <article class="panel premium-module" id="assistant-ia">
        <div class="module-head">
          <span class="module-index">03</span>
          <div><h2>Assistant IA contenu et SEO</h2><p>Génère des brouillons réutilisables dans le Studio et les articles.</p></div>
        </div>
        <form method="post" action="<%= adminBase %>/croissance/ia" class="form-grid">
          <input type="hidden" name="_csrf" value="<%= csrfToken %>">
          <div class="form-grid two">
            <label>Service<input name="service" placeholder="Nettoyage régulier, fin de bail, vitres..."></label>
            <label>Ville / zone<input name="city" placeholder="Lausanne"></label>
          </div>
          <div class="form-grid two">
            <label>Sujet<input name="topic" placeholder="Prestation locale, chantier ou contrat récurrent"></label>
            <label>Ton<input name="tone" value="premium clair"></label>
          </div>
          <button>Générer un brouillon</button>
        </form>
        <% if (growth.aiDraft) { %>
          <div class="ai-draft">
            <strong><%= growth.aiDraft.title %></strong>
            <p><%= growth.aiDraft.intro %></p>
            <small><%= growth.aiDraft.meta %></small>
          </div>
        <% } %>
      </article>

      <article class="panel premium-module">
        <div class="module-head">
          <span class="module-index">04</span>
          <div><h2>Modèle nettoyage</h2><p>Présélection verticale pour lancer ou réinitialiser une vitrine de nettoyage.</p></div>
        </div>
        <div class="preset-grid">
          <% Object.entries(growth.presets).forEach(([id, preset]) => { %>
            <% const presetColors = preset.colors || [preset.primary, preset.secondary]; %>
            <form method="post" action="<%= adminBase %>/croissance/modele-metier" class="preset-card" data-confirm="Appliquer ce modèle en brouillon Studio ?">
              <input type="hidden" name="_csrf" value="<%= csrfToken %>">
              <input type="hidden" name="preset_id" value="<%= id %>">
              <span style="background:<%= presetColors[0] %>"></span>
              <strong><%= preset.label %></strong>
              <small><%= preset.audience %></small>
              <button class="secondary small">Appliquer</button>
            </form>
          <% }) %>
        </div>
      </article>
    </section>

    <section class="premium-grid two">
      <article class="panel premium-module" id="automatisations">
        <div class="module-head">
          <span class="module-index">05</span>
          <div><h2>Signature, paiement et relances</h2><p>Prépare les workflows de vente: devis signé, paiement en ligne, relances SLA.</p></div>
        </div>
        <form method="post" action="<%= adminBase %>/croissance/fonctions" class="form-grid">
          <input type="hidden" name="_csrf" value="<%= csrfToken %>">
          <label class="check premium-check"><input type="checkbox" name="quote_esign_enabled" <%= settings.quote_esign_enabled === 'true' ? 'checked' : '' %>><span><strong>Signature électronique devis</strong><small>Les acceptations client sont historisées avec IP, navigateur et date.</small></span></label>
          <label class="check premium-check"><input type="checkbox" name="payment_links_enabled" <%= settings.payment_links_enabled === 'true' ? 'checked' : '' %>><span><strong>Paiement en ligne</strong><small>L’espace client affiche un bouton de paiement sécurisé sur les factures ouvertes.</small></span></label>
          <label class="check premium-check"><input type="checkbox" name="auto_reminders_enabled" <%= settings.auto_reminders_enabled === 'true' ? 'checked' : '' %>><span><strong>Relances automatiques</strong><small>Organise les relances devis, factures et demandes sans réponse.</small></span></label>
          <div class="form-grid two">
            <label>SLA réponse demande<input name="sla_first_response_hours" inputmode="numeric" value="<%= settings.sla_first_response_hours || '24' %>"></label>
            <label>Relance devis après<input name="sla_quote_followup_days" inputmode="numeric" value="<%= settings.sla_quote_followup_days || '7' %>"></label>
          </div>
          <div class="form-grid two">
            <label>Profil permissions<select name="permission_profile">
              <% ['standard','responsables','strict'].forEach((profile) => { %><option value="<%= profile %>" <%= settings.permission_profile === profile ? 'selected' : '' %>><%= ui.label(profile) %></option><% }) %>
            </select></label>
            <label>DNS / domaine<select name="dns_automation_status">
              <% ['manual','dns_assisted','platform_activation'].forEach((status) => { %><option value="<%= status %>" <%= dnsStatusValue === status ? 'selected' : '' %>><%= ui.label(status) %></option><% }) %>
            </select></label>
          </div>
          <label class="check premium-check"><input type="checkbox" name="white_label_enabled" <%= settings.white_label_enabled === 'true' ? 'checked' : '' %>><span><strong>Marque blanche</strong><small>Adapte l’expérience client autour de la marque de l’entreprise.</small></span></label>
          <button>Enregistrer les workflows</button>
        </form>
      </article>

      <article class="panel premium-module">
        <div class="module-head">
          <span class="module-index">06</span>
          <div><h2>PWA employé terrain</h2><p>Le planning terrain devient installable et utilisable sur mobile.</p></div>
        </div>
        <div class="pwa-preview">
          <span>Installable</span>
          <strong>Agenda terrain</strong>
          <p>Les employés accèdent à leur agenda terrain, complètent les notes, les matériaux utilisés et la signature client depuis une expérience installable.</p>
          <a class="button secondary" href="<%= staffBase %>">Ouvrir l’agenda</a>
        </div>
      </article>
    </section>

    <section class="premium-grid two">
      <article class="panel premium-module">
        <div class="module-head">
          <span class="module-index">07</span>
          <div><h2>Sécurité et audit</h2><p>Journal des actions récentes et profil de permissions.</p></div>
        </div>
        <div class="audit-list">
          <% growth.audit.forEach((event) => { %>
            <div>
              <strong><%= ui.label(event.action) %></strong>
              <span><%= event.first_name || 'Système' %> <%= event.last_name || '' %> · <%= ui.date(event.created_at, true) %></span>
            </div>
          <% }) %>
          <% if (!growth.audit.length) { %><p class="muted">Aucun événement récent.</p><% } %>
        </div>
      </article>

      <article class="panel premium-module" id="demo-reset">
        <div class="module-head">
          <span class="module-index">08</span>
          <div><h2>Reset automatique démo</h2><p>Maintient un environnement de démonstration propre, stable et contrôlé.</p></div>
        </div>
        <form method="post" action="<%= adminBase %>/croissance/demo-reset" class="form-grid">
          <input type="hidden" name="_csrf" value="<%= csrfToken %>">
          <label class="check premium-check"><input type="checkbox" name="enabled" <%= Number(demoReset.enabled || 0) ? 'checked' : '' %>><span><strong>Activer le reset démo</strong><small>La démo est restaurée automatiquement selon l’intervalle choisi.</small></span></label>
          <label>Intervalle en heures<input name="interval_hours" inputmode="numeric" value="<%= demoReset.interval_hours || 24 %>"></label>
          <label>Note interne<textarea name="notes"><%= demoReset.notes || 'Restaurer SaaS DEMO depuis le seed sécurisé.' %></textarea></label>
          <button>Configurer le reset</button>
        </form>
      </article>
    </section>

    <section class="premium-grid two">
      <article class="panel premium-module">
        <div class="module-head">
          <span class="module-index">09</span>
          <div><h2>Domaines et sous-domaines</h2><p>Suivi des URL publiques, domaines personnalisés et statuts d’activation.</p></div>
        </div>
        <div class="domain-mini-list">
          <% growth.domains.forEach((domain) => { %>
            <a href="https://<%= domain.hostname %>" target="_blank" rel="noopener">
              <strong><%= domain.hostname %></strong>
              <span><%= domain.type %> · <%= ui.label(domain.status) %></span>
            </a>
          <% }) %>
          <% if (!growth.domains.length) { %><p class="muted">Aucun domaine ajouté. Configurez-le dans Paramètres.</p><% } %>
        </div>
        <a class="button secondary" href="<%= adminBase %>/parametres">Configurer les domaines</a>
      </article>

      <article class="panel premium-module">
        <div class="module-head">
          <span class="module-index">10</span>
          <div><h2>Dashboards business</h2><p>Indicateurs pour piloter la croissance et justifier l’abonnement.</p></div>
        </div>
        <div class="business-metrics">
          <div><span>Impayés</span><strong><%= ui.money(metrics.unpaidTotal) %></strong><small><%= metrics.unpaidCount || 0 %> facture(s)</small></div>
          <div><span>Devis à relancer</span><strong><%= metrics.overdueQuotes || 0 %></strong><small>Plus de 7 jours</small></div>
          <div><span>Demandes totales</span><strong><%= metrics.requests || 0 %></strong><small>Base commerciale</small></div>
          <div><span>Interventions</span><strong><%= metrics.interventionsDone || 0 %></strong><small>Terminées ce mois</small></div>
        </div>
        <div class="actions inline-actions">
          <a class="button secondary" href="<%= adminBase %>/conversions">Conversions</a>
          <a class="button secondary" href="<%= adminBase %>/pipeline">Pipeline</a>
        </div>
      </article>
    </section>
  </section>
</div>
