// ScrollJob v2 — Two-factor authentication
// Appended to v2-auth.jsx via separate file so we don't risk breaking the
// existing sign-in / sign-up exports. Both screens reuse V2AuthShell so
// responsive behaviour matches V2SignInScreen.

// 6-digit OTP code input row — auto-advance-vibe via successive filled cells.
function OTPRow({ filled = 0 }) {
  return (
    <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
      {Array.from({ length: 6 }).map((_, i) => {
        const isFilled = i < filled;
        const isActive = i === filled;
        return (
          <div key={i} style={{
            width: 48, height: 56,
            border: `2px solid ${isActive ? V2.primary : isFilled ? V2.primaryRing : V2.lineStrong}`,
            borderRadius: V2.rMd,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 22, fontWeight: 700, color: V2.ink,
            fontFamily: V2.fontMono,
            background: '#fff',
            boxShadow: isActive ? `0 0 0 4px ${V2.primaryRing}55` : V2.shadowSm,
            transition: 'all .15s ease',
          }}>
            {isFilled ? ['8', '1', '2', '4', '0', ''][i] : isActive ? <CaretBlink /> : ''}
          </div>
        );
      })}
    </div>
  );
}

function CaretBlink() {
  return (
    <span style={{
      display: 'inline-block', width: 2, height: 24, background: V2.primary,
      animation: 'sjCaret 1s steps(2, start) infinite',
    }}>
      <style>{`@keyframes sjCaret { to { opacity: 0; } }`}</style>
    </span>
  );
}

function VerifiedPulse() {
  return (
    <span style={{ position: 'relative', display: 'inline-block', width: 12, height: 12 }}>
      <span style={{
        position: 'absolute', inset: 0, borderRadius: '50%',
        background: V2.success, animation: 'sjPulse 1.6s ease-out infinite',
      }} />
      <span style={{
        position: 'absolute', inset: 3, borderRadius: '50%', background: V2.success,
      }} />
      <style>{`@keyframes sjPulse {
        0% { transform: scale(1); opacity: 0.6; }
        100% { transform: scale(2.2); opacity: 0; }
      }`}</style>
    </span>
  );
}

// ─── A) 2FA SETUP ───────────────────────────────────────────────────────
function V2TwoFactorSetupScreen() {
  // Reuses V2AuthShell from v2-auth.jsx (already on window).
  return (
    <V2AuthShell
      title="Set up two-factor authentication"
      sub="Add an extra layer of security to your sign-in."
    >
      {/* QR code box */}
      <div style={{
        width: 240, height: 240,
        border: `2px dashed ${V2.lineStrong}`, borderRadius: V2.rLg,
        background: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        margin: '0 0 16px', position: 'relative',
      }}>
        <QRCodeArt size={196} />
        <span style={{
          position: 'absolute', top: 10, right: 10,
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '3px 9px', borderRadius: 999,
          background: V2.successBg, color: V2.success,
          fontSize: 11, fontWeight: 700,
        }}>
          <VerifiedPulse /> Ready to scan
        </span>
      </div>

      {/* Monospace fallback code chip */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
        padding: '10px 14px', borderRadius: 999,
        background: V2.primarySoft, border: `1px solid ${V2.primaryRing}`,
        marginBottom: 10, maxWidth: 360,
      }}>
        <span style={{
          fontFamily: V2.fontMono, fontSize: 14, fontWeight: 700,
          color: V2.primaryInk, letterSpacing: '0.06em',
        }}>JBSWY3DPEHPK3PXP</span>
        <button aria-label="Copy code" style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          color: V2.primary, display: 'inline-flex', alignItems: 'center', gap: 4,
          fontSize: 12, fontWeight: 700, fontFamily: V2.font,
        }}>
          <Icon name="document" size={13} /> Copy
        </button>
      </div>

      <p style={{ margin: '0 0 24px', fontSize: 13, color: V2.muted, lineHeight: 1.55, maxWidth: 360 }}>
        Scan with <strong style={{ color: V2.text }}>Google Authenticator</strong>, <strong style={{ color: V2.text }}>Authy</strong>, or <strong style={{ color: V2.text }}>1Password</strong>. Then enter the 6-digit code below.
      </p>

      <label style={{ display: 'block', fontSize: 13, fontWeight: 600, color: V2.ink2, marginBottom: 8 }}>
        Verification code
      </label>
      <OTPRow filled={4} />

      <V2Button variant="primary" size="lg" full iconRight="check">Verify & enable</V2Button>
    </V2AuthShell>
  );
}

// Right-hand panel content for 2FA setup — overrides V2AuthBenefits when
// shown alongside V2TwoFactorSetupScreen. Because V2AuthShell hard-codes
// V2AuthBenefits on the right, we wrap the screen in a second variant that
// renders our two cards inline using a parallel layout container.
function V2TwoFactorSetupScreenWithBackup() {
  return (
    <div style={{ background: V2.bg, fontFamily: V2.font, color: V2.ink, minHeight: '100%' }}>
      <header style={{
        padding: '20px 32px', borderBottom: `1px solid ${V2.line}`, background: '#fff',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <V2Logo />
        <span style={{ fontSize: 13, color: V2.muted }}>
          Need help? <a style={{ color: V2.primary, textDecoration: 'none', fontWeight: 600 }}>Contact us</a>
        </span>
      </header>
      <main style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr',
        minHeight: 'calc(100% - 65px)',
      }}>
        {/* Left — setup form */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '64px 48px',
        }}>
          <div style={{ width: '100%', maxWidth: 420 }}>
            <h1 style={{ margin: '0 0 8px', fontSize: 32, fontWeight: 800, color: V2.ink, letterSpacing: '-0.02em' }}>
              Set up two-factor authentication
            </h1>
            <p style={{ margin: '0 0 28px', fontSize: 15.5, color: V2.muted, lineHeight: 1.55 }}>
              Add an extra layer of security to your sign-in.
            </p>

            <div style={{
              width: 240, height: 240,
              border: `2px dashed ${V2.lineStrong}`, borderRadius: V2.rLg,
              background: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              margin: '0 0 16px', position: 'relative',
            }}>
              <QRCodeArt size={196} />
              <span style={{
                position: 'absolute', top: 10, right: 10,
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '3px 9px', borderRadius: 999,
                background: V2.successBg, color: V2.success,
                fontSize: 11, fontWeight: 700,
              }}>
                <VerifiedPulse /> Ready to scan
              </span>
            </div>

            <div style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
              padding: '10px 14px', borderRadius: 999,
              background: V2.primarySoft, border: `1px solid ${V2.primaryRing}`,
              marginBottom: 10,
            }}>
              <span style={{
                fontFamily: V2.fontMono, fontSize: 14, fontWeight: 700,
                color: V2.primaryInk, letterSpacing: '0.06em',
              }}>JBSWY3DPEHPK3PXP</span>
              <button aria-label="Copy code" style={{
                background: 'transparent', border: 'none', cursor: 'pointer',
                color: V2.primary, display: 'inline-flex', alignItems: 'center', gap: 4,
                fontSize: 12, fontWeight: 700, fontFamily: V2.font,
              }}>
                <Icon name="document" size={13} /> Copy
              </button>
            </div>

            <p style={{ margin: '0 0 24px', fontSize: 13, color: V2.muted, lineHeight: 1.55, maxWidth: 360 }}>
              Scan with <strong style={{ color: V2.text }}>Google Authenticator</strong>, <strong style={{ color: V2.text }}>Authy</strong>, or <strong style={{ color: V2.text }}>1Password</strong>. Then enter the 6-digit code below.
            </p>

            <label style={{ display: 'block', fontSize: 13, fontWeight: 600, color: V2.ink2, marginBottom: 8 }}>
              Verification code
            </label>
            <OTPRow filled={4} />

            <V2Button variant="primary" size="lg" full iconRight="check">Verify & enable</V2Button>
          </div>
        </div>

        {/* Right — Why card only */}
        <div style={{
          background: V2.primarySoft, padding: '64px 48px',
          borderLeft: `1px solid ${V2.line}`,
          display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 18,
        }}>
          <div style={{
            background: '#fff', border: `1px solid ${V2.line}`, borderRadius: V2.rLg,
            padding: 22, boxShadow: V2.shadowSm,
          }}>
            <h3 style={{ margin: '0 0 14px', fontSize: 16, fontWeight: 700, color: V2.ink, letterSpacing: '-0.01em' }}>
              Why turn it on?
            </h3>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 12 }}>
              {[
                'Stops password reuse attacks',
                'Required for employers managing >£1k of boost credits',
                'Use any standard authenticator app — Google, Authy, 1Password',
              ].map((t) => (
                <li key={t} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 14, color: V2.text, lineHeight: 1.55 }}>
                  <span style={{
                    width: 20, height: 20, borderRadius: '50%',
                    background: V2.successBg, color: V2.success,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0, marginTop: 1,
                  }}>
                    <Icon name="check" size={12} />
                  </span>
                  {t}
                </li>
              ))}
            </ul>
          </div>
        </div>
      </main>
    </div>
  );
}

// ─── B) 2FA CHALLENGE ───────────────────────────────────────────────────
function V2TwoFactorChallengeScreen() {
  return (
    <div style={{
      background: V2.bg, fontFamily: V2.font, color: V2.ink, minHeight: '100%',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 40,
    }}>
      <div style={{
        width: '100%', maxWidth: 440,
        background: '#fff', border: `1px solid ${V2.line}`,
        borderRadius: V2.rXl, padding: 36,
        boxShadow: V2.shadowLg,
      }}>
        <div style={{ marginBottom: 22 }}>
          <V2Logo size={32} />
        </div>

        <h1 style={{ margin: '0 0 6px', fontSize: 24, fontWeight: 800, color: V2.ink, letterSpacing: '-0.02em' }}>
          Enter your code
        </h1>
        <p style={{ margin: '0 0 8px', fontSize: 14, color: V2.muted, lineHeight: 1.55 }}>
          We sent a code via your authenticator app.
        </p>

        {/* 30-second countdown bar */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, marginBottom: 22,
        }}>
          <div style={{ flex: 1, height: 4, background: V2.line, borderRadius: 999, overflow: 'hidden' }}>
            <div style={{ width: '62%', height: '100%', background: V2.brandGradient, borderRadius: 999 }} />
          </div>
          <span style={{ fontSize: 12, fontWeight: 700, color: V2.text, fontVariantNumeric: 'tabular-nums' }}>
            18s
          </span>
        </div>

        <OTPRow filled={3} />

        <V2Button variant="primary" size="lg" full iconRight="arrow-right">Verify</V2Button>

        <div style={{
          marginTop: 16, paddingTop: 16, borderTop: `1px solid ${V2.line}`,
          display: 'flex', flexDirection: 'column', gap: 10,
        }}>
          <label style={{
            display: 'flex', alignItems: 'center', gap: 10,
            fontSize: 13.5, color: V2.text, cursor: 'pointer',
          }}>
            <input type="checkbox" defaultChecked style={{ width: 16, height: 16, accentColor: V2.primary }} />
            Trust this device for 30 days
          </label>
          <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', fontSize: 13 }}>
            <a style={{ color: V2.primary, fontWeight: 600, textDecoration: 'none' }}>Use a backup code</a>
          </div>
        </div>

        <p style={{ margin: '20px 0 0', textAlign: 'center', fontSize: 12, color: V2.muted }}>
          Lost access? <a style={{ color: V2.muted, textDecoration: 'underline' }}>Contact support</a>
        </p>
      </div>
    </div>
  );
}

// Inline QR-code art — a stylised 25×25 grid that reads as a QR code at a
// glance without us actually encoding anything. Deterministic pseudo-random
// pattern with the three corner finder squares correctly placed.
function QRCodeArt({ size = 196 }) {
  const N = 25;
  const cell = size / N;
  // Pre-baked deterministic bit pattern (mirrors a real-ish QR density)
  const pattern = (x, y) => ((x * 31 + y * 17 + (x ^ y)) & 7) > 3;
  const corners = (x, y) => (
    (x < 7 && y < 7) || (x >= N - 7 && y < 7) || (x < 7 && y >= N - 7)
  );
  const inFinder = (x, y, ox, oy) => {
    const dx = x - ox, dy = y - oy;
    return (dx >= 0 && dx < 7 && dy >= 0 && dy < 7);
  };
  const finderFill = (x, y, ox, oy) => {
    const dx = x - ox, dy = y - oy;
    const ring = dx === 0 || dx === 6 || dy === 0 || dy === 6;
    const center = dx >= 2 && dx <= 4 && dy >= 2 && dy <= 4;
    return ring || center;
  };
  const finders = [[0, 0], [N - 7, 0], [0, N - 7]];
  const cells = [];
  for (let y = 0; y < N; y++) {
    for (let x = 0; x < N; x++) {
      let filled = false;
      let inAnyFinder = false;
      for (const [ox, oy] of finders) {
        if (inFinder(x, y, ox, oy)) {
          inAnyFinder = true;
          filled = finderFill(x, y, ox, oy);
          break;
        }
      }
      if (!inAnyFinder) filled = pattern(x, y);
      if (filled) cells.push(<rect key={`${x}-${y}`} x={x * cell} y={y * cell} width={cell} height={cell} rx={cell * 0.18} />);
    }
  }
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-hidden="true">
      <rect width={size} height={size} fill="#fff" />
      <g fill={V2.ink}>{cells}</g>
    </svg>
  );
}

Object.assign(window, {
  V2TwoFactorSetupScreen: V2TwoFactorSetupScreenWithBackup,
  V2TwoFactorChallengeScreen,
});
