<div class="page" id="page-profile">
  <div class="ph"><div><div class="pt">Mi perfil</div><div class="ps">Gestiona tu cuenta</div></div></div>
  <div class="cfg-card">
    <div class="chd"><div class="ctit">Información de cuenta</div></div>
    <div style="display:flex;align-items:center;gap:14px;margin-bottom:18px">
      <div style="width:48px;height:48px;border-radius:50%;background:<?= htmlspecialchars($user['color']) ?>;display:flex;align-items:center;justify-content:center;font-family:var(--fh);font-weight:700;font-size:18px;color:#fff"><?= strtoupper(substr($user['name'],0,2)) ?></div>
      <div><div style="font-family:var(--fh);font-size:15px;font-weight:700"><?= htmlspecialchars($user['name']) ?></div><div style="font-size:12px;color:var(--m)"><?= htmlspecialchars($user['email']) ?> · <?= $user['role']==='admin'?'Administrador':'Cliente' ?></div></div>
    </div>
    <form method="POST" action="api/update-profile.php">
      <div class="mf"><label>Nombre</label><input type="text" name="name" value="<?= htmlspecialchars($user['name']) ?>" required></div>
      <div class="mf"><label>Email <span style="color:var(--m);font-weight:400">(cambiar requiere verificación por link al nuevo email)</span></label><input type="email" name="new_email" placeholder="Nuevo email (opcional)" autocomplete="email"></div>
      <div class="mf"><label>Contraseña actual <span style="color:var(--m);font-weight:400">(obligatoria si cambias email o contraseña)</span></label><input type="password" name="current_password" placeholder="Tu contraseña actual" autocomplete="current-password"></div>
      <div class="mf"><label>Nueva contraseña (dejar vacío para no cambiar)</label><input type="password" name="password" placeholder="Nueva contraseña (mín 8 caracteres)" autocomplete="new-password"></div>
      <div class="mf"><label>Confirmar nueva contraseña</label><input type="password" name="password2" placeholder="Repite la contraseña" autocomplete="new-password"></div>
      <button type="submit" class="pr-btn">Guardar cambios</button>
      <span id="profile-msg" style="font-size:12px;margin-left:10px"></span>
    </form>
  </div>

  <!-- Suscripción & Facturación -->
  <div class="cfg-card" id="billing-card">
    <div class="chd"><div class="ctit">Mi suscripción</div></div>
    <?php if ($user['role'] === 'admin'): ?>
    <div style="font-size:13px;color:var(--m);padding:10px 0">✦ Cuenta administrador — acceso completo sin suscripción.</div>
    <?php else: ?>
    <div id="billing-info" style="font-size:13px;color:var(--m)">Cargando...</div>
    <div id="cancel-banner" style="display:none;padding:10px 14px;border-radius:8px;font-size:13px;margin-top:12px;background:rgba(245,197,67,.08);border:1px solid rgba(245,197,67,.25);color:var(--y)"></div>
    <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px">
      <button data-click="_scShow|upgrade-modal|flex" class="pr-btn" style="background:var(--p)">⬆ Cambiar plan</button>
      <button data-click="openBillingPortal" class="pr-btn" style="background:var(--bg3);border:1px solid var(--br2);color:var(--t)">💳 Gestionar pago</button>
      <button data-click="requestImplementation" class="pr-btn" style="background:rgba(13,207,207,.15);border:1px solid rgba(13,207,207,.35);color:var(--teal)">🛠 Solicitar implementación</button>
      <button id="btn-cancel-sub" data-click="openCancelModal" class="pr-btn" style="display:none;background:rgba(232,39,42,.1);border:1px solid rgba(232,39,42,.3);color:var(--red)">✕ Cancelar suscripción</button>
      <button id="btn-reactivate-sub" data-click="reactivateSubscription" class="pr-btn" style="display:none;background:rgba(34,201,122,.1);border:1px solid rgba(34,201,122,.3);color:var(--g)">↩ Reactivar suscripción</button>
    </div>
    <!-- Cancel confirmation modal -->
    <div id="modal-cancel-sub" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.75);z-index:700;align-items:center;justify-content:center" data-closeifback="_scCancelSubHide">
      <div style="background:var(--bg2);border:1px solid rgba(232,39,42,.3);border-radius:14px;width:420px;max-width:95vw;padding:24px">
        <div style="font-size:16px;font-weight:700;margin-bottom:10px;font-family:var(--fh)">¿Cancelar suscripción?</div>
        <p style="font-size:13px;color:var(--m);margin-bottom:6px">Tu suscripción <strong style="color:var(--t)">se mantendrá activa hasta el final del ciclo de facturación actual</strong>. No habrá cargos adicionales.</p>
        <p id="cancel-modal-date" style="font-size:13px;color:var(--y);margin-bottom:20px"></p>
        <div style="display:flex;gap:10px;justify-content:flex-end">
          <button data-click="_scHide|modal-cancel-sub" class="pr-btn" style="background:var(--bg3);border:1px solid var(--br2);color:var(--t)">Mantener suscripción</button>
          <button data-click="confirmCancelSubscription" class="pr-btn" style="background:var(--red);border:none;color:#fff">Cancelar al final del ciclo</button>
        </div>
      </div>
    </div>
    <?php endif; ?>
  </div>
  <?php
  $sub_profile = function_exists('dm_get_subscription') ? dm_get_subscription((int)$user['id']) : null;
  $is_starter  = $sub_profile && $sub_profile['plan'] === 'starter';
  $mods_set    = $is_starter && !empty($sub_profile['modules_chosen']);
  ?>
  <?php if ($is_starter && $user['role'] !== 'admin'): ?>
  <div class="cfg-card" id="module-selector-card" style="<?= !$mods_set ? 'border-color:rgba(147,51,234,.4);background:rgba(147,51,234,.04)' : '' ?>">
    <div class="chd">
      <div class="ctit">Mis módulos (Starter)</div>
      <?php if (!$mods_set): ?><span style="font-size:11px;font-weight:600;color:#c084fc;background:rgba(147,51,234,.15);padding:2px 8px;border-radius:10px">⚡ Pendiente</span><?php endif ?>
    </div>
    <p style="font-size:13px;color:var(--m);margin-bottom:14px">
      <?= $mods_set ? 'Módulos activos. Puedes cambiarlos en cualquier momento.' : 'Plan Starter incluye <strong style="color:var(--t)">3 módulos</strong> — elige cuáles quieres usar.' ?>
    </p>
    <?php
    $all_mods = [
      'meta_ads'     => ['◉', 'Meta Ads'],
      'google_ads'   => ['◎', 'Google Ads'],
      'tiktok_ads'   => ['🎵', 'TikTok Ads'],
      'seo'          => ['◐', 'SEO'],
      'email'        => ['📧', 'Email Marketing'],
      'web'          => ['🌐', 'Sitios Web'],
      'videos'       => ['🎬', 'Videos IA'],
      'images'       => ['🖼', 'Imágenes IA'],
      'reports'      => ['📊', 'Reportes'],
      'brand'        => ['🎨', 'Activos de Marca'],
      'automations'  => ['⚡', 'Automatizaciones'],
    ];
    $cur_mods = $sub_profile['modules_chosen'] ?? [];
    ?>
    <div id="module-grid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:8px;margin-bottom:14px">
      <?php foreach ($all_mods as $key => [$icon, $label]): ?>
      <button type="button" data-click="toggleMod|__el|<?= $key ?>"
        class="mod-btn<?= in_array($key,$cur_mods)?' mod-active':'' ?>"
        data-mod="<?= $key ?>"
        style="padding:9px 10px;border-radius:8px;font-size:12px;cursor:pointer;text-align:left;display:flex;align-items:center;gap:7px;
          <?= in_array($key,$cur_mods) ? 'background:rgba(147,51,234,.2);border:1px solid rgba(147,51,234,.5);color:#c084fc;font-weight:600' : 'background:var(--bg3);border:1px solid var(--br2);color:var(--m)' ?>">
        <span><?= $icon ?></span><span><?= $label ?></span>
      </button>
      <?php endforeach ?>
    </div>
    <div style="display:flex;align-items:center;gap:12px">
      <button data-click="saveModules" class="pr-btn" style="background:var(--p)">Guardar módulos</button>
      <span id="mod-count" style="font-size:12px;color:var(--m)"><?= count($cur_mods) ?>/3 elegidos</span>
      <span id="mod-msg" style="font-size:12px;color:var(--teal)"></span>
    </div>
  </div>
  <script>
  function toggleMod(btn,key){
    const active=document.querySelectorAll('.mod-active');
    if(btn.classList.contains('mod-active')){
      btn.classList.remove('mod-active');
      btn.style.cssText='padding:9px 10px;border-radius:8px;font-size:12px;cursor:pointer;text-align:left;display:flex;align-items:center;gap:7px;background:var(--bg3);border:1px solid var(--br2);color:var(--m)';
    } else {
      if(active.length>=3){document.getElementById('mod-msg').textContent='Máximo 3 módulos.';return;}
      btn.classList.add('mod-active');
      btn.style.cssText='padding:9px 10px;border-radius:8px;font-size:12px;cursor:pointer;text-align:left;display:flex;align-items:center;gap:7px;background:rgba(147,51,234,.2);border:1px solid rgba(147,51,234,.5);color:#c084fc;font-weight:600';
    }
    document.getElementById('mod-count').textContent=document.querySelectorAll('.mod-active').length+'/3 elegidos';
    document.getElementById('mod-msg').textContent='';
  }
  async function saveModules(){
    const chosen=[...document.querySelectorAll('.mod-active')].map(b=>b.dataset.mod);
    if(chosen.length===0){document.getElementById('mod-msg').textContent='Elige al menos 1 módulo.';return;}
    const csrf=document.querySelector('meta[name="dm-csrf"]')?.content||'';
    const r=await fetch('/supercerebro/api/billing.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'action=save_modules&modules='+chosen.join(',')+'&csrf_token='+encodeURIComponent(csrf)});
    const d=await r.json();
    if(d.ok){document.getElementById('mod-msg').textContent='✓ Guardado. Recarga para ver los módulos en el menú.';document.getElementById('module-selector-card').style.borderColor='rgba(13,207,207,.3)';}
    else document.getElementById('mod-msg').textContent=d.error||'Error al guardar.';
  }
  </script>

<script>
(async function loadBillingStatus(){
  if(document.querySelector('#billing-card [data-admin]')) return; // skip for admin
  const csrf=document.querySelector('meta[name="dm-csrf"]')?.content||'';
  const r=await fetch('/supercerebro/api/billing.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'action=get_status&csrf_token='+encodeURIComponent(csrf)});
  const d=await r.json();
  if(!d.ok||!d.plan) return;
  const plans={'starter':'Starter','pro':'Pro','agency':'Agency','enterprise':'Enterprise'};
  const planName=plans[d.plan]||d.plan;
  const endDate=d.period_end?new Date(d.period_end*1000).toLocaleDateString('es-CO',{day:'numeric',month:'long',year:'numeric'}):'';
  const el=document.getElementById('billing-info');
  if(el) el.innerHTML=`<strong style="color:var(--t)">${planName}</strong> — ${d.status==='active'||d.status==='trialing'?'<span style="color:var(--g)">Activo</span>':'<span style="color:var(--y)">'+(d.status||'—')+'</span>'}${endDate?' · Ciclo: '+endDate:''}`;
  const banner=document.getElementById('cancel-banner');
  const btnC=document.getElementById('btn-cancel-sub');
  const btnR=document.getElementById('btn-reactivate-sub');
  if(d.is_canceling){
    if(banner){ banner.style.display='block'; banner.textContent='⚠ Tu suscripción está programada para cancelarse'+(endDate?' el '+endDate:'')+'. Aún tienes acceso completo hasta esa fecha.'; }
    if(btnC) btnC.style.display='none';
    if(btnR) btnR.style.display='inline-flex';
    window._subPeriodEnd=endDate;
  } else {
    if(btnC) btnC.style.display='inline-flex';
    window._subPeriodEnd=endDate;
  }
})();

function openCancelModal(){
  const m=document.getElementById('modal-cancel-sub');
  const d=document.getElementById('cancel-modal-date');
  if(d&&window._subPeriodEnd) d.textContent='Acceso hasta: '+window._subPeriodEnd;
  if(m) m.style.display='flex';
}

async function confirmCancelSubscription(){
  document.getElementById('modal-cancel-sub').style.display='none';
  const csrf=document.querySelector('meta[name="dm-csrf"]')?.content||'';
  const r=await fetch('/supercerebro/api/billing.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'action=cancel&csrf_token='+encodeURIComponent(csrf)});
  const d=await r.json();
  if(d.ok){ location.reload(); } else { alert('Error: '+(d.error||'intenta de nuevo')); }
}

async function reactivateSubscription(){
  if(!confirm('¿Reactivar tu suscripción? Se restablecerán los cobros automáticos al final del ciclo.')) return;
  const csrf=document.querySelector('meta[name="dm-csrf"]')?.content||'';
  const r=await fetch('/supercerebro/api/billing.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'action=reactivate&csrf_token='+encodeURIComponent(csrf)});
  const d=await r.json();
  if(d.ok){ location.reload(); } else { alert('Error: '+(d.error||'intenta de nuevo')); }
}
</script>

  <?php endif ?>

  <div class="cfg-card" style="border-color:rgba(232,39,42,.2)">
    <div class="chd"><div class="ctit" style="color:var(--red)">Cerrar sesión</div></div>
    <p style="font-size:13px;color:var(--m);margin-bottom:12px">Tu sesión actual en el Super Cerebro DIMARK</p>
    <a href="logout.php"><button style="padding:8px 18px;border-radius:7px;font-size:13px;background:var(--rl);border:1px solid var(--rb);color:var(--red);cursor:pointer;font-family:var(--fb)">→ Cerrar sesión</button></a>
  </div>
</div>
