/* ═══════════════════════════════════════════════════════════════════
   WizardShell.jsx — the ONE config-driven wizard shell chrome (§5a).
   Header + step-bar (3 variants + responsive) + content slot + footer nav +
   progress. Ported from Claude Design v2 deliverable (Increment 2).
   Load AFTER WizardIcons.jsx + WizardPrimitives.jsx.
   Registers (bare globals + window.WPSB.Wizard.*):
     WizardShell, FooterNav, StepNode, VerticalRail, HorizontalStepper,
     NumberedStepper, CompactProgress

   NOTE: Design owns this visual shell. Behavior (config-driven step engine,
   deferred atomic commit, per-step telemetry, locked-CTA routing, plan-aware
   step sets, dirty-state) is layered on by the consuming surface (e.g. the
   bg-removal wizard in Increment 3) — this file is the chrome it renders into.
   ═══════════════════════════════════════════════════════════════════ */
(function () {
  const { useState, useEffect } = React;
  const tx = (k, v, f) => (window.WPSB && window.WPSB.t) ? window.WPSB.t(k, v, f) : (f != null ? f : k);
  const WIcon = window.WIcon;     // dependency (WizardIcons.jsx)
  const WTag  = window.WTag;      // dependency (WizardPrimitives.jsx)

  /* responsive width hook */
  function useViewport() {
    const [w, setW] = useState(typeof window !== 'undefined' ? window.innerWidth : 1200);
    useEffect(() => {
      const onR = () => setW(window.innerWidth);
      window.addEventListener('resize', onR);
      return () => window.removeEventListener('resize', onR);
    }, []);
    return w;
  }

  /* status node (shared by all variants) */
  function StepNode({ status, n, size = 30 }) {
    let bg = 'var(--surface-2)', color = 'var(--wiz-step-upcoming)', border = '1.5px solid var(--border-2)', ring = 'none';
    if (status === 'done') { bg = 'var(--wiz-step-done)'; color = 'var(--on-accent)'; border = '1.5px solid var(--wiz-step-done)'; }
    else if (status === 'current') { bg = 'var(--wiz-step-current)'; color = 'var(--on-accent)'; border = '1.5px solid var(--wiz-step-current)'; ring = '0 0 0 4px color-mix(in oklch, var(--wiz-step-current) 20%, transparent)'; }
    return React.createElement('span', {
      style: {
        width: size, height: size, borderRadius: '50%', background: bg, color, border,
        boxShadow: ring, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none',
        fontFamily: 'var(--font-mono)', fontWeight: 'var(--fw-bold)', fontSize: size * 0.43 + 'px',
        transition: 'all 200ms ease',
      },
    }, status === 'done' ? React.createElement(WIcon, { name: 'check', size: size * 0.5, stroke: 3 }) : n);
  }

  function statusFor(i, current) { return i < current ? 'done' : i === current ? 'current' : 'upcoming'; }

  /* ── Variant: VERTICAL RAIL ──────────────────────────────────────── */
  function VerticalRail({ steps, current, maxReached, onStepClick }) {
    return React.createElement('nav', { 'aria-label': tx('page.wizardshell.steps_aria', null, 'Wizard steps'), style: { display: 'flex', flexDirection: 'column', gap: 0 } },
      steps.map((s, i) => {
        const st = statusFor(i, current);
        const clickable = i <= maxReached;
        return React.createElement('div', { key: s.key, style: { display: 'flex', gap: 'var(--sp-3)', alignItems: 'stretch' } },
          React.createElement('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 'none' } },
            React.createElement(StepNode, { status: st, n: i + 1 }),
            i < steps.length - 1 && React.createElement('span', {
              style: { width: 2, flex: 1, minHeight: 26, marginTop: 4, marginBottom: 4, background: i < current ? 'var(--wiz-rail-done)' : 'var(--wiz-rail)', borderRadius: 2, transition: 'background 200ms ease' },
            })
          ),
          React.createElement('button', {
            type: 'button', disabled: !clickable, onClick: () => clickable && onStepClick(i),
            className: clickable ? 'wiz-focusable' : '',
            style: { textAlign: 'left', background: 'none', border: 'none', padding: '3px 0 22px', cursor: clickable ? 'pointer' : 'default', flex: 1 },
          },
            React.createElement('div', { style: { fontWeight: 'var(--fw-label)', fontSize: '.9rem', color: st === 'upcoming' ? 'var(--dim)' : 'var(--text)' } }, s.title),
            s.subtitle && React.createElement('div', { style: { fontSize: '.76rem', color: 'var(--muted)', marginTop: 2 } }, s.subtitle),
            s.locked && React.createElement('span', { style: { display: 'inline-flex', marginTop: 6 } }, React.createElement(WTag, { label: s.locked, kind: 'tier' }))
          )
        );
      })
    );
  }

  /* ── Variant: HORIZONTAL STEPPER ─────────────────────────────────── */
  function HorizontalStepper({ steps, current, maxReached, onStepClick }) {
    return React.createElement('nav', { 'aria-label': tx('page.wizardshell.steps_aria', null, 'Wizard steps'), style: { display: 'flex', alignItems: 'center', gap: 0, width: '100%' } },
      steps.map((s, i) => {
        const st = statusFor(i, current);
        const clickable = i <= maxReached;
        return React.createElement(React.Fragment, { key: s.key },
          React.createElement('button', {
            type: 'button', disabled: !clickable, onClick: () => clickable && onStepClick(i),
            className: clickable ? 'wiz-focusable' : '',
            style: { display: 'flex', alignItems: 'center', gap: 'var(--sp-3)', flex: 'none', background: st === 'current' ? 'var(--beam-dim)' : 'transparent', border: '1px solid ' + (st === 'current' ? 'color-mix(in oklch, var(--beam) 30%, transparent)' : 'transparent'), borderRadius: 'var(--r)', padding: '8px 14px 8px 8px', cursor: clickable ? 'pointer' : 'default' },
          },
            React.createElement(StepNode, { status: st, n: i + 1, size: 32 }),
            React.createElement('span', { style: { textAlign: 'left' } },
              React.createElement('span', { style: { display: 'block', fontWeight: 'var(--fw-label)', fontSize: '.86rem', color: st === 'upcoming' ? 'var(--dim)' : 'var(--text)' } }, s.title),
              s.subtitle && React.createElement('span', { style: { display: 'block', fontSize: '.72rem', color: 'var(--muted)' } }, s.subtitle)
            )
          ),
          i < steps.length - 1 && React.createElement('span', { style: { flex: 1, height: 2, minWidth: 16, margin: '0 var(--sp-2)', background: i < current ? 'var(--wiz-rail-done)' : 'var(--wiz-rail)', borderRadius: 2 } })
        );
      })
    );
  }

  /* ── Variant: NUMBERED ───────────────────────────────────────────── */
  function NumberedStepper({ steps, current, maxReached, onStepClick }) {
    return React.createElement('nav', { 'aria-label': tx('page.wizardshell.steps_aria', null, 'Wizard steps'), style: { display: 'flex', alignItems: 'flex-start', justifyContent: 'center', gap: 0, width: '100%' } },
      steps.map((s, i) => {
        const st = statusFor(i, current);
        const clickable = i <= maxReached;
        return React.createElement(React.Fragment, { key: s.key },
          React.createElement('button', {
            type: 'button', disabled: !clickable, onClick: () => clickable && onStepClick(i),
            className: clickable ? 'wiz-focusable' : '',
            style: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, flex: 'none', width: 96, background: 'none', border: 'none', cursor: clickable ? 'pointer' : 'default', padding: 0 },
          },
            React.createElement(StepNode, { status: st, n: i + 1, size: 26 }),
            React.createElement('span', { style: { fontFamily: 'var(--font-mono)', fontSize: '.66rem', letterSpacing: '.04em', textAlign: 'center', textTransform: 'uppercase', fontWeight: 'var(--fw-mono-small)', color: st === 'current' ? 'var(--beam)' : st === 'upcoming' ? 'var(--dim)' : 'var(--text-2)' } }, s.title)
          ),
          i < steps.length - 1 && React.createElement('span', { style: { flex: 'none', width: 40, height: 2, marginTop: 12, background: i < current ? 'var(--wiz-rail-done)' : 'var(--wiz-rail)', borderRadius: 2 } })
        );
      })
    );
  }

  /* ── Compact responsive progress header (mobile) ─────────────────── */
  function CompactProgress({ steps, current }) {
    const pct = Math.round(((current) / (steps.length - 1)) * 100);
    return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 'var(--sp-3)' } },
        React.createElement(StepNode, { status: 'current', n: current + 1, size: 30 }),
        React.createElement('div', { style: { flex: 1, minWidth: 0 } },
          React.createElement('div', { style: { fontWeight: 'var(--fw-label)', fontSize: '.9rem', color: 'var(--text)' } }, steps[current].title),
          React.createElement('div', { className: 'wiz-eyebrow', style: { fontSize: '.62rem' } }, tx('page.wizardshell.step_of', { n: current + 1, total: steps.length }, 'Step {n} of {total}'))
        )
      ),
      React.createElement('div', { style: { height: 5, background: 'var(--wiz-rail)', borderRadius: 999, overflow: 'hidden' } },
        React.createElement('div', { style: { width: pct + '%', height: '100%', background: 'var(--wiz-step-current)', borderRadius: 999, transition: 'width 300ms cubic-bezier(0.16,1,0.3,1)' } }))
    );
  }

  /* ── Footer nav ──────────────────────────────────────────────────── */
  function FooterNav({ onBack, onNext, onSkip, onFinish, canBack, canSkip, isLast, nextLabel, finishLabel }) {
    return React.createElement('div', {
      style: { display: 'flex', alignItems: 'center', gap: 'var(--sp-3)', flexWrap: 'wrap', paddingTop: 'var(--sp-4)', marginTop: 'var(--sp-5)', borderTop: '1px solid var(--border)' },
    },
      React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-secondary', disabled: !canBack, onClick: onBack }, React.createElement(WIcon, { name: 'chevron-left', size: 16 }), tx('page.wizardshell.back', null, 'Back')),
      React.createElement('div', { style: { flex: 1 } }),
      canSkip && !isLast && React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-ghost', onClick: onSkip }, tx('page.wizardshell.skip', null, 'Skip for now')),
      isLast
        ? React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-primary', onClick: onFinish }, React.createElement(WIcon, { name: 'check', size: 16, stroke: 3 }), finishLabel || tx('page.wizardshell.finish', null, 'Finish'))
        : React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-primary', onClick: onNext }, nextLabel || tx('page.wizardshell.next', null, 'Next'), React.createElement(WIcon, { name: 'chevron-right', size: 16 }))
    );
  }

  /* ── The shell ───────────────────────────────────────────────────── */
  function WizardShell(props) {
    const { eyebrow, title, subtitle, steps, current, maxReached, stepVariant = 'vertical', onStepClick, children, footer } = props;
    const vw = useViewport();
    const isMobile = vw < 760;
    const pct = Math.round((current / (steps.length - 1)) * 100);

    const Variant = stepVariant === 'horizontal' ? HorizontalStepper : stepVariant === 'numbered' ? NumberedStepper : VerticalRail;
    const useVerticalLayout = stepVariant === 'vertical' && !isMobile;

    const header = React.createElement('header', { style: { marginBottom: 'var(--sp-5)' } },
      React.createElement('div', { className: 'wiz-eyebrow', style: { marginBottom: 8 } }, eyebrow),
      React.createElement('h1', { className: 'wiz-title', style: { margin: 0, fontSize: '1.6rem' } }, title),
      subtitle && React.createElement('p', { style: { margin: '8px 0 0', color: 'var(--text-2)', fontSize: '.92rem', maxWidth: 560, lineHeight: 1.5 } }, subtitle)
    );

    const topStepper = (!useVerticalLayout) && React.createElement('div', {
      style: { padding: 'var(--sp-4) 0', marginBottom: 'var(--sp-5)', borderBottom: '1px solid var(--border)', overflowX: 'auto' },
    }, isMobile ? React.createElement(CompactProgress, { steps, current }) : React.createElement(Variant, { steps, current, maxReached, onStepClick }));

    const content = React.createElement('div', { role: 'group', 'aria-label': steps[current].title }, children, React.createElement(FooterNav, footer));

    const progressBar = React.createElement('div', { style: { height: 4, background: 'var(--surface-2)', position: 'relative' } },
      React.createElement('div', { style: { position: 'absolute', inset: 0, width: pct + '%', background: 'linear-gradient(90deg, var(--wiz-step-done), var(--wiz-step-current))', transition: 'width 350ms cubic-bezier(0.16,1,0.3,1)' } }),
      React.createElement('span', { style: { position: 'absolute', right: 14, top: 10, fontFamily: 'var(--font-mono)', fontSize: '.62rem', letterSpacing: '.1em', color: 'var(--dim)' } }, pct + '%')
    );

    return React.createElement('section', {
      className: 'wiz-card',
      style: { background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-xl)', overflow: 'hidden', boxShadow: 'var(--shadow-lg)' },
    },
      progressBar,
      React.createElement('div', { style: { padding: 'var(--sp-7)' } },
        useVerticalLayout
          ? React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '232px 1px 1fr', gap: 'var(--sp-7)', alignItems: 'start' } },
              React.createElement('div', null,
                React.createElement('div', { className: 'wiz-eyebrow', style: { marginBottom: 'var(--sp-5)' } }, tx('page.wizardshell.setup', null, 'Setup')),
                React.createElement(VerticalRail, { steps, current, maxReached, onStepClick })
              ),
              React.createElement('div', { style: { background: 'var(--border)', alignSelf: 'stretch' } }),
              React.createElement('div', { style: { minWidth: 0 } }, header, content)
            )
          : React.createElement('div', null, header, topStepper, content)
      )
    );
  }

  const exports = { WizardShell, FooterNav, StepNode, VerticalRail, HorizontalStepper, NumberedStepper, CompactProgress };
  Object.assign(window, exports);
  window.WPSB = window.WPSB || {};
  window.WPSB.Wizard = Object.assign(window.WPSB.Wizard || {}, exports);
  console.log('[WPSB Wizard] Shell loaded (config-driven chrome + 3 step-bar variants).');
})();
