// ScanYourRepo — the converting section. Paste a repo → animated phase-1 preview
// (engine progress only, no fabricated findings) → consent + email gate that
// queues a REAL SAST scan (emailed within 24h) and, on consent, feeds the
// company logo onto the ScanBand wall.
//
// Two presentations, one set of behaviour:
//   default        the cream <section> used on /product/proof-not-probability/
//   variant="apple" a bare pill field for the white landing-page hero. The
//                   hero supplies its own headline and lede, so the section
//                   header is skipped entirely.
// Everything else — validation, useLiveScan, EmailGate, Turnstile, the
// /api/free-scan submit — is shared. id="scan" is on the outer element in both
// presentations because nine places across the site link to /#scan, including
// an absolute URL in components/blog/Post847.jsx.
function ScanYourRepo({
  eyebrow,
  heading,
  sub,
  fineprint,
  variant,
  defaultUrl = 'github.com/saleor/saleor',
} = {}) {
  const { React, ScanProgress, EmailGate, useLiveScan } = window;
  const { useState } = React;
  const [url, setUrl] = useState(defaultUrl);
  const [emailSubmitted, setEmailSubmitted] = useState(false);
  const [emailValue, setEmailValue] = useState(null);
  const [urlError, setUrlError] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);
  const [queued, setQueued] = useState(null); // { status, jobId, message? }
  const { scan, run, cancel } = useLiveScan();

  const onSubmit = (e) => {
    e.preventDefault();
    setUrlError(null);
    const v = window.githubLib.validate(url);
    if (!v.ok) { setUrlError(v.error); return; }
    setEmailSubmitted(false);
    setSubmitError(null);
    setQueued(null);
    run(url);
  };

  // Real submission: queue the SAST scan on our infrastructure.
  const requestFullReport = async ({ email, consentScan, consentFeature, hp, turnstileToken, isPrivate, repoToken }) => {
    setSubmitting(true);
    setSubmitError(null);
    try {
      const res = await fetch('/api/free-scan', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ repoUrl: url, email, consentScan, consentFeature, hp, turnstileToken, isPrivate, repoToken }),
      });
      const data = await res.json().catch(() => ({}));
      if (!data.ok) {
        setSubmitError(data.error || 'something went wrong — try again or email hello@sekura.ai');
        return;
      }
      setEmailValue(email);
      setQueued({ status: data.status, jobId: data.jobId, message: data.message || null });
      setEmailSubmitted(true);
    } catch {
      setSubmitError('network error — try again or email hello@sekura.ai');
    } finally {
      setSubmitting(false);
    }
  };

  const isRunning = scan.status === 'running';
  const isDone    = scan.status === 'done';

  // The running/done stage is identical in both presentations; only the
  // wrapper class differs so styles.home.css can quiet it down on white.
  const stage = (isRunning || isDone) && (
    <div className={variant === 'apple' ? 'ah-scan-stage' : 'syr-stage'}>
      <ScanProgress scan={scan} onCancel={cancel} />

      {isDone && !emailSubmitted && (
        <EmailGate
          submitted={emailSubmitted}
          submitting={submitting}
          error={submitError}
          repoUrl={url}
          onSubmit={requestFullReport}
        />
      )}

      {isDone && emailSubmitted && queued && (
        <div className="syr-post">
          {queued.status === 'duplicate' ? (
            <>
              <div className="syr-post-title">recently scanned</div>
              <div className="syr-post-copy">{queued.message}</div>
            </>
          ) : (
            <>
              <div className="syr-post-title">
                ✓ scan queued — full report emailed to <span className="syr-post-email">{emailValue}</span> within 24h
              </div>
              <div className="syr-post-copy">
                that was a phase-1 preview. the full run (recon, vuln agents, exploit,
                chain analysis) lands in your inbox. want it on a live target or on a
                schedule? we run those for you.
              </div>
            </>
          )}
          <div className="syr-post-ctas">
            <a href="/managed-scan/" className="cta cta--primary">
              schedule a managed scan <span className="cta-arrow">→</span>
            </a>
            <a href="/poc/" className="cta cta--ghost">talk to sales</a>
          </div>
        </div>
      )}
    </div>
  );

  // The landing hero no longer runs the scan inline: a scan is an attack, and
  // the disclosures at /authorize/ have to be signed against a named target
  // first. The field validates here so a typo is caught before the handoff.
  const goAuthorize = (e) => {
    e.preventDefault();
    setUrlError(null);
    const v = window.githubLib.validate(url);
    if (!v.ok) { setUrlError(v.error); return; }
    window.location.href = '/authorize/?repo=' + encodeURIComponent(url.trim());
  };

  if (variant === 'apple') {
    return (
      <div className="ah-scan" id="scan">
        <form className="ah-field" onSubmit={goAuthorize}>
          <input
            type="text"
            className="ah-field-input"
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            disabled={isRunning}
            placeholder="github.com/your-company/your-repo"
            aria-label="Repository URL"
            spellCheck={false} autoCorrect="off" autoCapitalize="off" />
          <button type="submit" className="ah-btn">Scan free</button>
        </form>

        <p className="ah-scan-note ah-caption">
          {urlError
            ? <span className="ah-scan-error">{urlError}</span>
            : (fineprint || 'Public or private repos. Full report in 24 hours. No card required.')}
        </p>

        {stage}
      </div>
    );
  }

  return (
    <section className="syr-section" data-screen-label="04 Scan Your Repo" id="scan">
      <div className="syr-inner">
        <header className="syr-header">
          <div className="syr-eyebrow">
            <span className="ph-line" /> {eyebrow || 'run it on your code · free, phase 1 only'}
          </div>
          <h2 className="syr-h2">
            {heading || 'stop reading. start scanning.'}
          </h2>
          <p className="syr-sub">
            {sub || (
              <React.Fragment>
                paste a github, gitlab or bitbucket repo — public or private. we'll run phase 1 —
                whitebox + sast, seven engines, zero traffic to your target — then email you the full report.
              </React.Fragment>
            )}
          </p>
        </header>

        <form className={`syr-form ${isRunning ? 'is-running' : ''}`} onSubmit={onSubmit}>
          <span className="syr-form-prefix">https://</span>
          <input
            type="text" className="syr-input"
            value={url} onChange={(e) => setUrl(e.target.value)}
            disabled={isRunning}
            placeholder="github.com/your/repo"
            spellCheck={false} autoCorrect="off" autoCapitalize="off" />
          {!isRunning ? (
            <button type="submit" className="syr-button">
              scan it <span className="cta-arrow">→</span>
            </button>
          ) : (
            <button type="button" className="syr-button syr-button--cancel" onClick={cancel}>
              cancel
            </button>
          )}
        </form>

        <div className="syr-fineprint">
          {urlError ? (
            <span className="syr-error">⚠ {urlError}</span>
          ) : (
            <span>
              {fineprint || (
                <React.Fragment>
                  public or private repos · source-code scan (whitebox + sast) ·
                  full report emailed within 24h
                </React.Fragment>
              )}
            </span>
          )}
        </div>

        {stage}
      </div>
    </section>
  );
}
window.ScanYourRepo = ScanYourRepo;
