// Waiver step — scroll to unlock + type/draw signature.
// Verbiage is the official AFSW Liability Release & Express Assumption of Risk.
// The personalized opening paragraph (with the candidate's name) is rendered
// inline by the components below; WAIVER_TEXT holds the remaining paragraphs.

// Inline opener — text wraps the candidate name. Used by both desktop and mobile.
const WAIVER_OPENER_BEFORE = "I, ";
const WAIVER_OPENER_AFTER  = ", hereby affirm that I have been advised and thoroughly informed of the inherent hazards of the physical activities involved with participating in Air Force Special Warfare (AFSW) training and candidate development. These activities include, but are not limited to: cardiovascular conditioning, strength and endurance training, rucking and weighted marches, aquatic and underwater breath-hold training, obstacle course navigation, combatives and contact drills, high-intensity interval training, simulated field training exercises, and all events on the AFSW Initial Fitness Test (IFT) and Diagnostic Fitness Testing Evaluation Form (DFT) (Push-Ups, Sit-Ups, Pull-Ups, 1.5-Mile Run). This release applies to all AFSW career fields: Pararescue (PJ), Combat Control (CCT), Special Reconnaissance (SR), Tactical Air Control Party (TACP), Tactical Air Control Party Officer (TACP-O), Special Tactics Officer (STO), Combat Rescue Officer (CRO), Explosive Ordnance Disposal (EOD), and SERE.";

const WAIVER_TEXT = [
  "I hereby state I am in good physical condition and health, and I know of no medical symptoms, conditions, illnesses, or other ailments which would be aggravated, worsened, or in any way adversely affected by my participation in the activities which assess or improve my ability to function in the physical challenges of Air Force Special Warfare training.",
  "I understand I am not required to participate in these activities. I hereby state that I am voluntarily participating in these activities because I desire to participate. I agree to follow the directions and orders of the Air Force personnel directing these activities. I acknowledge that the recruiting personnel supervising these Special Warfare training activities possess current CPR/AED training and certification, as required for the conduct of Special Warfare training.",
  "In consideration for being allowed to participate in these activities, I hereby personally assume all risks in connection with said activities, for any harm, injury or damage that may befall me, including all risks connected with these activities, including but not limited to musculoskeletal injury, cardiovascular events, heat-related illness, drowning or near-drowning, and blunt-force trauma. Also, I understand neither the Air Force nor the United States government provides any medical care in the event I am injured while participating in these physical activities.",
  "I hereby exempt, release, and hold harmless the United States Government and the United States Air Force from any claim or lawsuit by me, my family, estate, heirs, or assigns, arising out of my participation in these activities. I further state that I am of lawful age and legally competent to sign this liability release, or that I have acquired the written consent of my parent or guardian. This agreement shall be interpreted according to federal law. It shall be as broad and inclusive as is permitted by pertinent federal law.",
];

const SignaturePad = ({ value, onChange }) => {
  const canvasRef = React.useRef(null);
  const [drawing, setDrawing] = React.useState(false);
  const [hasInk, setHasInk] = React.useState(false);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const dpr = window.devicePixelRatio || 1;
    const rect = canvas.getBoundingClientRect();
    canvas.width = rect.width * dpr;
    canvas.height = rect.height * dpr;
    ctx.scale(dpr, dpr);
    ctx.strokeStyle = T.bone;
    ctx.lineWidth = 2.4;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
  }, []);

  const pos = (e) => {
    const rect = canvasRef.current.getBoundingClientRect();
    const t = e.touches?.[0];
    return { x: (t?.clientX ?? e.clientX) - rect.left, y: (t?.clientY ?? e.clientY) - rect.top };
  };

  const start = (e) => {
    e.preventDefault();
    const ctx = canvasRef.current.getContext('2d');
    const p = pos(e);
    ctx.beginPath();
    ctx.moveTo(p.x, p.y);
    setDrawing(true);
  };
  const move = (e) => {
    if (!drawing) return;
    e.preventDefault();
    const ctx = canvasRef.current.getContext('2d');
    const p = pos(e);
    ctx.lineTo(p.x, p.y);
    ctx.stroke();
    setHasInk(true);
    onChange?.('drawn');
  };
  const end = () => setDrawing(false);

  const clear = () => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    setHasInk(false);
    onChange?.('');
  };

  return (
    <div style={{ position: 'relative' }}>
      <canvas
        ref={canvasRef}
        style={{ width: '100%', height: 90, border: `1px solid ${T.rule}`, background: T.bg2, touchAction: 'none', cursor: 'crosshair', display: 'block' }}
        onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
        onTouchStart={start} onTouchMove={move} onTouchEnd={end}
      />
      {!hasInk && (
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Mono size={11} color={T.mute}>SIGN HERE</Mono>
        </div>
      )}
      <button onClick={clear} style={{ position: 'absolute', top: 6, right: 6, background: 'transparent', border: `1px solid ${T.rule}`, color: T.mute, fontFamily: "'JetBrains Mono',monospace", fontSize: 9, padding: '3px 8px', cursor: 'pointer', letterSpacing: 1 }}>
        CLEAR
      </button>
    </div>
  );
};

const Waiver = ({ ctx, setCtx, go, event }) => {
  const scrollRef = React.useRef(null);
  const [unlocked, setUnlocked] = React.useState(false);
  const [progress, setProgress] = React.useState(0);
  const [mode, setMode] = React.useState('type'); // type | draw
  const [busy, setBusy] = React.useState(false);
  const [submitError, setSubmitError] = React.useState('');
  const fullName = `${ctx.first || ''} ${ctx.last || ''}`.trim();
  const isMinor = ctx.guardianName ? true : false;

  const onScroll = (e) => {
    const el = e.currentTarget;
    const max = el.scrollHeight - el.clientHeight;
    const p = max > 0 ? Math.min(1, el.scrollTop / max) : 1;
    setProgress(p);
    if (p >= 0.95) setUnlocked(true);
  };

  const sigOk = mode === 'type' ? (ctx.typedSig && ctx.typedSig.trim().length > 1) : ctx.drawnSig === 'drawn';
  const guardianSigOk = !isMinor || (ctx.guardianTypedSig && ctx.guardianTypedSig.trim().length > 1);
  const canConfirm = unlocked && sigOk && guardianSigOk;

  return (
    <div style={{ maxWidth: 760, margin: '0 auto', padding: '8px 32px 48px' }}>
      <Mono size={11} color={T.mute}>// STEP 02 OF 03 · LIABILITY RELEASE</Mono>
      <Bebas size={36} style={{ marginTop: 6 }}>Waiver · review & sign.</Bebas>

      <div style={{ marginTop: 18, border: `1px solid ${T.rule}`, position: 'relative' }}>
        <div ref={scrollRef} onScroll={onScroll} style={{ height: 280, overflowY: 'auto', padding: 22, position: 'relative' }}>
          <Mono size={9} color={T.gold} style={{ display: 'block', marginBottom: 4 }}>// LIABILITY RELEASE AND EXPRESS ASSUMPTION OF RISK</Mono>
          <Mono size={9} color={T.mute} style={{ display: 'block', marginBottom: 12 }}>AIR FORCE SPECIAL WARFARE TRAINING ACTIVITIES · {event.city}, {event.state} · {event.date}</Mono>
          <Body size={13} color={T.bone}>
            {WAIVER_OPENER_BEFORE}<span style={{ color: T.gold }}>{fullName || '(your name)'}</span>{WAIVER_OPENER_AFTER}
          </Body>
          {WAIVER_TEXT.map((p, i) => (
            <Body key={i} size={13} color={T.bone} style={{ display: 'block', marginTop: 14 }}>{p}</Body>
          ))}
          <Body size={11} color={T.mute} style={{ display: 'block', marginTop: 18 }}>
            Last revised: 06 MAY 2026 · USAF / AFSPECWAR / RECRUITING · Previous edition is obsolete.
          </Body>
        </div>
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 3, background: T.rule }}>
          <div style={{ height: '100%', width: (progress * 100) + '%', background: unlocked ? T.gold : T.blue2, transition: 'width .1s' }} />
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 }}>
        <Mono size={10} color={unlocked ? T.gold : T.mute}>
          {unlocked ? '✓ WAIVER REVIEWED' : `SCROLL TO UNLOCK · ${Math.round(progress * 100)}%`}
        </Mono>
      </div>

      {/* Signature */}
      <div style={{ marginTop: 24, opacity: unlocked ? 1 : 0.4, pointerEvents: unlocked ? 'auto' : 'none', transition: 'opacity .2s' }}>
        <Mono size={10} color={T.mute}>// CANDIDATE SIGNATURE</Mono>
        <div style={{ display: 'flex', gap: 4, marginTop: 8 }}>
          {['type', 'draw'].map(m => (
            <button key={m} onClick={() => setMode(m)} style={{
              padding: '6px 14px',
              background: mode === m ? T.bone : 'transparent',
              color: mode === m ? T.bg : T.bone,
              border: `1px solid ${T.bone}`,
              fontFamily: "'JetBrains Mono',monospace",
              fontSize: 10,
              letterSpacing: 1,
              cursor: 'pointer',
            }}>{m.toUpperCase()}</button>
          ))}
        </div>
        <div style={{ marginTop: 10 }}>
          {mode === 'type' ? (
            <input
              value={ctx.typedSig || fullName}
              onChange={e => setCtx({ typedSig: e.target.value })}
              style={{ width: '100%', padding: 14, background: T.bg2, border: `1px solid ${T.rule}`, color: T.bone, fontFamily: "'Caveat',cursive", fontSize: 32, outline: 'none' }}
            />
          ) : (
            <SignaturePad value={ctx.drawnSig} onChange={v => setCtx({ drawnSig: v })} />
          )}
        </div>

        {isMinor && (
          <div style={{ marginTop: 22, padding: 16, border: `1px solid ${T.gold}`, background: 'rgba(200,168,78,0.06)' }}>
            <Mono size={10} color={T.gold}>// GUARDIAN CO-SIGNATURE · {ctx.guardianName?.toUpperCase()}</Mono>
            <input
              value={ctx.guardianTypedSig || ctx.guardianName || ''}
              onChange={e => setCtx({ guardianTypedSig: e.target.value })}
              style={{ width: '100%', marginTop: 10, padding: 14, background: T.bg2, border: `1px solid ${T.rule}`, color: T.bone, fontFamily: "'Caveat',cursive", fontSize: 28, outline: 'none' }}
            />
          </div>
        )}
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginTop: 32 }}>
        <button onClick={() => go('signup', { step: 0 })} style={{ background: 'transparent', border: 'none', color: T.mute, fontFamily: "'JetBrains Mono',monospace", fontSize: 11, letterSpacing: 1, cursor: 'pointer' }}>
          ← Back
        </button>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8 }}>
          <PrimaryCTA blue disabled={!canConfirm || busy} style={{ opacity: busy ? 0.6 : 1 }} onClick={async () => {
            if (busy) return;
            setBusy(true); setSubmitError('');
            const signedAt = new Date().toISOString();
            const body = {
              eventCode: event.code,
              first: ctx.first,
              last: ctx.last,
              email: ctx.email,
              phone: ctx.phone,
              birthday: ctx.birthday,
              careers: ctx.careers || [],
              waiver: {
                signatureType: mode,
                ...(mode === 'type' ? { typedSig: ctx.typedSig || fullName } : { drawnSig: ctx.drawnSig || 'drawn' }),
                signedAt,
              },
            };
            if (isMinor) {
              body.guardianName = ctx.guardianName;
              body.guardianEmail = ctx.guardianEmail;
              body.guardianPhone = ctx.guardianPhone;
              body.waiver.guardianTypedSig = ctx.guardianTypedSig || ctx.guardianName;
              body.waiver.guardianSignatureType = 'type';
              body.waiver.guardianSignedAt = signedAt;
            }
            try {
              const r = await window.api.apiPost('/api/signup', body);
              setCtx({ confirmNum: r.confirmationNumber, signedAt });
              go('signup', { step: 2 });
            } catch (e) {
              const fields = e.fields ? ` (${e.fields.join(', ')})` : '';
              setSubmitError(`${e.message}${fields}`);
            } finally {
              setBusy(false);
            }
          }}>{busy ? 'Submitting…' : 'Confirm signature →'}</PrimaryCTA>
          {submitError && <Mono size={10} color={T.red} style={{ maxWidth: 300, textAlign: 'right' }}>{submitError}</Mono>}
        </div>
      </div>
    </div>
  );
};

window.Waiver = Waiver;
window.WAIVER_TEXT = WAIVER_TEXT;
window.WAIVER_OPENER_BEFORE = WAIVER_OPENER_BEFORE;
window.WAIVER_OPENER_AFTER = WAIVER_OPENER_AFTER;
