// ScanStep6Auth — authorization consent + submit to generate e-sign document.

function ScanStep6Auth({ data, update, onBack, onSubmit, submitting, error, stepLabel }) {
  const { React } = window;
  const { useState, useEffect, useRef, useCallback } = React;

  const [errors, setErrors] = useState({});
  const [turnstileToken, setTurnstileToken] = useState(null);
  const turnstileRef = useRef(null);
  const widgetIdRef = useRef(null);

  const SITE_KEY = '0x4AAAAAAACy-xveuX2MjZ6vd';

  useEffect(() => {
    if (!window.turnstile || !turnstileRef.current || widgetIdRef.current != null) return;
    widgetIdRef.current = window.turnstile.render(turnstileRef.current, {
      sitekey: SITE_KEY,
      theme: 'light',
      callback: (token) => setTurnstileToken(token),
      'expired-callback': () => setTurnstileToken(null),
      'error-callback': () => setTurnstileToken(null),
    });
    return () => {
      if (widgetIdRef.current != null) {
        window.turnstile.remove(widgetIdRef.current);
        widgetIdRef.current = null;
      }
    };
  }, []);

  const isLocal = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';

  function handleSubmit() {
    const errs = window.ManagedScanSchema.validateStep6(data);
    if (!turnstileToken && !isLocal) errs.turnstile = 'please complete the verification';
    setErrors(errs);
    if (Object.keys(errs).length === 0) onSubmit(turnstileToken);
  }

  const Checkmark = () => (
    <svg width="10" height="8" viewBox="0 0 10 8" fill="none">
      <path d="M1 4l3 3 5-6" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );

  return (
    <div className="form-step">
      <div className="form-step-heading">{stepLabel}</div>

      <p style={{ fontSize: '13px', color: 'var(--muted)', marginBottom: '24px', lineHeight: '1.5' }}>
        before we generate your scan authorization document, we need your explicit consent.
      </p>

      <div className="form-group">
        <div className="consent-group">
          <div className={`consent-opt${data.authorizationConfirmed ? ' is-checked' : ''}`}
            onClick={() => update({ authorizationConfirmed: !data.authorizationConfirmed })}>
            <div className="consent-box">{data.authorizationConfirmed && <Checkmark />}</div>
            <div className="consent-text">
              I confirm I am authorized to commission security testing on the targets described above,
              and Sekura is permitted to perform active network scanning and non-destructive exploitation
              attempts against them.
            </div>
          </div>
          {errors.authorizationConfirmed && (
            <div className="form-error" style={{ marginLeft: '30px' }}>{errors.authorizationConfirmed}</div>
          )}

          <div className={`consent-opt${data.termsAccepted ? ' is-checked' : ''}`}
            onClick={() => update({ termsAccepted: !data.termsAccepted })}>
            <div className="consent-box">{data.termsAccepted && <Checkmark />}</div>
            <div className="consent-text">
              I agree to Sekura's{' '}
              <a href="#terms" target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()}>scan terms</a>{' '}
              and{' '}
              <a href="#privacy" target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()}>privacy policy</a>.
            </div>
          </div>
          {errors.termsAccepted && (
            <div className="form-error" style={{ marginLeft: '30px' }}>{errors.termsAccepted}</div>
          )}

          <div className={`consent-opt${data.dataProcessingAccepted ? ' is-checked' : ''}`}
            onClick={() => update({ dataProcessingAccepted: !data.dataProcessingAccepted })}>
            <div className="consent-box">{data.dataProcessingAccepted && <Checkmark />}</div>
            <div className="consent-text">
              I understand that scan configuration data will be shared with Sekura's operations team
              to provision the scanner in my cloud environment.
            </div>
          </div>
          {errors.dataProcessingAccepted && (
            <div className="form-error" style={{ marginLeft: '30px' }}>{errors.dataProcessingAccepted}</div>
          )}
        </div>
      </div>

      <div style={{ margin: '16px 0' }}>
        <div ref={turnstileRef}></div>
        {errors.turnstile && <div className="form-error">{errors.turnstile}</div>}
      </div>

      {error && <div className="submit-error">{error}</div>}

      <div className="form-actions">
        <button className="btn-back" onClick={onBack} disabled={submitting}>← back</button>
        <button className={`btn-submit${submitting ? ' is-submitting' : ''}`}
          onClick={handleSubmit} disabled={submitting}>
          {submitting ? 'generating...' : 'generate authorization document →'}
        </button>
      </div>
    </div>
  );
}

window.ScanStep6Auth = ScanStep6Auth;
