import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import WelcomeStep from './steps/WelcomeStep';
import ConfigurationStep from './steps/ConfigurationStep';
import CompleteStep from './steps/CompleteStep';
import OnboardingMainDecor from './OnboardingMainDecor';

const STEP_COUNT = 3;

function getOnboardingData() {
  return window.wowextOnboarding || {};
}

function CloseIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
      <path d="M18 6 6 18M6 6l12 12" strokeLinecap="round" />
    </svg>
  );
}

export default function App() {
  const data = getOnboardingData();
  const S = data.strings || {};
  const steps = useMemo(
    () => [
      { id: 'welcome', label: S.stepWelcome || 'Welcome' },
      { id: 'configure', label: S.stepConfigure || 'Configuration' },
      { id: 'complete', label: S.stepComplete || 'Good to Go' },
    ],
    [S.stepWelcome, S.stepConfigure, S.stepComplete]
  );

  const [step, setStep] = useState(0);
  const [direction, setDirection] = useState(1);
  const [busy, setBusy] = useState(false);
  const contentRef = useRef(null);
  const onboardingRef = useRef(null);
  const stepRef = useRef(0);

  useEffect(() => {
    stepRef.current = step;
  }, [step]);

  const goToStep = useCallback((next, dir = 1) => {
    const clamped = Math.max(0, Math.min(next, STEP_COUNT - 1));
    setDirection(dir);
    setStep(clamped);
  }, []);

  const completeOnboarding = useCallback(async () => {
    if (busy) return;
    setBusy(true);
    const onboarding = getOnboardingData();
    try {
      const body = new URLSearchParams();
      body.append('action', 'wowexfow_complete_onboarding');
      body.append('nonce', onboarding.nonce || '');
      const res = await fetch(onboarding.ajaxUrl, {
        method: 'POST',
        body,
        credentials: 'same-origin',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
      });
      const json = await res.json();
      if (json.success && json.data?.redirect) {
        window.location.href = json.data.redirect;
        return;
      }
    } catch {
      /* fall through */
    }
    window.location.href = onboarding.homeUrl || '#';
  }, [busy]);

  /* Native click delegation — reliable inside WP admin alongside jQuery. */
  useEffect(() => {
    const root = onboardingRef.current;
    if (!root) return undefined;

    function onRootClick(event) {
      const target = event.target instanceof Element ? event.target.closest('[data-onboarding-action]') : null;
      if (!target || !root.contains(target)) return;

      const action = target.getAttribute('data-onboarding-action');
      if (!action) return;

      event.preventDefault();
      event.stopPropagation();

      if (action === 'next') {
        const current = stepRef.current;
        if (current < STEP_COUNT - 1) {
          goToStep(current + 1, 1);
        }
        return;
      }

      if (action === 'prev') {
        const current = stepRef.current;
        if (current > 0) {
          goToStep(current - 1, -1);
        }
        return;
      }

      if (action === 'goto') {
        const idx = Number.parseInt(target.getAttribute('data-onboarding-step') || '', 10);
        if (Number.isNaN(idx) || idx < 0 || idx >= STEP_COUNT) return;
        const current = stepRef.current;
        if (idx <= current + 1) {
          goToStep(idx, idx >= current ? 1 : -1);
        }
        return;
      }

      if (action === 'complete') {
        completeOnboarding();
      }
    }

    root.addEventListener('click', onRootClick, true);
    return () => root.removeEventListener('click', onRootClick, true);
  }, [goToStep, completeOnboarding]);

  useEffect(() => {
    window.wowextOnboardingNav = {
      next: () => {
        const current = stepRef.current;
        if (current < STEP_COUNT - 1) goToStep(current + 1, 1);
      },
      prev: () => {
        const current = stepRef.current;
        if (current > 0) goToStep(current - 1, -1);
      },
      goTo: (index) => goToStep(index, index >= stepRef.current ? 1 : -1),
    };
    return () => {
      delete window.wowextOnboardingNav;
    };
  }, [goToStep]);

  useEffect(() => {
    if (contentRef.current) {
      contentRef.current.focus({ preventScroll: true });
    }
  }, [step]);

  const animClass = direction >= 0 ? 'wowext-onboarding-step--enter-forward' : 'wowext-onboarding-step--enter-back';

  return (
    <div
      ref={onboardingRef}
      className="wowext-onboarding"
      role="dialog"
      aria-modal="true"
      aria-label={S.welcomeTitle || 'Onboarding'}
    >
      <header className="wowext-onboarding__header">
        <div className="wowext-onboarding__brand">
          {data.logoUrl && (
            <img src={data.logoUrl} alt="" className="wowext-onboarding__logo" width="40" height="40" />
          )}
          <div>
            <strong className="wowext-onboarding__brand-name">Wow Extensions</strong>
            <span className="wowext-onboarding__brand-version">v{data.version}</span>
          </div>
        </div>
        <button
          type="button"
          className="wowext-onboarding__close"
          data-onboarding-action="complete"
          disabled={busy}
          aria-label={S.close || 'Close'}
        >
          <CloseIcon />
        </button>
      </header>

      <nav className="wowext-onboarding__progress" aria-label="Setup progress">
        <ol className="wowext-onboarding__steps">
          {steps.map((s, i) => (
            <li key={s.id} className="wowext-onboarding__step-item">
              <button
                type="button"
                className={`wowext-onboarding__step-marker${i === step ? ' is-active' : ''}${i < step ? ' is-done' : ''}`}
                data-onboarding-action="goto"
                data-onboarding-step={i}
                aria-current={i === step ? 'step' : undefined}
                disabled={i > step + 1}
              >
                <span className="wowext-onboarding__step-num">{i < step ? '✓' : i + 1}</span>
                <span className="wowext-onboarding__step-label">{s.label}</span>
              </button>
              {i < steps.length - 1 && (
                <span
                  className={`wowext-onboarding__step-connector${i < step ? ' is-done' : ''}`}
                  aria-hidden="true"
                />
              )}
            </li>
          ))}
        </ol>
      </nav>

      <main className="wowext-onboarding__main">
        <OnboardingMainDecor />
        <div
          key={step}
          ref={contentRef}
          tabIndex={-1}
          className={`wowext-onboarding-step wowext-onboarding-step--${steps[step].id} ${animClass}`}
        >
          {step === 0 && <WelcomeStep strings={S} features={data.features || []} logoUrl={data.logoUrl} />}
          {step === 1 && <ConfigurationStep strings={S} />}
          {step === 2 && (
            <CompleteStep
              strings={S}
              docsUrl={data.docsUrl}
              supportUrl={data.supportUrl}
              tutorialsUrl={data.tutorialsUrl}
            />
          )}
        </div>
      </main>

      <footer className="wowext-onboarding__footer">
        <button
          type="button"
          className="button button-link wowext-onboarding__skip"
          data-onboarding-action="complete"
          disabled={busy}
        >
          {S.skip || 'Skip setup'}
        </button>
        <div className="wowext-onboarding__nav">
          {step > 0 && (
            <button type="button" className="button" data-onboarding-action="prev" disabled={busy}>
              {S.previous || 'Previous'}
            </button>
          )}
          {step < steps.length - 1 ? (
            <button type="button" className="button button-primary" data-onboarding-action="next" disabled={busy}>
              {S.next || 'Next'}
            </button>
          ) : (
            <button type="button" className="button button-primary" data-onboarding-action="complete" disabled={busy}>
              {S.goToDashboard || 'Go to Dashboard Home'}
            </button>
          )}
        </div>
      </footer>
    </div>
  );
}
