// EmailGate — collects email + consent and queues the REAL free scan.
// (The progress animation above it is an illustrative phase-1 preview; this is
// where the actual SAST scan is queued and the report emailed within 24h.)
//
// Supports private repositories: tick "private repository" and paste a read-only
// clone token (GitHub PAT / GitLab token / Bitbucket access token). The token is
// sent over HTTPS, used only to clone, and wiped after the scan.
//
// Bot-hardened: a hidden honeypot field plus Cloudflare Turnstile (rendered only
// when window.SEKURA_TURNSTILE_SITEKEY is set; otherwise skipped client-side and
// the server falls back to honeypot + rate limits).

// Host-aware token guidance, derived from the repo URL the user entered.
function tokenHint(repoUrl) {
  const h = String(repoUrl || '').toLowerCase();
  if (h.includes('gitlab.com')) {
    return { label: 'GitLab access token', hint: 'personal or project token with read_repository scope' };
  }
  if (h.includes('bitbucket.org')) {
    return { label: 'Bitbucket access token', hint: 'repository or workspace access token with Read scope' };
  }
  return { label: 'GitHub token (PAT)', hint: 'fine-grained token · Contents: Read · this repo only' };
}

function EmailGate({ onSubmit, submitted, submitting, error, repoUrl }) {
  const { React } = window;
  const { useState, useRef, useEffect } = React;
  const [email, setEmail] = useState('');
  const [touched, setTouched] = useState(false);
  const [consentScan, setConsentScan] = useState(false);
  const [consentFeature, setConsentFeature] = useState(true);
  const [isPrivate, setIsPrivate] = useState(false);
  const [repoToken, setRepoToken] = useState('');
  const [hp, setHp] = useState('');             // honeypot — humans leave blank
  const [tsToken, setTsToken] = useState('');   // Turnstile token

  const siteKey = (window.SEKURA_TURNSTILE_SITEKEY || '').trim();
  const needsTurnstile = !!siteKey;
  const tsRef = useRef(null);
  const widgetId = useRef(null);
  const tok = tokenHint(repoUrl);

  // Render the Turnstile widget once challenges.cloudflare.com/api.js is ready.
  useEffect(() => {
    if (!needsTurnstile || !tsRef.current) return undefined;
    let cancelled = false;
    let poll = 0;
    const doRender = () => {
      if (cancelled || widgetId.current !== null || !window.turnstile) return;
      try {
        widgetId.current = window.turnstile.render(tsRef.current, {
          sitekey: siteKey,
          theme: 'dark',
          callback: (t) => setTsToken(t),
          'expired-callback': () => setTsToken(''),
          'error-callback': () => setTsToken(''),
        });
      } catch (e) { /* api not ready yet — poll will retry */ }
    };
    if (window.turnstile) doRender();
    else poll = setInterval(() => { if (window.turnstile) { clearInterval(poll); doRender(); } }, 200);
    return () => { cancelled = true; if (poll) clearInterval(poll); };
  }, [siteKey]);

  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const tokenOk = !isPrivate || repoToken.trim().length >= 8;
  const canSubmit = emailValid && consentScan && tokenOk && !submitting && (!needsTurnstile || !!tsToken);

  if (submitted) return null;

  const submit = (e) => {
    e.preventDefault();
    if (!canSubmit) { setTouched(true); return; }
    onSubmit({
      email, consentScan, consentFeature, hp, turnstileToken: tsToken,
      isPrivate, repoToken: isPrivate ? repoToken.trim() : '',
    });
  };

  return (
    <div className="email-gate">
      <div className="eg-inner">
        <div className="eg-title">
          <span className="eg-lock">⏿</span>
          <span>get your full report — emailed within 24h</span>
        </div>
        <div className="eg-sub">
          we run the full scan on our infrastructure and email you the interactive
          HTML report. no drip, no list.
        </div>

        <form className="eg-form eg-form--stacked" onSubmit={submit}>
          <input
            type="email" placeholder="you@work.com" autoComplete="email"
            value={email} onChange={(e) => setEmail(e.target.value)}
            onBlur={() => setTouched(true)} />

          {/* honeypot — off-screen; bots fill it, humans never see it */}
          <div aria-hidden="true"
            style={{ position: 'absolute', left: '-9999px', width: '1px', height: '1px', overflow: 'hidden' }}>
            <label>Company website
              <input type="text" tabIndex={-1} autoComplete="off"
                value={hp} onChange={(e) => setHp(e.target.value)} />
            </label>
          </div>

          <label className="eg-check">
            <input type="checkbox" checked={consentScan}
              onChange={(e) => setConsentScan(e.target.checked)} />
            <span>I'm authorized to run a security scan on this repository.</span>
          </label>

          <label className="eg-check">
            <input type="checkbox" checked={isPrivate}
              onChange={(e) => setIsPrivate(e.target.checked)} />
            <span>🔒 This is a private repository.</span>
          </label>

          {isPrivate && (
            <div className="eg-private">
              <input
                type="password" autoComplete="off" spellCheck={false}
                placeholder={`paste a ${tok.label}`}
                value={repoToken} onChange={(e) => setRepoToken(e.target.value)} />
              <div className="eg-private-hint">
                {tok.hint} — used only to clone your repo, then deleted. Never stored long-term.
              </div>
            </div>
          )}

          <label className="eg-check">
            <input type="checkbox" checked={consentFeature}
              onChange={(e) => setConsentFeature(e.target.checked)} />
            <span>Sekura may feature our logo as a scanned project. <em>(optional)</em></span>
          </label>

          {needsTurnstile && <div className="eg-turnstile" ref={tsRef} />}

          <button type="submit" disabled={!canSubmit}
            className={canSubmit ? 'is-valid' : ''}>
            {submitting ? 'queuing…' : 'send me the full report →'}
          </button>
        </form>

        {touched && !emailValid && <div className="eg-error">use a valid email</div>}
        {touched && emailValid && !consentScan && <div className="eg-error">authorization is required to scan</div>}
        {touched && emailValid && consentScan && isPrivate && !tokenOk &&
          <div className="eg-error">paste a clone token for the private repo</div>}
        {touched && emailValid && consentScan && tokenOk && needsTurnstile && !tsToken &&
          <div className="eg-error">please complete the bot check above</div>}
        {error && <div className="eg-error">{error}</div>}
      </div>
    </div>
  );
}
window.EmailGate = EmailGate;
