// ManagedScanForm — multi-step managed web-app scan order container.
// identity → target → review+authorize → payment (Stripe Checkout redirect).

function ManagedScanForm() {
  const { React } = window;
  const { useState, useEffect, useRef } = React;

  const STORAGE_KEY = 'sekura_managed_scan_v2';

  const STEPS = [
    { id: 'identity', label: 'identity', component: window.ScanStep1Identity },
    { id: 'target',   label: 'target',   component: window.ScanStep2Target },
    { id: 'review',   label: 'review',   component: window.ScanStep4Review },
    { id: 'payment',  label: 'payment',  component: window.ScanStep5Payment },
  ];
  const TOTAL_STEPS = STEPS.length;

  const EMPTY_FORM = {
    // step 1: identity
    fullName: '',
    workEmail: '',
    company: '',
    // step 2: target
    scanType: '',
    repoUrl: '',
    repoBranch: '',
    liveUrl: '',
    additionalNotes: '',
    // step 3: authorization (click-wrap)
    authorizationConfirmed: false,
    termsAccepted: false,
    dataProcessingAccepted: false,
  };

  function loadSaved() {
    try {
      const raw = sessionStorage.getItem(STORAGE_KEY);
      if (raw) {
        const saved = JSON.parse(raw);
        return { form: { ...EMPTY_FORM, ...saved.form }, step: saved.step || 0 };
      }
    } catch {}
    return { form: EMPTY_FORM, step: 0 };
  }

  const saved = useRef(loadSaved());
  const [stepIndex, setStepIndex] = useState(saved.current.step);
  const [formData, setFormData] = useState(saved.current.form);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);

  useEffect(() => {
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify({ form: formData, step: stepIndex }));
  }, [formData, stepIndex]);

  function update(patch) {
    setFormData(prev => ({ ...prev, ...patch }));
  }

  function handleNext() {
    setStepIndex(s => Math.min(s + 1, TOTAL_STEPS - 1));
    window.scrollTo(0, 0);
  }

  function handleBack() {
    setStepIndex(s => Math.max(s - 1, 0));
    window.scrollTo(0, 0);
  }

  function goToStep(stepNum) {
    setStepIndex(stepNum - 1);
    window.scrollTo(0, 0);
  }

  // Submit the order; on success the server returns a Stripe Checkout URL
  // and we leave the site. The status page (success_url) takes over after
  // payment.
  async function handleSubmit() {
    setSubmitting(true);
    setSubmitError(null);

    try {
      const res = await fetch('/api/managed-scan', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(formData),
      });

      const json = await res.json().catch(() => ({}));

      if (!res.ok || !json.checkoutUrl) {
        setSubmitError(json.error || 'something went wrong — please try again or email hello@sekura.ai');
        setSubmitting(false);
        return;
      }

      sessionStorage.removeItem(STORAGE_KEY);
      window.location.href = json.checkoutUrl;
    } catch (err) {
      setSubmitError('network error — please check your connection and try again');
      setSubmitting(false);
    }
  }

  const currentStep = STEPS[stepIndex];
  const stepNum = stepIndex + 1;
  const stepLabel = `step ${stepNum} of ${TOTAL_STEPS} — ${currentStep.label}`;

  const labels = STEPS.map(s => s.label);
  const siSteps = [];
  for (let i = 0; i < TOTAL_STEPS; i++) {
    siSteps.push({ num: i + 1, isDone: i < stepIndex, isActive: i === stepIndex });
  }

  function renderStep() {
    const StepComponent = currentStep.component;
    const baseProps = { data: formData, update, stepLabel };

    if (stepIndex === 0) {
      return <StepComponent {...baseProps} onNext={handleNext} />;
    }
    if (currentStep.id === 'review') {
      return <StepComponent {...baseProps} onNext={handleNext} onBack={handleBack} goToStep={goToStep} />;
    }
    if (currentStep.id === 'payment') {
      return <StepComponent {...baseProps} onBack={handleBack} onSubmit={handleSubmit} submitting={submitting} error={submitError} />;
    }
    return <StepComponent {...baseProps} onNext={handleNext} onBack={handleBack} />;
  }

  return (
    <React.Fragment>
      <div className="intake-page">
        <div className="intake-inner">
          <h1 className="intake-title">managed scan</h1>
          <p className="intake-sub">
            point us at your repository and/or live application, pay with a card,
            and get a full security report — no calls, no contracts.
          </p>

          <div className="step-indicator">
            <div className="si-steps">
              {siSteps.map((s, idx) => (
                <React.Fragment key={s.num}>
                  <div className={`si-step${s.isActive ? ' is-active' : ''}${s.isDone ? ' is-done' : ''}`}>
                    <div className="si-circle">{s.isDone ? '✓' : s.num}</div>
                    <div className="si-label">{labels[idx] || ''}</div>
                  </div>
                  {idx < siSteps.length - 1 && (
                    <div className={`si-line${s.isDone ? ' is-done' : ''}`} />
                  )}
                </React.Fragment>
              ))}
            </div>
          </div>

          {renderStep()}
        </div>
      </div>

    </React.Fragment>
  );
}

window.ManagedScanForm = ManagedScanForm;
