// Member verification step — runs after checkout from the dashboard.
// Three sub-steps:
//   1. Upload government-issued ID (front + back)
//   2. Record short consent + identity video (member reads sentence, says name + DOB)
//   3. Confirmation — review runs; provider can step in if anything's off.

const VerifyStep = ({ contact, onComplete, onBack }) => {
  const [step, setStep] = React.useState('intro'); // intro | id | video | review | done
  const [idFront, setIdFront] = React.useState(null);
  const [idBack, setIdBack] = React.useState(null);
  const [recording, setRecording] = React.useState(false);
  const [recordedSec, setRecordedSec] = React.useState(0);
  const [videoCaptured, setVideoCaptured] = React.useState(false);
  const [videoBlob, setVideoBlob] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');
  const [consents, setConsents] = React.useState({
    record: false,
    storage: false,
    identity: false,
  });
  const recorderRef = React.useRef(null);
  const streamRef = React.useRef(null);
  const timerRef = React.useRef(null);
  const tickRef = React.useRef(null);
  const videoPreviewRef = React.useRef(null);

  const allConsented = consents.record && consents.storage && consents.identity;
  const idReady = idFront && idBack;

  React.useEffect(() => () => {
    window.clearTimeout(timerRef.current);
    window.clearInterval(tickRef.current);
    streamRef.current?.getTracks?.().forEach((track) => track.stop());
  }, []);

  React.useEffect(() => {
    if (!recording) return;
    const t = setInterval(() => {
      setRecordedSec((s) => {
        const next = s + 1;
        if (next >= 12) {
          recorderRef.current?.stop?.();
          return 12;
        }
        return next;
      });
    }, 1000);
    return () => clearInterval(t);
  }, [recording]);

  const startRecording = async () => {
    setError('');
    setRecordedSec(0);
    setVideoCaptured(false);
    setVideoBlob(null);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
      streamRef.current = stream;
      if (videoPreviewRef.current) {
        videoPreviewRef.current.srcObject = stream;
      }
      const chunks = [];
      const recorderOptions = MediaRecorder.isTypeSupported?.('video/webm') ? { mimeType: 'video/webm' } : undefined;
      const recorder = new MediaRecorder(stream, recorderOptions);
      recorderRef.current = recorder;
      recorder.ondataavailable = (event) => {
        if (event.data && event.data.size > 0) chunks.push(event.data);
      };
      recorder.onstop = () => {
        const blob = new Blob(chunks, { type: 'video/webm' });
        setVideoBlob(blob);
        setVideoCaptured(true);
        setRecording(false);
        stream.getTracks().forEach((track) => track.stop());
        streamRef.current = null;
      };
      recorder.start();
      setRecording(true);
      timerRef.current = window.setTimeout(() => recorder.stop(), 12000);
    } catch {
      setError('Camera and microphone access are required to record verification.');
    }
  };

  const reRecord = () => {
    window.clearTimeout(timerRef.current);
    setRecordedSec(0);
    setVideoCaptured(false);
    setVideoBlob(null);
  };

  const onIdPick = (which) => (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    const url = URL.createObjectURL(f);
    if (which === 'front') setIdFront({ name: f.name, url, file: f });
    else setIdBack({ name: f.name, url, file: f });
  };

  const proceedFromReview = async () => {
    if (!idFront?.file || !idBack?.file || !videoBlob) {
      setError('ID and video are required before verification can be submitted.');
      return;
    }
    setError('');
    setSubmitting(true);
    try {
      const formData = new FormData();
      formData.set('visitorId', window.localStorage?.getItem('axo_site_visitor_id') || '');
      formData.set('idFront', idFront.file);
      formData.set('idBack', idBack.file);
      formData.set('video', videoBlob, 'identity-video.webm');
      formData.set('contact', JSON.stringify(contact || {}));
      const res = await fetch('/api/site/verification', { method: 'POST', body: formData });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Verification upload failed');
      setStep('done');
      window.setTimeout(() => onComplete && onComplete({ verified: true, verification: data.verification }), 900);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Verification upload failed');
      setSubmitting(false);
    }
  };

  return (
    <div className="verify-shell">
      <div className="verify-top">
        <Logo size={20} asLink />
        <div className="verify-progress">
          <div className="verify-progress-fill" style={{
            width: step === 'intro' ? '15%'
                 : step === 'id' ? '40%'
                 : step === 'video' ? '70%'
                 : step === 'review' ? '90%'
                 : '100%'
          }} />
        </div>
        <div className="verify-counter mono">MEMBER VERIFICATION</div>
      </div>

      <div className="verify-stage">
        {step === 'intro' && (
          <div className="verify-card">
            <div className="verify-eyebrow mono">— MEMBER VERIFICATION</div>
            <h1 className="serif verify-h1">Verify your <em>identity.</em></h1>
            <p className="verify-sub">
              We need to confirm who you are before fulfillment. This keeps your membership tied to the right person and gives the review team the record they need.
            </p>

            <div className="verify-steps">
              <div className="verify-step-row">
                <span className="verify-step-num">01</span>
                <div>
                  <h3>Photo of your ID</h3>
                  <p>Driver's license, passport, or state ID. Front and back.</p>
                </div>
              </div>
              <div className="verify-step-row">
                <span className="verify-step-num">02</span>
                <div>
                  <h3>Twelve-second video</h3>
                  <p>You'll read a short sentence and say your name and date of birth. We match it to your ID and your assessment.</p>
                </div>
              </div>
              <div className="verify-step-row">
                <span className="verify-step-num">03</span>
                <div>
                  <h3>Then review</h3>
                  <p>Once submitted, your verification is added to your member record for review before fulfillment.</p>
                </div>
              </div>
            </div>

            <div className="verify-legal mono">
              Your ID and video are stored securely against your member record. They are not shared outside our network. You can request deletion at any time after your membership ends.
            </div>

            <div className="verify-actions">
              <button className="btn btn-soft" onClick={onBack}>← Back</button>
              <button className="btn btn-primary btn-lg" onClick={() => setStep('id')}>
                Start verification →
              </button>
            </div>
          </div>
        )}

        {step === 'id' && (
          <div className="verify-card">
            <div className="verify-eyebrow mono">— STEP 1 OF 2</div>
            <h1 className="serif verify-h1">Your <em>ID.</em></h1>
            <p className="verify-sub">
              Driver's license, passport, or state ID. Make sure all four corners are visible and the text is readable.
            </p>

            <div className="verify-id-grid">
              <IdSlot
                label="Front of ID"
                file={idFront}
                onPick={onIdPick('front')}
                onClear={() => setIdFront(null)}
              />
              <IdSlot
                label="Back of ID"
                file={idBack}
                onPick={onIdPick('back')}
                onClear={() => setIdBack(null)}
              />
            </div>

            <div className="verify-tips">
              <div className="verify-tip-h mono">— TIPS</div>
              <ul>
                <li>Use a flat surface in good light. No glare.</li>
                <li>Match the name on your ID to the legal name on your account.</li>
                <li>Expired ID? Use a different one — we can't ship without a current ID.</li>
              </ul>
            </div>

            <div className="verify-actions">
              <button className="btn btn-soft" onClick={() => setStep('intro')}>← Back</button>
              <button
                className="btn btn-primary btn-lg"
                onClick={() => setStep('video')}
                disabled={!idReady}
                style={{ opacity: idReady ? 1 : 0.4, pointerEvents: idReady ? 'auto' : 'none' }}
              >
                Continue to video →
              </button>
            </div>
          </div>
        )}

        {step === 'video' && (
          <div className="verify-card">
            <div className="verify-eyebrow mono">— STEP 2 OF 2</div>
            <h1 className="serif verify-h1">A short <em>video.</em></h1>
            <p className="verify-sub">
              Twelve seconds, looking at your camera. We use this to confirm you are the person on the ID and to record your consent on file.
            </p>

            <div className="verify-script">
              <div className="verify-script-h mono">— READ THIS WHEN RECORDING</div>
              <p>
                "My name is <strong>{contact?.legalName || '[your full name]'}</strong>, my date of birth is <strong>[your DOB]</strong>, and I consent to AmazingXO and its network reviewing my health information."
              </p>
            </div>

            <div className="verify-cam">
              <div className={`verify-cam-frame ${recording ? 'is-recording' : ''} ${videoCaptured ? 'is-captured' : ''}`}>
                {!recording && !videoCaptured && (
                  <div className="verify-cam-placeholder">
                    <div className="verify-cam-icon">▶</div>
                    <div className="verify-cam-text mono">CAMERA PREVIEW · NOT RECORDING</div>
                  </div>
                )}
                {recording && (
                  <div className="verify-cam-placeholder">
                    <video ref={videoPreviewRef} autoPlay muted playsInline style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: 0.55 }} />
                    <div className="verify-cam-rec">● REC</div>
                    <div className="verify-cam-timer">{recordedSec}s / 12s</div>
                    <div className="verify-cam-hint mono">READING SCRIPT…</div>
                  </div>
                )}
                {videoCaptured && (
                  <div className="verify-cam-placeholder">
                    <div className="verify-cam-check">✓</div>
                    <div className="verify-cam-text mono">VIDEO CAPTURED · 12s</div>
                  </div>
                )}
              </div>

            <div className="verify-cam-actions">
                {!recording && !videoCaptured && (
                  <button className="btn btn-primary btn-lg" onClick={startRecording}>● Start recording</button>
                )}
                {recording && (
                  <div className="verify-recording-hint mono">RECORDING — STAY STILL</div>
                )}
                {videoCaptured && (
                  <button className="btn btn-soft" onClick={reRecord}>↻ Re-record</button>
                )}
              </div>
              {error && <p style={{ color: 'var(--accent)', fontSize: 13, lineHeight: 1.4, textAlign: 'center', margin: 0 }}>{error}</p>}
            </div>

            <div className="verify-consents">
              <Check
                checked={consents.record}
                onChange={(v) => setConsents({ ...consents, record: v })}
                label="I consent to being recorded for identity verification"
                detail="The video is stored against your member record and used only by AmazingXO and its network."
              />
              <Check
                checked={consents.storage}
                onChange={(v) => setConsents({ ...consents, storage: v })}
                label="I consent to my ID and video being stored for the duration of my membership"
                detail="You can request deletion at any time after your membership ends."
              />
              <Check
                checked={consents.identity}
                onChange={(v) => setConsents({ ...consents, identity: v })}
                label="I confirm I am the person on the ID and that the information I provided is accurate"
                detail="Misrepresentation is grounds for membership cancellation and refund."
              />
            </div>

            <div className="verify-actions">
              <button className="btn btn-soft" onClick={() => setStep('id')}>← Back</button>
              <button
                className="btn btn-primary btn-lg"
                onClick={() => setStep('review')}
                disabled={!videoCaptured || !videoBlob || !allConsented}
                style={{ opacity: (videoCaptured && videoBlob && allConsented) ? 1 : 0.4, pointerEvents: (videoCaptured && videoBlob && allConsented) ? 'auto' : 'none' }}
              >
                Submit for review →
              </button>
            </div>
          </div>
        )}

        {step === 'review' && (
          <div className="verify-card verify-review">
            <div className="verify-eyebrow mono">— REVIEW BEFORE SUBMIT</div>
            <h1 className="serif verify-h1">Everything <em>look right?</em></h1>
            <p className="verify-sub">Last chance to re-record or swap an ID photo. Once you submit, the file is added to your member record for review.</p>

            <div className="verify-review-grid">
              <div className="verify-review-card">
                <div className="verify-review-h mono">— ID FRONT</div>
                {idFront ? <img src={idFront.url} alt="ID front" /> : <div className="verify-review-empty">missing</div>}
                <button className="verify-review-edit mono" onClick={() => setStep('id')}>EDIT</button>
              </div>
              <div className="verify-review-card">
                <div className="verify-review-h mono">— ID BACK</div>
                {idBack ? <img src={idBack.url} alt="ID back" /> : <div className="verify-review-empty">missing</div>}
                <button className="verify-review-edit mono" onClick={() => setStep('id')}>EDIT</button>
              </div>
              <div className="verify-review-card">
                <div className="verify-review-h mono">— ID VIDEO</div>
                <div className="verify-review-empty" style={{ background: 'var(--ink)', color: 'var(--bg)' }}>
                  ✓ 12s captured
                </div>
                <button className="verify-review-edit mono" onClick={() => setStep('video')}>EDIT</button>
              </div>
            </div>

            <div className="verify-actions">
              <button className="btn btn-soft" onClick={() => setStep('video')}>← Back</button>
              <button className="btn btn-primary btn-lg" onClick={proceedFromReview} disabled={submitting}>
                {submitting ? 'Submitting verification…' : 'Submit verification →'}
              </button>
            </div>
            {error && <p style={{ color: 'var(--accent)', fontSize: 13, lineHeight: 1.4, textAlign: 'center' }}>{error}</p>}
          </div>
        )}

        {step === 'done' && (
          <div className="verify-card verify-done">
            <div className="verify-done-mark">✓</div>
            <h1 className="serif verify-h1" style={{ textAlign: 'center' }}>You're <em>verified.</em></h1>
            <p className="verify-sub" style={{ textAlign: 'center' }}>
              Your verification is on your member record. You can return to your dashboard while review is completed.
            </p>
            <div className="verify-done-status mono">
              <span className="verify-dot" /> Taking you to your dashboard…
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

const IdSlot = ({ label, file, onPick, onClear }) => {
  const id = `id-input-${label.replace(/\s+/g, '-')}`;
  return (
    <div className={`verify-id-slot ${file ? 'has-file' : ''}`}>
      <div className="verify-id-label mono">— {label.toUpperCase()}</div>
      {file ? (
        <>
          <img src={file.url} alt={label} />
          <div className="verify-id-meta">
            <span className="mono">{file.name}</span>
            <button className="verify-id-clear mono" onClick={onClear}>REMOVE</button>
          </div>
        </>
      ) : (
        <>
          <label htmlFor={id} className="verify-id-drop">
            <div className="verify-id-icon">+</div>
            <div className="verify-id-cta">Click to upload</div>
            <div className="verify-id-hint mono">JPG, PNG, HEIC · UP TO 10MB</div>
          </label>
          <input
            id={id}
            type="file"
            accept="image/*"
            capture="environment"
            onChange={onPick}
            style={{ display: 'none' }}
          />
        </>
      )}
    </div>
  );
};

const Check = ({ checked, onChange, label, detail }) => (
  <label className="verify-check">
    <span
      onClick={() => onChange(!checked)}
      className={`verify-check-box ${checked ? 'is-on' : ''}`}
    >{checked ? '✓' : ''}</span>
    <span onClick={() => onChange(!checked)} className="verify-check-text">
      <div className="verify-check-label">{label}</div>
      <div className="verify-check-detail">{detail}</div>
    </span>
  </label>
);

window.VerifyStep = VerifyStep;
