// Register.jsx — terminal-style account creation with Turnstile captcha
// SECURITY: validate strength client-side AND server-side. Hash with argon2id in prod.
// Never reflect raw user input back into HTML — all renders via React {}.

const Register = ({ onRegistered, onSwitchToLogin }) => {
  const [form, setForm] = React.useState({ email: '', handle: '', password: '', confirm: '' });
  const [agree, setAgree] = React.useState(false);
  const [marketing, setMarketing] = React.useState(true);
  const [phase, setPhase] = React.useState('idle'); // idle | submitting | success
  const [err, setErr] = React.useState(null);
  const [logLines, setLogLines] = React.useState([]);
  const [newUser, setNewUser] = React.useState(null);
  const [turnstileToken, setTurnstileToken] = React.useState(null);
  const turnstileWidgetId = React.useRef(null);

  const set = (k, v) => { setForm((f) => ({ ...f, [k]: v })); setErr(null); };

  // Password strength scoring — purely indicative. Real check is server-side.
  const passwordStrength = (pw) => {
    if (!pw) return 0;
    let s = 0;
    if (pw.length >= 8) s++;
    if (pw.length >= 12) s++;
    if (pw.length >= 16) s++;
    if (/[A-Z]/.test(pw) && /[a-z]/.test(pw)) s++;
    if (/[0-9]/.test(pw)) s++;
    if (/[^A-Za-z0-9]/.test(pw)) s++;
    return Math.min(s, 5);
  };
  const strength = passwordStrength(form.password);
  const strengthLabels = ['BRITTLE', 'WEAK', 'OKAY', 'STRONG', 'HARDENED', 'FORTRESS'];
  const strengthColors = ['#FF3344', '#FF3344', '#FF8C42', '#FFD23F', '#00FF41', '#00FF41'];

  // Render Turnstile widget when in idle phase
  React.useEffect(() => {
    if (phase === 'idle' && window.turnstile) {
      // Clean up previous widget if it exists
      if (turnstileWidgetId.current != null) {
        try { window.turnstile.remove(turnstileWidgetId.current); } catch (e) { /* noop */ }
        turnstileWidgetId.current = null;
      }
      const el = document.getElementById('register-turnstile');
      if (!el) return;
      turnstileWidgetId.current = window.turnstile.render('#register-turnstile', {
        sitekey: '0x4AAAAAADT5ebjsA6gd7yaa',
        theme: 'dark',
        callback: (token) => setTurnstileToken(token),
        'expired-callback': () => setTurnstileToken(null),
        'error-callback': () => setTurnstileToken(null),
      });
    }
    return () => {
      if (turnstileWidgetId.current != null) {
        try { window.turnstile.remove(turnstileWidgetId.current); } catch (e) { /* noop */ }
        turnstileWidgetId.current = null;
      }
    };
  }, [phase]);

  const submit = async (e) => {
    e.preventDefault();
    if (phase !== 'idle') return;

    // Client-side validation — generic enough to not enumerate, strict enough to catch obvious issues.
    if (!form.email.includes('@') || form.email.length < 5) return setErr('// invalid email format.');
    if (!form.handle.match(/^[a-zA-Z0-9_]{3,32}$/)) return setErr('// handle must be 3-32 alphanumeric chars or underscore.');
    if (form.password.length < 12) return setErr('// password must be at least 12 characters.');
    if (form.password !== form.confirm) return setErr('// passwords do not match.');
    if (strength < 3) return setErr('// password too weak. add length, mix cases + symbols.');
    if (!agree) return setErr('// must accept terms to continue.');
    if (form.email.length > 320 || form.handle.length > 32) return setErr('// payload too large.');

    // Require Turnstile token (skip check in mock mode for demo convenience)
    if (!turnstileToken && window.OBC_API.mode !== 'mock') return setErr('// captcha verification required.');

    setErr(null);
    setPhase('submitting');

    // Animated provisioning log — run animation and API call in parallel.
    const lines = [
      { t: 100,  text: 'validating email format ............... [ OK ]' },
      { t: 400,  text: 'checking handle availability .......... [ OK ]' },
      { t: 800,  text: 'hashing password (argon2id, t=3, m=64M) [ OK ]' },
      { t: 1300, text: 'provisioning customer record .......... [ OK ]' },
      { t: 1700, text: 'generating recovery codes ............. [ OK ]' },
      { t: 2100, text: 'enrolling in default 2FA prompt ....... [ OK ]' },
      { t: 2400, text: 'syncing to /api/customer (shopify) .... [ OK ]' },
      { t: 2700, text: 'issuing session token ................. [ OK ]' },
    ];

    const ANIM_DURATION = 3100;
    setLogLines([]);
    lines.forEach((l) => {
      setTimeout(() => setLogLines((prev) => [...prev, l]), l.t);
    });

    // Fire API call in parallel with the animation
    const apiPromise = window.OBC_API.register(
      { email: form.email, handle: form.handle, password: form.password, marketing },
      turnstileToken,
    );

    // Wait for both API and animation to finish
    const animPromise = new Promise((resolve) => setTimeout(resolve, ANIM_DURATION));

    try {
      const [provisioned] = await Promise.all([apiPromise, animPromise]);
      setNewUser(provisioned);
      setPhase('success');
      // Auto-route into account
      setTimeout(() => onRegistered(provisioned), 2200);
    } catch (error) {
      // API failed — return to idle with error
      setPhase('idle');
      setTurnstileToken(null);
      setErr('// registration failed. try again.');
    }
  };

  return (
    <section style={{ padding: '60px 24px 80px', maxWidth: 720, margin: '0 auto' }}>
      {/* terminal window header */}
      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 16px', borderBottom:'1px solid rgba(255,255,255,0.22)', background:'#0A0A0A', border:'1px solid rgba(255,255,255,0.22)' }}>
        <span style={{ width: 10, height: 10, borderRadius: '50%', background:'#FF3344' }}></span>
        <span style={{ width: 10, height: 10, borderRadius: '50%', background:'#FFD23F' }}></span>
        <span style={{ width: 10, height: 10, borderRadius: '50%', background:'#00FF41' }}></span>
        <span style={{ marginLeft: 14, fontSize: 12, color:'#BFBFBF', letterSpacing:'0.12em' }}>operator@brew-co — /bin/register</span>
        <span style={{ marginLeft:'auto', fontSize: 11, color:'#9A9A9A', letterSpacing:'0.18em' }}>SESSION: NEW · TLS 1.3</span>
      </div>

      <div style={{ border:'1px solid rgba(255,255,255,0.22)', borderTop:'none', padding:'36px 32px', background:'#000' }}>
        {phase === 'idle' && (
          <form onSubmit={submit}>
            <div style={{ fontSize: 11, color:'#00FF41', letterSpacing:'0.22em', marginBottom: 10 }}>$ ./register --new-operator</div>
            <h2 style={{ fontSize: 32, fontWeight: 800, color:'#FFF', letterSpacing:'0.04em', margin: '0 0 8px' }}>ENLIST</h2>
            <p style={{ fontSize: 13, color:'#BFBFBF', lineHeight: 1.6, letterSpacing:'0.04em', margin: '0 0 28px' }}>
              // create an account. unlock orders history, subscriptions, points, and earlier drop access.
            </p>

            <RegField label="EMAIL" value={form.email} onChange={(v) => set('email', v)} type="email" placeholder="operator@target.coffee" autoFocus />
            <RegField label="HANDLE" value={form.handle} onChange={(v) => set('handle', v)} placeholder="op1337" hint="// 3-32 chars. letters, numbers, underscore. shown on receipts." />
            <RegField label="PASSWORD" value={form.password} onChange={(v) => set('password', v)} type="password" placeholder="min 12 chars" />

            {/* strength meter */}
            {form.password && (
              <div style={{ marginTop: -8, marginBottom: 12 }}>
                <div style={{ display:'flex', gap: 4 }}>
                  {[1,2,3,4,5].map((i) => (
                    <div key={i} style={{
                      flex: 1, height: 4,
                      background: i <= strength ? strengthColors[strength] : 'rgba(255,255,255,0.14)',
                      transition: 'background 120ms',
                    }}></div>
                  ))}
                </div>
                <div style={{ marginTop: 6, fontSize: 10, letterSpacing:'0.2em', color: strengthColors[strength], fontWeight: 700 }}>
                  [{strengthLabels[strength]}]
                </div>
              </div>
            )}

            <RegField label="CONFIRM PASSWORD" value={form.confirm} onChange={(v) => set('confirm', v)} type="password" placeholder="re-enter to confirm" />

            <label style={{ display:'flex', alignItems:'flex-start', gap: 10, marginTop: 18, cursor:'pointer' }}>
              <input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} style={{ marginTop: 3, accentColor:'#00FF41' }} />
              <span style={{ fontSize: 12, color:'#E0E0E0', lineHeight: 1.6, letterSpacing:'0.03em' }}>
                i agree to the <span style={{ color:'#00FF41', textDecoration:'underline' }}>terms</span> and{' '}
                <span style={{ color:'#00FF41', textDecoration:'underline' }}>privacy policy</span>. i'll{' '}
                <span style={{ color:'#FFD23F' }}>brew responsibly</span> and{' '}
                <span style={{ color:'#FFD23F' }}>pwn responsibly</span>.
              </span>
            </label>
            <label style={{ display:'flex', alignItems:'flex-start', gap: 10, marginTop: 10, cursor:'pointer' }}>
              <input type="checkbox" checked={marketing} onChange={(e) => setMarketing(e.target.checked)} style={{ marginTop: 3, accentColor:'#00FF41' }} />
              <span style={{ fontSize: 12, color:'#BFBFBF', lineHeight: 1.6, letterSpacing:'0.03em' }}>
                send me new drop alerts. (~1 email/month. unsubscribe anytime.)
              </span>
            </label>

            {/* Turnstile captcha */}
            <div style={{ margin: '18px 0', padding: '14px', border: '1px dashed rgba(255,255,255,0.22)', background: '#0A0A0A' }}>
              <div style={{ fontSize: 10, letterSpacing: '0.2em', color: '#9A9A9A', marginBottom: 8 }}>// CAPTCHA VERIFICATION — cf-turnstile</div>
              <div id="register-turnstile"></div>
            </div>

            {err && (
              <div role="alert" style={{ marginTop: 18, padding: '10px 14px', border:'1px solid #FF3344', color:'#FF3344', fontSize: 12, letterSpacing:'0.06em' }}>
                {err}
              </div>
            )}

            <div style={{ display:'flex', alignItems:'center', gap: 12, marginTop: 24 }}>
              <button type="submit" disabled={!turnstileToken && window.OBC_API.mode !== 'mock'} style={{
                background: (!turnstileToken && window.OBC_API.mode !== 'mock') ? '#3A3A3A' : '#00FF41',
                color:'#000', border: '1px solid ' + ((!turnstileToken && window.OBC_API.mode !== 'mock') ? '#3A3A3A' : '#00FF41'),
                padding:'14px 22px', fontFamily:'inherit', fontWeight: 800, fontSize: 13,
                letterSpacing:'0.22em', cursor: (!turnstileToken && window.OBC_API.mode !== 'mock') ? 'not-allowed' : 'pointer', borderRadius: 2,
                opacity: (!turnstileToken && window.OBC_API.mode !== 'mock') ? 0.5 : 1,
              }}>{'>'} ./provision</button>
              <a style={{ marginLeft: 'auto', fontSize: 12, color:'#BFBFBF', letterSpacing:'0.15em', cursor:'pointer' }} onClick={onSwitchToLogin}>
                ./have-account?-login →
              </a>
            </div>

            <p style={{ marginTop: 22, fontSize: 10, color:'#7A7A7A', letterSpacing:'0.15em', lineHeight: 1.6 }}>
              // we use argon2id for password hashing. accounts sync to shopify customer api.<br/>
              // your email is for receipts + drop alerts only. no third-party sharing. no resale.
            </p>
          </form>
        )}

        {phase === 'submitting' && (
          <div style={{ color:'#00FF41', fontSize: 14, lineHeight: 1.9, letterSpacing:'0.04em' }}>
            <div>$ ./register --provision</div>
            {logLines.map((l, i) => (
              <div key={i}>&nbsp;&nbsp;{l.text}</div>
            ))}
            {logLines.length < 8 && (
              <div style={{ marginTop: 8, color:'#BFBFBF' }}>// provisioning<span className="provision-cursor"></span></div>
            )}
          </div>
        )}

        {phase === 'success' && newUser && (
          <div style={{ textAlign:'center' }}>
            <div style={{ fontSize: 11, color:'#00FF41', letterSpacing:'0.22em', marginBottom: 14 }}>$ whoami</div>
            <div style={{ fontSize: 14, color:'#BFBFBF', letterSpacing:'0.04em', lineHeight: 1.8 }}>
              <div>HANDLE: <span style={{ color:'#00FF41', fontWeight: 700 }}>{newUser.handle}</span></div>
              <div>EMAIL: <span style={{ color:'#00E5FF', fontWeight: 700 }}>{newUser.email}</span></div>
              <div>TIER: <span style={{ color:'#FFD23F', fontWeight: 700 }}>{newUser.tier}</span></div>
            </div>
            <div style={{ marginTop: 28 }}>
              <span className="reg-granted">[ ACCOUNT PROVISIONED ]</span>
            </div>
            <div style={{ marginTop: 18, fontSize: 12, color:'#BFBFBF', letterSpacing:'0.15em' }}>
              → routing to /account<span className="provision-cursor"></span>
            </div>
          </div>
        )}
      </div>

      <div style={{ marginTop: 18, fontSize: 10, color:'#7A7A7A', letterSpacing:'0.2em', textAlign:'center' }}>
        // by enlisting you agree to brew responsibly. pwn responsibly.
      </div>

      <style>{`
        .reg-granted {
          display: inline-block;
          background: #00FF41; color: #000;
          padding: 10px 20px;
          font-size: 18px; font-weight: 800; letter-spacing: 0.22em;
          box-shadow: 0 0 24px rgba(0,255,65,0.6);
          animation: regGrantedFlash 160ms steps(2) 5;
        }
        @keyframes regGrantedFlash {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.2; }
        }
        .provision-cursor::after {
          content: '█';
          animation: provBlink 1s steps(2) infinite;
          margin-left: 4px;
          color: #00FF41;
        }
        @keyframes provBlink { to { opacity: 0; } }
      `}</style>
    </section>
  );
};

const RegField = ({ label, value, onChange, type='text', placeholder, autoFocus, hint }) => (
  <div style={{ marginBottom: 16 }}>
    <div style={{ fontSize: 11, letterSpacing:'0.22em', color:'#E0E0E0', fontWeight: 700, marginBottom: 6 }}>{'>'} {label}</div>
    <input
      type={type}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      autoFocus={autoFocus}
      autoComplete={type === 'password' ? 'new-password' : (type === 'email' ? 'email' : 'username')}
      maxLength={type === 'password' ? 256 : 320}
      style={{
        width: '100%', background:'#0A0A0A', border:'1px solid rgba(255,255,255,0.28)',
        color:'#FFF', fontFamily:'inherit', fontSize: 14, padding:'12px 14px', borderRadius: 2,
      }}
      onFocus={(e) => { e.target.style.borderColor = '#00FF41'; e.target.style.boxShadow = '0 0 0 1px #00FF41'; }}
      onBlur={(e) => { e.target.style.borderColor = 'rgba(255,255,255,0.28)'; e.target.style.boxShadow = 'none'; }}
    />
    {hint && <div style={{ marginTop: 6, fontSize: 10, color:'#9A9A9A', letterSpacing:'0.05em' }}>{hint}</div>}
  </div>
);

window.Register = Register;
