/**
 * OnboardingWizard.jsx — First-time user onboarding
 * Repo: wpsitebeam-app / design/OnboardingWizard.jsx
 * Version: v1.0.0 — 2026-05-26
 *
 * 5-step wizard triggered on first Dashboard load for new accounts.
 * Steps: Welcome → Connect site → Run scan → Quick win → Done
 *
 * Trigger from App.jsx:
 *   GET /account/onboarding/status → if show_wizard === true → mount wizard
 *
 * Completion:
 *   POST /account/onboarding/complete → dismiss wizard permanently
 *
 * Design: full-screen overlay modal, progress bar, skip always available.
 * WCAG 2.1 AA: focus trap, aria-modal, keyboard nav, aria-live scan progress.
 */

(function () {
  'use strict';
  const VERSION = '1.0.0';
  console.log('[OnboardingWizard] v' + VERSION + ' loaded');

  /* ─── API helpers ─────────────────────────────────────────── */
  function apiBase() { return (window.WPSBD && window.WPSBD.apiBase) || 'https://api.wpsitebeam.io'; }
  function getToken() { return window.WPSBD && window.WPSBD.getToken ? window.WPSBD.getToken() : ''; }

  async function apiFetch(path, opts) {
    const r = await fetch(apiBase() + path, {
      ...opts,
      headers: { Authorization: 'Bearer ' + getToken(), 'Content-Type': 'application/json', ...(opts && opts.headers) },
    });
    if (!r.ok) { const b = await r.json().catch(() => ({})); throw new Error(b.error || 'HTTP ' + r.status); }
    return r.json();
  }

  function firstName() {
    const meta = window.WPSBD && window.WPSBD.state && window.WPSBD.state.user_metadata;
    return (meta && meta.first_name) || '';
  }

  function planName() {
    const role = window.WPSBD && window.WPSBD.state && window.WPSBD.state.role;
    const plan = window.WPSBD && window.WPSBD.state && window.WPSBD.state.plan;
    const names = { solo: 'Solo', starter: 'Starter', growth: 'Pro', pro: 'Pro', agency: 'Agency', enterprise: 'Enterprise' };
    return names[plan] || 'Free';
  }

  /* ─── CSS ─────────────────────────────────────────────────── */
  const CSS = `
.ow-overlay {
  position: fixed; inset: 0;
  background: rgba(0,0,0,.65);
  display: flex; align-items: center; justify-content: center;
  z-index: 9000;
  padding: 20px;
}
.ow-card {
  background: var(--panel);
  border: 1px solid var(--border);
  border-radius: 16px;
  width: 100%;
  max-width: 520px;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
}
.ow-progress {
  height: 3px;
  background: var(--border);
  border-radius: 3px 3px 0 0;
  overflow: hidden;
}
.ow-progress-fill {
  height: 100%;
  background: var(--cyan,#06b6d4);
  border-radius: 3px;
  transition: width .3s ease;
}
.ow-header {
  padding: 20px 24px 0;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.ow-step-label { font-size: 12px; color: var(--dim); font-weight: 500; }
.ow-skip-btn {
  background: none; border: none; cursor: pointer;
  color: var(--dim); font-size: 12px; padding: 4px 8px;
  border-radius: 5px;
  min-height: 28px;
}
.ow-skip-btn:hover { background: rgba(0,0,0,.08); color: var(--text); }
.ow-body { padding: 20px 24px 24px; }
.ow-icon { font-size: 42px; margin-bottom: 12px; line-height: 1; }
.ow-title { font-size: 22px; font-weight: 700; margin-bottom: 8px; line-height: 1.2; }
.ow-sub { font-size: 14px; color: var(--dim); line-height: 1.6; margin-bottom: 20px; }
.ow-features { list-style: none; padding: 0; margin: 0 0 24px; display: flex; flex-direction: column; gap: 8px; }
.ow-feature { display: flex; align-items: flex-start; gap: 10px; font-size: 14px; }
.ow-feature-icon { font-size: 18px; margin-top: 1px; flex-shrink: 0; }
.ow-feature-text strong { display: block; font-weight: 500; }
.ow-feature-text span { font-size: 12px; color: var(--dim); }
.ow-input {
  width: 100%; padding: 10px 12px;
  font-size: 14px; border: 1px solid var(--border); border-radius: 8px;
  background: var(--panel); color: var(--text); margin-bottom: 12px;
  box-sizing: border-box;
}
.ow-input:focus { outline: 2px solid var(--cyan,#06b6d4); outline-offset: 1px; }
.ow-detect-result {
  font-size: 13px; padding: 10px 12px;
  border-radius: 8px; margin-bottom: 16px;
}
.ow-detect-ok { background: rgba(16,185,129,.1); color: var(--green,#10b981); border: 1px solid rgba(16,185,129,.3); }
.ow-detect-warn { background: rgba(245,158,11,.1); color: var(--warn,#f59e0b); border: 1px solid rgba(245,158,11,.3); }
.ow-detect-err { background: rgba(239,68,68,.1); color: var(--red,#ef4444); border: 1px solid rgba(239,68,68,.3); }
.ow-plugin-options { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 20px; }
.ow-option-card {
  padding: 14px 16px; border: 1px solid var(--border); border-radius: 10px;
  cursor: pointer; font-size: 13px; background: transparent;
  text-align: left; color: var(--text); transition: background .15s;
  min-height: 44px;
}
.ow-option-card:hover { background: rgba(6,182,212,.08); border-color: rgba(6,182,212,.4); }
.ow-option-card strong { display: block; font-weight: 600; margin-bottom: 3px; }
.ow-option-card span { color: var(--dim); font-size: 11px; }
.ow-scan-progress {
  background: rgba(0,0,0,.08); border-radius: 10px;
  padding: 16px; margin-bottom: 20px;
}
.ow-scan-bar-track { height: 6px; background: var(--border); border-radius: 3px; margin-bottom: 8px; }
.ow-scan-bar-fill { height: 100%; background: var(--cyan,#06b6d4); border-radius: 3px; transition: width .5s; }
.ow-scan-label { font-size: 12px; color: var(--dim); }
.ow-issue-summary { font-size: 28px; font-weight: 700; color: var(--red,#ef4444); }
.ow-issue-sub { font-size: 13px; color: var(--dim); margin-bottom: 20px; }
.ow-quick-win {
  border: 1px solid var(--border); border-radius: 10px;
  padding: 14px 16px; margin-bottom: 20px; font-size: 13px;
  background: rgba(6,182,212,.05); border-color: rgba(6,182,212,.3);
}
.ow-quick-win-label { font-size: 11px; font-weight: 600; color: var(--cyan,#06b6d4); text-transform: uppercase; letter-spacing: .05em; margin-bottom: 6px; }
.ow-quick-win-text { font-weight: 500; margin-bottom: 4px; }
.ow-quick-win-sub { color: var(--dim); }
.ow-next-steps { display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px; }
.ow-next-card {
  display: flex; align-items: center; gap: 12px;
  padding: 12px 14px; border: 1px solid var(--border); border-radius: 10px;
  cursor: pointer; background: transparent; text-align: left; color: var(--text); width: 100%; min-height: 44px;
}
.ow-next-card:hover { background: rgba(0,0,0,.05); }
.ow-next-card-icon { font-size: 20px; flex-shrink: 0; }
.ow-next-card-text strong { display: block; font-size: 13px; font-weight: 500; }
.ow-next-card-text span { font-size: 12px; color: var(--dim); }
.ow-btn-primary {
  width: 100%; padding: 12px; font-size: 14px; font-weight: 600;
  background: var(--cyan,#06b6d4); color: #fff; border: none; border-radius: 9px;
  cursor: pointer; min-height: 44px;
}
.ow-btn-primary:hover { opacity: .9; }
.ow-btn-primary:disabled { opacity: .5; cursor: not-allowed; }
.ow-btn-secondary {
  width: 100%; padding: 10px; font-size: 13px; font-weight: 500;
  background: transparent; color: var(--dim); border: 1px solid var(--border);
  border-radius: 9px; cursor: pointer; margin-top: 8px; min-height: 40px;
}
.ow-btn-secondary:hover { background: rgba(0,0,0,.05); color: var(--text); }
.ow-error { font-size: 12px; color: var(--red,#ef4444); margin-bottom: 10px; }
@media (max-width: 480px) {
  .ow-overlay { padding: 0; align-items: flex-end; }
  .ow-card { max-width: 100%; border-radius: 16px 16px 0 0; max-height: 92vh; }
  .ow-plugin-options { grid-template-columns: 1fr; }
}
`;

  /* ─── Step components ─────────────────────────────────────── */
  function StepWelcome({ onNext }) {
    const name = firstName();
    return React.createElement('div', { className: 'ow-body' },
      React.createElement('div', { className: 'ow-icon', 'aria-hidden': 'true' }, '\uD83D\uDE80'),
      React.createElement('h1', { className: 'ow-title' }, 'Welcome' + (name ? ', ' + name : '') + '\u2019'),
      React.createElement('p', { className: 'ow-sub' },
        'You\u2019re on the ', React.createElement('strong', null, planName()), ' plan. Here\u2019s what you can do in the next 3 minutes:'
      ),
      React.createElement('ul', { className: 'ow-features' },
        React.createElement('li', { className: 'ow-feature' },
          React.createElement('span', { className: 'ow-feature-icon', 'aria-hidden': 'true' }, '\uD83D\uDD0D'),
          React.createElement('div', { className: 'ow-feature-text' },
            React.createElement('strong', null, 'Scan a site for issues'),
            React.createElement('span', null, 'Accessibility, SEO, and performance — one scan')
          )
        ),
        React.createElement('li', { className: 'ow-feature' },
          React.createElement('span', { className: 'ow-feature-icon', 'aria-hidden': 'true' }, '\u2705'),
          React.createElement('div', { className: 'ow-feature-text' },
            React.createElement('strong', null, 'Fix problems in one click'),
            React.createElement('span', null, 'Auto-fix common issues without touching code')
          )
        ),
        React.createElement('li', { className: 'ow-feature' },
          React.createElement('span', { className: 'ow-feature-icon', 'aria-hidden': 'true' }, '\uD83D\uDCC8'),
          React.createElement('div', { className: 'ow-feature-text' },
            React.createElement('strong', null, 'Track SEO rankings'),
            React.createElement('span', null, 'Keywords tracked weekly, included in your plan')
          )
        )
      ),
      React.createElement('button', { className: 'ow-btn-primary', onClick: onNext }, 'Get started \u2192')
    );
  }

  function StepConnect({ onNext, onSkip }) {
    const [url, setUrl] = React.useState('');
    const [checking, setChecking] = React.useState(false);
    const [detectResult, setDetectResult] = React.useState(null);
    const [error, setError] = React.useState('');

    async function handleCheck() {
      if (!url.trim()) { setError('Please enter a URL'); return; }
      let clean = url.trim();
      if (!/^https?:\/\//.test(clean)) clean = 'https://' + clean;
      setChecking(true); setError(''); setDetectResult(null);
      try {
        const r = await fetch(apiBase() + '/scanner/detect-platform?url=' + encodeURIComponent(clean), {
          headers: { Authorization: 'Bearer ' + getToken() },
        });
        const data = await r.json().catch(() => ({}));
        const isWp = data.platform === 'wordpress' || data.is_wordpress;
        setDetectResult({ url: clean, isWp, platform: data.platform || 'unknown' });
      } catch (e) {
        setDetectResult({ url: clean, isWp: false, platform: 'unknown', err: e.message });
      }
      setChecking(false);
    }

    return React.createElement('div', { className: 'ow-body' },
      React.createElement('div', { className: 'ow-icon', 'aria-hidden': 'true' }, '\uD83D\uDD17'),
      React.createElement('h2', { className: 'ow-title' }, 'Connect a site'),
      React.createElement('p', { className: 'ow-sub' }, 'Enter the URL of your WordPress site or a client site.'),
      error && React.createElement('p', { className: 'ow-error', role: 'alert' }, error),
      React.createElement('input', {
        type: 'url', className: 'ow-input',
        placeholder: 'https://yourclientsite.com',
        value: url, onChange: e => setUrl(e.target.value),
        'aria-label': 'Site URL',
        onKeyDown: e => { if (e.key === 'Enter') handleCheck(); },
      }),
      detectResult && React.createElement('div', {
        className: 'ow-detect-result ' + (detectResult.isWp ? 'ow-detect-ok' : 'ow-detect-warn'),
        role: 'status',
      },
        detectResult.isWp
          ? '\u2705 WordPress detected at ' + detectResult.url
          : '\u26A0\uFE0F WordPress not detected — you can still run a shallow scan'
      ),
      !detectResult
        ? React.createElement('button', {
            className: 'ow-btn-primary', onClick: handleCheck, disabled: checking,
          }, checking ? 'Checking\u2026' : 'Check site \u2192')
        : React.createElement('div', null,
            detectResult.isWp && React.createElement('div', { className: 'ow-plugin-options' },
              React.createElement('button', { className: 'ow-option-card', onClick: () => window.open('https://wordpress.org/plugins/wpsitebeam/', '_blank') },
                React.createElement('strong', null, 'Install plugin'),
                React.createElement('span', null, 'Unlock full scanning')
              ),
              React.createElement('button', { className: 'ow-option-card', onClick: () => onNext(detectResult.url) },
                React.createElement('strong', null, 'Skip for now'),
                React.createElement('span', null, 'Run a shallow scan')
              )
            ),
            !detectResult.isWp && React.createElement('button', {
              className: 'ow-btn-primary', onClick: () => onNext(detectResult.url),
            }, 'Run a shallow scan \u2192')
          ),
      React.createElement('button', { className: 'ow-btn-secondary', onClick: onSkip }, 'I\u2019ll add a site later')
    );
  }

  function StepScan({ siteUrl, onNext }) {
    const [progress, setProgress] = React.useState(0);
    const [status, setStatus] = React.useState('Starting scan\u2026');
    const [results, setResults] = React.useState(null);
    const [error, setError] = React.useState('');

    React.useEffect(() => {
      if (!siteUrl) { onNext(null); return; }
      let cancelled = false;
      const steps = [
        [400, 15, 'Fetching site\u2026'],
        [800, 30, 'Detecting WordPress\u2026'],
        [600, 50, 'Scanning pages\u2026'],
        [800, 70, 'Checking accessibility\u2026'],
        [600, 85, 'Analyzing SEO\u2026'],
        [400, 95, 'Finishing up\u2026'],
      ];
      let i = 0;
      function runStep() {
        if (cancelled || i >= steps.length) return;
        const [delay, pct, msg] = steps[i++];
        setTimeout(() => {
          if (!cancelled) { setProgress(pct); setStatus(msg); runStep(); }
        }, delay);
      }
      runStep();
      apiFetch('/scanner/quick-scan', {
        method: 'POST',
        body: JSON.stringify({ url: siteUrl, max_pages: 10 }),
      }).then(data => {
        if (!cancelled) {
          setProgress(100);
          setStatus('Scan complete');
          setResults(data);
        }
      }).catch(e => {
        if (!cancelled) setError('Scan failed: ' + e.message);
      });
      return () => { cancelled = true; };
    }, [siteUrl]);

    if (error) {
      return React.createElement('div', { className: 'ow-body' },
        React.createElement('div', { className: 'ow-icon', 'aria-hidden': 'true' }, '\u26A0\uFE0F'),
        React.createElement('h2', { className: 'ow-title' }, 'Scan ran into an issue'),
        React.createElement('p', { className: 'ow-sub' }, error),
        React.createElement('button', { className: 'ow-btn-primary', onClick: () => onNext(null) }, 'Continue anyway \u2192')
      );
    }

    if (!results) {
      return React.createElement('div', { className: 'ow-body' },
        React.createElement('div', { className: 'ow-icon', 'aria-hidden': 'true' }, '\uD83D\uDD0D'),
        React.createElement('h2', { className: 'ow-title' }, 'Scanning ' + (siteUrl || 'your site')),
        React.createElement('p', { className: 'ow-sub' }, 'This takes about 30 seconds\u2026'),
        React.createElement('div', { className: 'ow-scan-progress', role: 'progressbar', 'aria-valuenow': progress, 'aria-valuemin': 0, 'aria-valuemax': 100 },
          React.createElement('div', { className: 'ow-scan-bar-track' },
            React.createElement('div', { className: 'ow-scan-bar-fill', style: { width: progress + '%' } })
          ),
          React.createElement('p', { className: 'ow-scan-label', 'aria-live': 'polite' }, status)
        )
      );
    }

    const total = (results.total_issues || results.issue_count || 0);
    const critical = (results.critical || 0);
    return React.createElement('div', { className: 'ow-body' },
      React.createElement('div', { className: 'ow-icon', 'aria-hidden': 'true' }, total > 0 ? '\uD83D\uDCCB' : '\uD83C\uDF89'),
      React.createElement('h2', { className: 'ow-title' }, 'Scan complete'),
      total > 0
        ? React.createElement(React.Fragment, null,
            React.createElement('div', { className: 'ow-issue-summary' }, total + ' issues found'),
            React.createElement('p', { className: 'ow-issue-sub' },
              critical > 0 ? critical + ' critical \u00B7 ' : '',
              (results.pages_scanned || 1) + ' pages scanned'
            )
          )
        : React.createElement('p', { className: 'ow-sub' }, 'No major issues found. Great start!'),
      React.createElement('button', { className: 'ow-btn-primary', onClick: () => onNext(results) }, 'See what to fix \u2192')
    );
  }

  function StepQuickWin({ results, onNext }) {
    const issues = (results && results.top_issues) || [];
    const first = issues[0];
    const winText = first
      ? { text: 'Fix ' + (first.count || 'several') + ' ' + (first.description || 'issues').toLowerCase(), sub: 'One-click fix available in the Scanner' }
      : { text: 'Review your full scan results', sub: 'See all issues in the Scanner tab' };

    return React.createElement('div', { className: 'ow-body' },
      React.createElement('div', { className: 'ow-icon', 'aria-hidden': 'true' }, '\u26A1\uFE0F'),
      React.createElement('h2', { className: 'ow-title' }, 'Quick win'),
      React.createElement('p', { className: 'ow-sub' }, 'Here\u2019s the highest-impact thing to fix right now:'),
      React.createElement('div', { className: 'ow-quick-win' },
        React.createElement('div', { className: 'ow-quick-win-label' }, 'Recommended fix'),
        React.createElement('div', { className: 'ow-quick-win-text' }, winText.text),
        React.createElement('div', { className: 'ow-quick-win-sub' }, winText.sub)
      ),
      React.createElement('button', { className: 'ow-btn-primary', onClick: onNext }, 'Show me how \u2192')
    );
  }

  function StepDone({ onFinish }) {
    const nextSteps = [
      { icon: '\u2795', label: 'Add more sites', sub: 'Connect client sites to track', action: 'sites' },
      { icon: '\uD83D\uDD0C', label: 'Install the plugin', sub: 'Unlock scheduled scans + auto-fix', action: 'plugin' },
      { icon: '\uD83D\uDCCA', label: 'View full scan results', sub: 'See every issue across all pages', action: 'scanner' },
    ];
    return React.createElement('div', { className: 'ow-body' },
      React.createElement('div', { className: 'ow-icon', 'aria-hidden': 'true' }, '\uD83C\uDF89'),
      React.createElement('h2', { className: 'ow-title' }, 'You\u2019re all set'),
      React.createElement('p', { className: 'ow-sub' }, 'Here\u2019s what you can do next:'),
      React.createElement('div', { className: 'ow-next-steps' },
        nextSteps.map(s => React.createElement('button', {
          key: s.action, className: 'ow-next-card',
          onClick: () => onFinish(s.action),
          'aria-label': s.label,
        },
          React.createElement('span', { className: 'ow-next-card-icon', 'aria-hidden': 'true' }, s.icon),
          React.createElement('div', { className: 'ow-next-card-text' },
            React.createElement('strong', null, s.label),
            React.createElement('span', null, s.sub)
          )
        ))
      ),
      React.createElement('button', { className: 'ow-btn-secondary', onClick: () => onFinish('dashboard') }, 'Go to Dashboard')
    );
  }

  /* ─── Root component ─────────────────────────────────────── */
  function OnboardingWizard({ onComplete }) {
    const [step, setStep] = React.useState(0);
    const [siteUrl, setSiteUrl] = React.useState('');
    const [scanResults, setScanResults] = React.useState(null);
    const TOTAL = 5;

    async function markComplete(action) {
      try { await apiFetch('/account/onboarding/complete', { method: 'POST', body: JSON.stringify({ step_completed: 'all', site_url: siteUrl || undefined }) }); }
      catch (e) { console.warn('[OnboardingWizard] complete failed:', e.message); }
      onComplete && onComplete(action);
    }

    async function handleSkip() { await markComplete('skip'); }

    const steps = [
      React.createElement(StepWelcome, { key: 0, onNext: () => setStep(1) }),
      React.createElement(StepConnect, { key: 1, onNext: url => { setSiteUrl(url); setStep(2); }, onSkip: () => setStep(2) }),
      React.createElement(StepScan, { key: 2, siteUrl, onNext: r => { setScanResults(r); setStep(r && (r.total_issues || r.issue_count) > 0 ? 3 : 4); } }),
      React.createElement(StepQuickWin, { key: 3, results: scanResults, onNext: () => setStep(4) }),
      React.createElement(StepDone, { key: 4, onFinish: markComplete }),
    ];

    return React.createElement(React.Fragment, null,
      React.createElement('style', null, CSS),
      React.createElement('div', {
        className: 'ow-overlay',
        role: 'dialog',
        'aria-modal': 'true',
        'aria-label': 'Getting started with WPSiteBeam',
      },
        React.createElement('div', { className: 'ow-card' },
          React.createElement('div', { className: 'ow-progress' },
            React.createElement('div', { className: 'ow-progress-fill', style: { width: ((step / (TOTAL - 1)) * 100) + '%' } })
          ),
          React.createElement('div', { className: 'ow-header' },
            React.createElement('span', { className: 'ow-step-label' }, 'Step ' + (step + 1) + ' of ' + TOTAL),
            step < TOTAL - 1 && React.createElement('button', {
              className: 'ow-skip-btn', onClick: handleSkip, 'aria-label': 'Skip setup',
            }, 'Skip setup')
          ),
          steps[step]
        )
      )
    );
  }

  window.OnboardingWizard = OnboardingWizard;
})();
