<?php if($isAdmin): ?>
<!-- ===== ONBOARDING WIZARD ===== -->
<div id="onboarding-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.65);z-index:10000;align-items:center;justify-content:center;padding:16px">
  <div style="background:var(--bg2);border:1px solid var(--br2);border-radius:16px;width:100%;max-width:520px;max-height:90vh;overflow-y:auto;box-shadow:0 16px 64px rgba(0,0,0,.5)">

    <!-- Header -->
    <div style="padding:22px 28px 0;display:flex;align-items:center;justify-content:space-between">
      <div>
        <div style="font-size:17px;font-weight:700;color:var(--t);font-family:var(--fh)">Configurar cliente</div>
        <div style="font-size:12px;color:var(--m);margin-top:2px" id="ob-client-name-hdr"></div>
      </div>
      <button data-click="obClose" style="background:none;border:none;color:var(--m);font-size:22px;cursor:pointer;line-height:1;padding:4px">×</button>
    </div>

    <!-- Step indicators -->
    <div style="display:flex;align-items:center;gap:0;padding:18px 28px 0">
      <?php for($s=1;$s<=4;$s++): ?>
      <div style="display:flex;align-items:center;flex:1<?= $s===4?';flex:none':'' ?>">
        <div class="ob-step-dot" id="ob-dot-<?= $s ?>"
          style="width:28px;height:28px;border-radius:50%;border:2px solid var(--br2);background:var(--bg3);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:var(--m);flex-shrink:0;transition:all .25s">
          <?= $s ?>
        </div>
        <?php if($s<4): ?><div class="ob-step-line" id="ob-line-<?= $s ?>" style="flex:1;height:2px;background:var(--br2);transition:background .25s"></div><?php endif ?>
      </div>
      <?php endfor ?>
    </div>
    <div style="display:flex;justify-content:space-between;padding:4px 18px 0;font-size:10px;color:var(--m)">
      <span>Resumen</span><span>Meta Ads</span><span>Google</span><span>¡Listo!</span>
    </div>

    <!-- Steps container -->
    <div style="padding:20px 28px 28px">

      <!-- PASO 1: Resumen -->
      <div class="ob-step" id="ob-step-1">
        <div style="font-size:14px;font-weight:700;color:var(--t);margin-bottom:4px">¿Qué servicios vas a conectar?</div>
        <div style="font-size:12px;color:var(--m);margin-bottom:18px">Selecciona los canales activos para este cliente. Puedes completar cada conexión en el siguiente paso.</div>
        <div id="ob-svc-grid" style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:20px">
          <div class="ob-svc-card" id="ob-svc-meta" data-click="obToggleSvc|meta"
            style="border:2px solid var(--br2);border-radius:10px;padding:14px;cursor:pointer;transition:all .2s;background:var(--bg3)">
            <div style="font-size:20px;margin-bottom:6px">📘</div>
            <div style="font-size:13px;font-weight:700;color:var(--t)">Meta Ads</div>
            <div style="font-size:11px;color:var(--m);margin-top:2px">Facebook · Instagram</div>
            <div class="ob-svc-status" id="ob-svc-status-meta" style="margin-top:8px;font-size:11px;color:var(--m)">Verificando...</div>
          </div>
          <div class="ob-svc-card" id="ob-svc-google" data-click="obToggleSvc|google"
            style="border:2px solid var(--br2);border-radius:10px;padding:14px;cursor:pointer;transition:all .2s;background:var(--bg3)">
            <div style="font-size:20px;margin-bottom:6px">🟢</div>
            <div style="font-size:13px;font-weight:700;color:var(--t)">Google Ads</div>
            <div style="font-size:11px;color:var(--m);margin-top:2px">Search · Display · PMax</div>
            <div class="ob-svc-status" id="ob-svc-status-google" style="margin-top:8px;font-size:11px;color:var(--m)">Verificando...</div>
          </div>
          <div class="ob-svc-card" id="ob-svc-gsc" data-click="obToggleSvc|gsc"
            style="border:2px solid var(--br2);border-radius:10px;padding:14px;cursor:pointer;transition:all .2s;background:var(--bg3)">
            <div style="font-size:20px;margin-bottom:6px">🔍</div>
            <div style="font-size:13px;font-weight:700;color:var(--t)">SEO / GSC</div>
            <div style="font-size:11px;color:var(--m);margin-top:2px">Google Search Console</div>
            <div class="ob-svc-status" id="ob-svc-status-gsc" style="margin-top:8px;font-size:11px;color:var(--m)">Verificando...</div>
          </div>
          <div class="ob-svc-card" id="ob-svc-tiktok" data-click="obToggleSvc|tiktok"
            style="border:2px solid var(--br2);border-radius:10px;padding:14px;cursor:pointer;transition:all .2s;background:var(--bg3)">
            <div style="font-size:20px;margin-bottom:6px">🎵</div>
            <div style="font-size:13px;font-weight:700;color:var(--t)">TikTok Ads</div>
            <div style="font-size:11px;color:var(--m);margin-top:2px">Business · Ad Manager</div>
            <div class="ob-svc-status" id="ob-svc-status-tiktok" style="margin-top:8px;font-size:11px;color:var(--m)">Verificando...</div>
          </div>
        </div>
        <button data-click="obGoStep|2" style="width:100%;padding:11px;background:var(--red);color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;font-family:var(--fb)">Siguiente →</button>
      </div>

      <!-- PASO 2: Meta Ads -->
      <div class="ob-step" id="ob-step-2" style="display:none">
        <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px">
          <div style="font-size:28px">📘</div>
          <div>
            <div style="font-size:14px;font-weight:700;color:var(--t)">Meta Ads</div>
            <div style="font-size:12px;color:var(--m)">Facebook · Instagram · Audience Network</div>
          </div>
        </div>
        <div id="ob-meta-status-banner" style="border-radius:8px;padding:12px 14px;font-size:13px;margin-bottom:16px"></div>
        <div style="background:var(--bg3);border:1px solid var(--br);border-radius:10px;padding:16px;margin-bottom:16px">
          <div style="font-size:12px;font-weight:600;color:var(--m);margin-bottom:10px;text-transform:uppercase;letter-spacing:.5px">Para conectar Meta Ads</div>
          <div style="display:flex;flex-direction:column;gap:8px;font-size:13px;color:var(--t)">
            <div>1. Ve a <strong>Clientes</strong> en el menú lateral</div>
            <div>2. Abre el cliente y pestaña <strong>Meta</strong></div>
            <div>3. Ingresa el <strong>Ad Account ID</strong> y el <strong>Access Token</strong></div>
          </div>
        </div>
        <div style="display:flex;gap:8px">
          <button data-click="obVerifyStep|meta|ob-meta-status-banner" id="ob-verify-meta"
            style="flex:1;padding:9px;background:rgba(74,158,248,.12);border:1px solid rgba(74,158,248,.3);color:var(--b);border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:var(--fb)">
            ↺ Verificar conexión
          </button>
          <button data-click="obGoStep|1" style="padding:9px 16px;background:var(--bg3);border:1px solid var(--br2);color:var(--m);border-radius:8px;font-size:13px;cursor:pointer">← Atrás</button>
          <button data-click="obGoStep|3" style="padding:9px 16px;background:var(--red);color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;font-family:var(--fb)">Siguiente →</button>
        </div>
      </div>

      <!-- PASO 3: Google Ads + GSC -->
      <div class="ob-step" id="ob-step-3" style="display:none">
        <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px">
          <div style="font-size:28px">🟢</div>
          <div>
            <div style="font-size:14px;font-weight:700;color:var(--t)">Google Ads + Search Console</div>
            <div style="font-size:12px;color:var(--m)">Campañas + datos SEO orgánico</div>
          </div>
        </div>

        <!-- Google Ads status -->
        <div style="font-size:12px;font-weight:600;color:var(--m);margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px">Google Ads</div>
        <div id="ob-google-status-banner" style="border-radius:8px;padding:10px 14px;font-size:13px;margin-bottom:10px"></div>
        <div style="background:var(--bg3);border:1px solid var(--br);border-radius:10px;padding:14px;margin-bottom:14px;font-size:13px;color:var(--t)">
          Ve a <strong>Clientes</strong> → cliente → pestaña <strong>Google</strong> → ingresa el <strong>Customer ID</strong>
        </div>

        <!-- GSC status -->
        <div style="font-size:12px;font-weight:600;color:var(--m);margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px">Google Search Console</div>
        <div id="ob-gsc-status-banner" style="border-radius:8px;padding:10px 14px;font-size:13px;margin-bottom:10px"></div>
        <div style="background:var(--bg3);border:1px solid var(--br);border-radius:10px;padding:14px;margin-bottom:16px;font-size:13px;color:var(--t)">
          Ve a <strong>Configuración</strong> → <strong>APIs</strong> → pestaña Google → conecta OAuth. Luego ingresa el dominio en <strong>Clientes</strong>.
        </div>

        <div style="display:flex;gap:8px;flex-wrap:wrap">
          <button data-click="_scVerifyAllGoogle" id="ob-verify-google"
            style="flex:1;min-width:140px;padding:9px;background:rgba(74,158,248,.12);border:1px solid rgba(74,158,248,.3);color:var(--b);border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:var(--fb)">
            ↺ Verificar conexiones
          </button>
          <button data-click="obGoStep|2" style="padding:9px 16px;background:var(--bg3);border:1px solid var(--br2);color:var(--m);border-radius:8px;font-size:13px;cursor:pointer">← Atrás</button>
          <button data-click="obGoStep|4" style="padding:9px 16px;background:var(--red);color:#fff;border:none;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;font-family:var(--fb)">Siguiente →</button>
        </div>
      </div>

      <!-- PASO 4: Resumen final -->
      <div class="ob-step" id="ob-step-4" style="display:none">
        <div style="text-align:center;padding:8px 0 16px">
          <div style="font-size:40px;margin-bottom:10px">🎉</div>
          <div style="font-size:16px;font-weight:700;color:var(--t);font-family:var(--fh)">¡Configuración completada!</div>
          <div style="font-size:13px;color:var(--m);margin-top:4px" id="ob-done-subtitle"></div>
        </div>
        <div id="ob-final-summary" style="display:flex;flex-direction:column;gap:8px;margin-bottom:20px"></div>
        <button data-click="_scObCloseResumen"
          style="width:100%;padding:12px;background:var(--red);color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:700;cursor:pointer;font-family:var(--fb)">
          Ir al dashboard →
        </button>
      </div>

    </div>
  </div>
</div>

<script>
(function(){
  let _obClientId = null;
  let _obStatus   = {};
  let _obSelected = new Set(['meta','google','gsc','tiktok']);
  let _obStep     = 1;

  // FASE 8.4: persistencia BD del progreso del wizard
  const _obCsrf = () => document.querySelector('meta[name="dm-csrf"]')?.content || '';

  async function _obSaveProgress(extra = {}) {
    if (!_obClientId) return;
    try {
      await fetch('api/onboarding-progress.php?action=save', {
        method: 'POST',
        headers: { 'Content-Type':'application/json', 'X-CSRF-Token': _obCsrf() },
        body: JSON.stringify(Object.assign({
          client_id: _obClientId,
          step: _obStep,
          selected: Array.from(_obSelected),
        }, extra))
      });
    } catch(_) {}
  }

  async function _obLoadProgress() {
    if (!_obClientId) return false;
    try {
      const r = await fetch('api/onboarding-progress.php?action=load&client_id=' + _obClientId).then(r => r.json());
      if (r?.ok && r.has_progress && !r.completed) {
        _obStep = r.step || 1;
        if (Array.isArray(r.selected) && r.selected.length) _obSelected = new Set(r.selected);
        return true;
      }
    } catch(_) {}
    return false;
  }

  window.obOpen = async function(clientId) {
    _obClientId = clientId;
    _obStatus   = {};
    _obSelected = new Set(['meta','google','gsc','tiktok']);
    _obStep     = 1;
    document.getElementById('onboarding-modal').style.display = 'flex';
    // Rehidratar progreso si existe — si no, mantiene defaults
    const restored = await _obLoadProgress();
    if (restored) {
      // Reflejar selección en cards
      ['meta','google','gsc','tiktok','wordpress','shopify','mailchimp'].forEach(svc => {
        const card = document.getElementById('ob-svc-' + svc);
        if (!card) return;
        if (_obSelected.has(svc)) {
          card.style.borderColor = 'var(--red)';
          card.style.background  = 'rgba(220,38,38,.06)';
          card.style.opacity     = '1';
        } else {
          card.style.borderColor = 'var(--br2)';
          card.style.background  = 'var(--bg3)';
          card.style.opacity     = '.5';
        }
      });
    }
    obGoStep(_obStep);
    obLoadStatus();
  };

  window.obClose = function() {
    document.getElementById('onboarding-modal').style.display = 'none';
    _obSaveProgress(); // guardar al cerrar (snapshot)
  };

  window.obToggleSvc = function(svc) {
    const card = document.getElementById('ob-svc-' + svc);
    if (_obSelected.has(svc)) {
      _obSelected.delete(svc);
      card.style.borderColor = 'var(--br2)';
      card.style.background  = 'var(--bg3)';
      card.style.opacity     = '.5';
    } else {
      _obSelected.add(svc);
      card.style.borderColor = 'var(--red)';
      card.style.background  = 'rgba(220,38,38,.06)';
      card.style.opacity     = '1';
    }
    _obSaveProgress();
  };

  window.obGoStep = function(n) {
    _obStep = n;
    _obSaveProgress(n === 4 ? { completed: true } : {}); // step 4 = final
    document.querySelectorAll('.ob-step').forEach(el => el.style.display = 'none');
    const s = document.getElementById('ob-step-' + n);
    if (s) s.style.display = 'block';

    // Update dots & lines
    for (let i = 1; i <= 4; i++) {
      const dot  = document.getElementById('ob-dot-' + i);
      const line = document.getElementById('ob-line-' + i);
      if (dot) {
        if (i < n) {
          dot.style.background   = 'var(--red)';
          dot.style.borderColor  = 'var(--red)';
          dot.style.color        = '#fff';
          dot.textContent        = '✓';
        } else if (i === n) {
          dot.style.background   = 'var(--red)';
          dot.style.borderColor  = 'var(--red)';
          dot.style.color        = '#fff';
          dot.textContent        = i;
        } else {
          dot.style.background   = 'var(--bg3)';
          dot.style.borderColor  = 'var(--br2)';
          dot.style.color        = 'var(--m)';
          dot.textContent        = i;
        }
      }
      if (line) line.style.background = (i < n) ? 'var(--red)' : 'var(--br2)';
    }

    if (n === 2) obRenderStepBanner('meta', 'ob-meta-status-banner');
    if (n === 3) {
      obRenderStepBanner('google', 'ob-google-status-banner');
      obRenderStepBanner('gsc',    'ob-gsc-status-banner');
    }
    if (n === 4) obRenderFinalSummary();
  };

  window.obLoadStatus = async function() {
    if (!_obClientId) return;
    // Update header
    const hdr = document.getElementById('ob-client-name-hdr');
    // Reset all statuses to loading
    ['meta','google','gsc','tiktok'].forEach(s => {
      const el = document.getElementById('ob-svc-status-' + s);
      if (el) el.textContent = 'Verificando...';
    });
    try {
      const res  = await fetch('api/onboarding-check.php?client_id=' + _obClientId);
      const data = await res.json();
      if (!data.ok) return;
      _obStatus = data.status;
      if (hdr && data.client) hdr.textContent = data.client.name;

      ['meta','google','gsc','tiktok'].forEach(svc => {
        const ok  = data.status[svc];
        const el  = document.getElementById('ob-svc-status-' + svc);
        const card = document.getElementById('ob-svc-' + svc);
        if (el) {
          el.textContent = ok ? '✓ Conectado' : '✗ Sin configurar';
          el.style.color = ok ? 'var(--g)' : 'var(--red)';
        }
        if (card) {
          card.style.borderColor = ok ? 'rgba(34,197,94,.5)' : 'var(--br2)';
          card.style.background  = ok ? 'rgba(34,197,94,.06)' : 'var(--bg3)';
          card.style.opacity     = '1';
        }
        // Pre-select only services with data or explicitly selected
        if (ok) _obSelected.add(svc);
      });

      // Refresh current step banners
      if (_obStep === 2) obRenderStepBanner('meta', 'ob-meta-status-banner');
      if (_obStep === 3) {
        obRenderStepBanner('google', 'ob-google-status-banner');
        obRenderStepBanner('gsc',    'ob-gsc-status-banner');
      }
    } catch(e) {
      console.error('onboarding-check error', e);
    }
  };

  window.obVerifyStep = async function(svc, bannerId) {
    const btn = document.getElementById('ob-verify-' + svc.split(',')[0]) ||
                document.getElementById('ob-verify-google');
    if (btn) { btn.disabled = true; btn.textContent = 'Verificando...'; }
    try {
      const res  = await fetch('api/onboarding-check.php?client_id=' + _obClientId);
      const data = await res.json();
      if (data.ok) {
        _obStatus = data.status;
        // Update step 1 cards
        ['meta','google','gsc','tiktok'].forEach(s => {
          const el = document.getElementById('ob-svc-status-' + s);
          if (el) {
            el.textContent = data.status[s] ? '✓ Conectado' : '✗ Sin configurar';
            el.style.color = data.status[s] ? 'var(--g)' : 'var(--red)';
          }
        });
        obRenderStepBanner(svc, bannerId);
        // Also refresh gsc if google was checked
        if (svc === 'google') obRenderStepBanner('gsc', 'ob-gsc-status-banner');
      }
    } catch(e) {}
    if (btn) { btn.disabled = false; btn.textContent = '↺ Verificar conexión' + (svc === 'google' ? 'es' : ''); }
  };

  function obRenderStepBanner(svc, bannerId) {
    const el = document.getElementById(bannerId);
    if (!el) return;
    const ok = _obStatus[svc];
    el.style.background = ok
      ? 'rgba(34,197,94,.1)'
      : 'rgba(248,113,113,.08)';
    el.style.border = ok
      ? '1px solid rgba(34,197,94,.25)'
      : '1px solid rgba(248,113,113,.2)';
    el.style.color = ok ? 'var(--g)' : '#f87171';
    el.textContent = ok
      ? '✓ Conectado correctamente'
      : '✗ No configurado — sigue los pasos para conectar';
  }

  function obRenderFinalSummary() {
    const labels = { meta:'Meta Ads', google:'Google Ads', gsc:'Google Search Console', tiktok:'TikTok Ads' };
    const cont = document.getElementById('ob-final-summary');
    const sub  = document.getElementById('ob-done-subtitle');
    if (!cont) return;
    const connected = Object.keys(_obStatus).filter(s => _obStatus[s]);
    if (sub) sub.textContent = connected.length
      ? connected.length + ' servicio' + (connected.length > 1 ? 's' : '') + ' conectado' + (connected.length > 1 ? 's' : '')
      : 'Sin servicios conectados aún — puedes hacerlo en cualquier momento';
    cont.innerHTML = Object.keys(labels).map(svc => {
      const ok = _obStatus[svc];
      return `<div style="display:flex;align-items:center;gap:10px;padding:10px 14px;border-radius:8px;background:var(--bg3);border:1px solid ${ok ? 'rgba(34,197,94,.25)' : 'var(--br)'}">
        <span style="font-size:18px">${{meta:'📘',google:'🟢',gsc:'🔍',tiktok:'🎵'}[svc]}</span>
        <span style="flex:1;font-size:13px;font-weight:600;color:var(--t)">${labels[svc]}</span>
        <span style="font-size:12px;font-weight:700;color:${ok ? 'var(--g)' : 'var(--m)'}">${ok ? '✓ Conectado' : '— Pendiente'}</span>
      </div>`;
    }).join('');
  }

  // Close on backdrop click
  document.getElementById('onboarding-modal').addEventListener('click', function(e) {
    if (e.target === this) obClose();
  });
})();
</script>
<?php endif ?>
