// ManagedScanForm — top-level multi-step managed scan intake container.

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

  const PAYMENT_ENABLED = false;
  const STORAGE_KEY = 'sekura_managed_scan';

  const ALL_STEPS = [
    { id: 'identity',  label: 'identity',  component: window.ScanStep1Identity,  enabled: true },
    { id: 'cloud',     label: 'cloud',     component: window.ScanStep2Cloud,     enabled: true },
    { id: 'target',    label: 'targets',   component: window.ScanStep3Target,    enabled: true },
    { id: 'review',    label: 'review',    component: window.ScanStep4Review,    enabled: true },
    { id: 'payment',   label: 'payment',   component: window.ScanStep5Payment,   enabled: PAYMENT_ENABLED },
    { id: 'authorize', label: 'authorize', component: window.ScanStep6Auth,      enabled: true },
  ];

  const STEPS = ALL_STEPS.filter(s => s.enabled);
  const TOTAL_STEPS = STEPS.length;

  const EMPTY_FORM = {
    // step 1: identity
    fullName: '',
    workEmail: '',
    company: '',
    companyDomain: '',
    role: '',
    companySize: '',
    industry: '',
    // step 2: cloud
    cloudProvider: '',
    aws_region: 'us-east-1',
    aws_vpc_id: '',
    aws_subnet_id: '',
    aws_instance_type: 'm5.xlarge',
    aws_key_name: '',
    azure_subscription_id: '',
    azure_location: 'eastus',
    azure_vm_size: 'Standard_D4s_v5',
    azure_ssh_public_key: '',
    azure_resource_group_name: '',
    azure_vnet_name: '',
    azure_subnet_id: '',
    gcp_project_id: '',
    gcp_region: 'us-central1',
    gcp_zone: 'us-central1-a',
    gcp_machine_type: 'e2-standard-4',
    gcp_network: 'default',
    gcp_subnet: 'default',
    // step 3: target
    targetCidrs: [],
    scanEnvironment: '',
    scanScope: '',
    scanWindow: '',
    scanWindowDetail: '',
    additionalNotes: '',
    // step 6: authorization
    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 [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);
  const [submissionId, setSubmissionId] = useState(null);
  const [docUrl, setDocUrl] = useState(null);

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

  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);
  }

  async function handleSubmit(turnstileToken) {
    setSubmitting(true);
    setSubmitError(null);

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

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

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

      if (json.submissionId) setSubmissionId(json.submissionId);
      if (json.docUrl) setDocUrl(json.docUrl);
      sessionStorage.removeItem(STORAGE_KEY);
      setSubmitted(true);
    } catch (err) {
      setSubmitError('network error — please check your connection and try again');
    } finally {
      setSubmitting(false);
    }
  }

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

  // Step indicator labels
  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 isLast = stepIndex === TOTAL_STEPS - 1;

    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 (isLast) {
      return <StepComponent {...baseProps} onBack={handleBack} onSubmit={handleSubmit} submitting={submitting} error={submitError} />;
    }

    return <StepComponent {...baseProps} onNext={handleNext} onBack={handleBack} />;
  }

  return (
    <React.Fragment>
      <header className="hero-nav">
        <div className="nav-brand">
          <a href="#">
            <img src="branding/sekura-logo.svg" alt="sekura" height="28" />
          </a>
        </div>
        <nav className="nav-links">
          <a href="#">the story</a>
          <a href="#product">product</a>
          <a href="#team">team</a>
          <a href="#login" className="nav-login">log in</a>
        </nav>
      </header>

      <div className="intake-page">
        <div className="intake-inner">
          {submitted ? (
            <window.ScanSuccessScreen data={formData} />
          ) : (
            <React.Fragment>
              <h1 className="intake-title">managed scan</h1>
              <p className="intake-sub">
                configure your cloud environment and scan targets. we'll generate an authorization document for you to sign.
              </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()}
            </React.Fragment>
          )}
        </div>
      </div>
    </React.Fragment>
  );
}

window.ManagedScanForm = ManagedScanForm;
