// Flow — the stepped creation wizard.
// Each step is its own full window; the progress rail lives on the left.

const { useState: useStateF, useEffect: useEffectF } = React;

const Flow = ({ initialDraft, onCancel, onSave, onLaunch }) => {
  const { STEPS } = window;
  const [draft, setDraft] = useStateF(() => initialDraft);
  const [stepIdx, setStepIdx] = useStateF(0);

  // Validation per step
  const stepValid = {
    type:     () => !!draft.type,
    identity: () => !!draft.name && !!draft.id,
    brand:    () => !!draft.brand && draft.geos.length > 0 && !!draft.defaultUrl,
    routing:  () => draft.geos.length > 0,
    tracking: () => true,                            // optional
    locales:  () => draft.locales.length > 0,
    review:   () => true,
  };

  const currentStep = STEPS[stepIdx];
  const canAdvance = stepValid[currentStep.id]();

  const jumpTo = (i) => {
    // Allow jumping to any step <= furthest completed + 1
    setStepIdx(i);
  };

  const next = () => {
    if (!canAdvance) {
      window.toast('Complete required fields first', 'error');
      return;
    }
    if (stepIdx < STEPS.length - 1) setStepIdx(stepIdx + 1);
  };
  const prev = () => stepIdx > 0 && setStepIdx(stepIdx - 1);

  // Keyboard shortcuts
  useEffectF(() => {
    const onKey = (e) => {
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
      if (e.key === 'ArrowRight') next();
      if (e.key === 'ArrowLeft') prev();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  });

  // Step component selector
  const StepComp = {
    type: window.Step1Type,
    identity: window.Step2Identity,
    brand: window.Step3Brand,
    routing: window.Step4Routing,
    tracking: window.Step5Tracking,
    locales: window.Step6Locales,
    review: window.Step7Review,
  }[currentStep.id];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '232px 1fr', minHeight: '100%' }}>
      {/* Progress rail */}
      <div style={{
        borderRight: '1px solid var(--line-soft)',
        padding: '32px 18px',
        position: 'sticky', top: 53, height: 'calc(100vh - 53px)',
        background: 'var(--bg-1)',
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{
          fontSize: 10.5, color: 'var(--muted)', textTransform: 'uppercase',
          letterSpacing: '0.1em', fontWeight: 600, marginBottom: 14, paddingLeft: 4,
          fontFamily: 'JetBrains Mono, monospace',
        }}>
          {draft._editing ? 'Editing' : 'New app'}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2, position: 'relative' }}>
          {/* vertical line */}
          <div style={{
            position: 'absolute', top: 18, bottom: 14, left: 14,
            width: 1, background: 'var(--line)', zIndex: 0,
          }}></div>

          {STEPS.map((s, i) => {
            const isActive = i === stepIdx;
            const isDone = i < stepIdx;
            const isFuture = i > stepIdx;
            return (
              <div
                key={s.id}
                onClick={() => jumpTo(i)}
                style={{
                  display: 'grid', gridTemplateColumns: '28px 1fr',
                  gap: 12,
                  padding: '10px 4px',
                  borderRadius: 7,
                  cursor: 'pointer',
                  alignItems: 'flex-start',
                  position: 'relative',
                  zIndex: 1,
                  background: isActive ? 'var(--bg-2)' : 'transparent',
                  transition: 'background 0.12s',
                }}>
                <div style={{
                  width: 28, height: 28, borderRadius: '50%',
                  background: isDone ? 'var(--accent)' : (isActive ? 'var(--bg-1)' : 'var(--bg-3)'),
                  border: `1.5px solid ${isDone ? 'var(--accent)' : (isActive ? 'var(--accent)' : 'var(--line)')}`,
                  display: 'grid', placeItems: 'center',
                  color: isDone ? '#001a0c' : (isActive ? 'var(--accent)' : 'var(--muted)'),
                  fontSize: 11, fontWeight: 600,
                  fontFamily: 'JetBrains Mono, monospace',
                  transition: 'all 0.15s',
                  boxShadow: isActive ? '0 0 0 3px rgba(0,208,132,0.15)' : 'none',
                }}>
                  {isDone ? <window.IconCheck size={13} sw={3} /> : (i + 1)}
                </div>
                <div style={{ paddingTop: 4 }}>
                  <div style={{
                    fontSize: 13,
                    fontWeight: isActive ? 600 : 500,
                    color: isFuture ? 'var(--muted)' : 'var(--text)',
                    lineHeight: 1.2,
                  }}>{s.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--muted-2)', marginTop: 2, lineHeight: 1.3 }}>{s.desc}</div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Bottom helper */}
        <div style={{
          marginTop: 'auto',
          fontSize: 11, color: 'var(--muted-2)',
          padding: '10px 12px', background: 'var(--bg-0)',
          borderRadius: 7, border: '1px solid var(--line-soft)',
          lineHeight: 1.5,
        }}>
          <div style={{ color: 'var(--muted)', marginBottom: 4, fontWeight: 600 }}>Tip</div>
          Use <code style={{ background: 'var(--bg-2)', padding: '1px 4px', borderRadius: 3 }}>← →</code> to navigate steps.
        </div>
      </div>

      {/* Step content */}
      <div style={{ padding: '32px 40px 100px', maxWidth: 1100, position: 'relative' }}>
        <div key={currentStep.id}>
          {StepComp && <StepComp draft={draft} setDraft={setDraft} onLaunch={() => onLaunch?.(draft)} />}
        </div>

        {/* Sticky action bar */}
        <div style={{
          position: 'fixed', bottom: 0, left: 248 + 232, right: 0,
          background: 'rgba(7,9,15,0.94)',
          backdropFilter: 'blur(10px)',
          borderTop: '1px solid var(--line-soft)',
          padding: '14px 40px',
          display: 'flex', alignItems: 'center', gap: 12,
          zIndex: 5,
        }}>
          <button className="btn ghost" onClick={onCancel}>
            <window.IconX size={13} />Cancel
          </button>

          <div style={{ width: 1, height: 22, background: 'var(--line)' }}></div>

          <button className="btn secondary" disabled={stepIdx === 0} onClick={prev}
                  style={{ opacity: stepIdx === 0 ? 0.4 : 1 }}>
            <window.IconChevronLeft size={13} />Back
          </button>

          <div style={{ flex: 1 }}></div>

          <button className="btn ghost" onClick={() => { onSave?.(draft); }}>
            Save draft
          </button>

          {stepIdx < STEPS.length - 1 ? (
            <button className="btn primary" onClick={next} disabled={!canAdvance}
                    style={{ opacity: canAdvance ? 1 : 0.4 }}>
              Continue
              <window.IconChevronRight size={13} />
            </button>
          ) : (
            <button className="btn primary" onClick={() => onLaunch?.(draft)}>
              <window.IconRocket size={13} />
              {draft._editing ? 'Save & deploy' : 'Launch'}
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

window.Flow = Flow;
