(function() {

  const REQUIRED_STEPS = [
    {
      id: 'add_connection',
      title: 'Add your first Oracle connection',
      desc: 'Connect TuneVault to your Oracle database via proxy agent.',
      cta: 'Add Connection →',
      href: '/connections/new',
      required: true,
    },
    {
      id: 'run_health_check',
      title: 'Run your first health check',
      desc: '200+ checks across DB performance, security, storage and EBS in under 2 minutes.',
      cta: 'Go to Servers →',
      href: '/connections',
      required: true,
    },
  ];

  const OPTIONAL_STEPS = [
    {
      id: 'try_dba_agent',
      title: 'Try the DBA Agent',
      desc: 'Investigate a blocking session or performance issue with one sentence.',
      cta: 'Open DBA Agent →',
      href: '/tune',
      required: false,
    },
    {
      id: 'check_security_score',
      title: 'Check your Security Posture score',
      desc: 'See how your Oracle DB scores on security — privileges, auditing, patch currency.',
      cta: 'View Security →',
      href: '/security',
      required: false,
    },
    {
      id: 'try_tunebot',
      title: 'Ask TuneBot about your database',
      desc: 'AI assistant connected to your live findings and Oracle documentation.',
      cta: 'Open TuneBot →',
      href: '/tune',
      required: false,
    },
    {
      id: 'download_report',
      title: 'Download your first PDF report',
      desc: 'Share your health check findings with your team or manager.',
      cta: 'View Reports →',
      href: '/reports',
      required: false,
    },
    {
      id: 'setup_monitoring',
      title: 'Set up autonomous monitoring',
      desc: 'Schedule health checks to run automatically and alert you on new issues.',
      cta: 'Set up schedules →',
      href: '/connections',
      required: false,
    },
  ];

  const ALL_STEPS = [...REQUIRED_STEPS, ...OPTIONAL_STEPS];

  async function fetchProgress() {
    try {
      const r = await fetch('/api/onboarding/progress');
      if (!r.ok) return {};
      return await r.json();
    } catch(e) { return {}; }
  }

  function render(progress) {
    if (progress.dismissed) {
      // Show small trigger button
      const trigger = document.getElementById('onboarding-trigger');
      if (trigger) {
        const requiredDone = REQUIRED_STEPS.every(s => progress[s.id]);
        if (!requiredDone) trigger.style.display = 'block';
      }
      return;
    }

    const requiredDone = REQUIRED_STEPS.every(s => progress[s.id]);
    const allDone = ALL_STEPS.every(s => progress[s.id]);

    if (allDone) {
      fetch('/api/onboarding/dismiss', {method:'POST'});
      return;
    }

    // Only show modal automatically on first login (no connection yet)
    const isFirstTime = !progress.add_connection;
    if (!isFirstTime && !window._onboardingForceOpen) {
      // Show trigger button instead
      const trigger = document.getElementById('onboarding-trigger');
      if (trigger && !requiredDone) trigger.style.display = 'block';
      return;
    }

    showModal(progress);
  }

  function showModal(progress) {
    // Remove existing modal if any
    const existing = document.getElementById('onboarding-overlay');
    if (existing) existing.remove();

    const requiredCompleted = REQUIRED_STEPS.filter(s => progress[s.id]).length;
    const optionalCompleted = OPTIONAL_STEPS.filter(s => progress[s.id]).length;
    const totalCompleted = ALL_STEPS.filter(s => progress[s.id]).length;
    const pct = Math.round((totalCompleted / ALL_STEPS.length) * 100);

    const overlay = document.createElement('div');
    overlay.id = 'onboarding-overlay';
    overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.75);z-index:9999;display:flex;align-items:center;justify-content:center;padding:16px;';

    function stepHTML(s) {
      const done = !!progress[s.id];
      return `
        <div style="display:flex;align-items:center;gap:12px;padding:12px;background:${done ? '#0a1a0a' : '#1a1a1f'};border:1px solid ${done ? '#1a3a1a' : '#2a2a30'};border-radius:8px;">
          <div style="width:28px;height:28px;border-radius:50%;background:${done ? '#16a34a' : s.required ? '#1a0a00' : '#2a2a30'};border:${s.required && !done ? '1px solid #f97316' : 'none'};display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            ${done
              ? '<svg width="14" height="14" viewBox="0 0 24 24" fill="white"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>'
              : s.required
                ? '<svg width="10" height="10" viewBox="0 0 24 24" fill="#f97316"><circle cx="12" cy="12" r="8"/></svg>'
                : '<svg width="10" height="10" viewBox="0 0 24 24" fill="#555"><circle cx="12" cy="12" r="8"/></svg>'
            }
          </div>
          <div style="flex:1;min-width:0;">
            <div style="font-size:13px;font-weight:${done ? '400' : '600'};color:${done ? '#555' : '#e8e8ed'};${done ? 'text-decoration:line-through;' : ''}">
              ${s.title}
              ${s.required && !done ? '<span style="font-size:10px;color:#f97316;margin-left:6px;background:#1a0a00;padding:1px 6px;border-radius:10px;">Required</span>' : ''}
              ${!s.required && !done ? '<span style="font-size:10px;color:#555;margin-left:6px;background:#1a1a1f;padding:1px 6px;border-radius:10px;border:1px solid #2a2a30;">Optional</span>' : ''}
            </div>
            ${!done ? `<div style="font-size:12px;color:#888;margin-top:2px;">${s.desc}</div>` : ''}
          </div>
          ${!done ? `<a href="${s.href}" onclick="document.getElementById('onboarding-overlay').remove();window._onboardingForceOpen=false;" style="font-size:11px;color:#f97316;text-decoration:none;white-space:nowrap;flex-shrink:0;background:#1a0a00;padding:5px 10px;border-radius:6px;border:1px solid #f9731640;">${s.cta}</a>` : ''}
        </div>
      `;
    }

    overlay.innerHTML = `
      <div style="background:#111114;border:1px solid #2a2a30;border-radius:16px;padding:28px;max-width:520px;width:100%;position:relative;max-height:90vh;overflow-y:auto;">
        <button onclick="window.dismissOnboarding()" style="position:absolute;top:16px;right:16px;background:none;border:none;color:#888;cursor:pointer;font-size:22px;line-height:1;">×</button>

        <div style="margin-bottom:20px;">
          <div style="font-size:18px;font-weight:700;color:#e8e8ed;">Welcome to TuneVault 👋</div>
          <div style="font-size:13px;color:#888;margin-top:4px;">Complete the required steps to get started. Optional steps unlock more value.</div>
        </div>

        <div style="margin-bottom:20px;">
          <div style="display:flex;justify-content:space-between;margin-bottom:6px;">
            <span style="font-size:12px;color:#888;">${totalCompleted} of ${ALL_STEPS.length} complete (${requiredCompleted}/${REQUIRED_STEPS.length} required)</span>
            <span style="font-size:12px;font-weight:600;color:#f97316;">${pct}%</span>
          </div>
          <div style="height:4px;background:#2a2a30;border-radius:2px;">
            <div style="width:${pct}%;height:100%;background:#f97316;border-radius:2px;transition:width 0.3s;"></div>
          </div>
        </div>

        <div style="margin-bottom:8px;">
          <div style="font-size:11px;text-transform:uppercase;letter-spacing:1px;color:#f97316;margin-bottom:8px;">Required</div>
          <div style="display:flex;flex-direction:column;gap:6px;">
            ${REQUIRED_STEPS.map(s => stepHTML(s)).join('')}
          </div>
        </div>

        <div style="margin-top:16px;">
          <div style="font-size:11px;text-transform:uppercase;letter-spacing:1px;color:#555;margin-bottom:8px;">Optional — explore more</div>
          <div style="display:flex;flex-direction:column;gap:6px;">
            ${OPTIONAL_STEPS.map(s => stepHTML(s)).join('')}
          </div>
        </div>

        <div style="margin-top:20px;text-align:center;border-top:1px solid #2a2a30;padding-top:16px;">
          <button onclick="window.dismissOnboarding()" style="font-size:12px;color:#555;background:none;border:none;cursor:pointer;">Dismiss — I'll explore on my own</button>
        </div>
      </div>
    `;

    document.body.appendChild(overlay);
  }

  window.dismissOnboarding = async function() {
    await fetch('/api/onboarding/dismiss', {method:'POST'});
    const overlay = document.getElementById('onboarding-overlay');
    if (overlay) overlay.remove();
    window._onboardingForceOpen = false;
    // Show trigger button after dismiss if required steps not done
    const trigger = document.getElementById('onboarding-trigger');
    if (trigger) trigger.style.display = 'block';
  };

  window.initOnboarding = async function() {
    const progress = await fetchProgress();
    render(progress);
  };

  window.openOnboarding = async function() {
    window._onboardingForceOpen = true;
    const progress = await fetchProgress();
    showModal(progress);
  };

})();
