// ResetPassword.jsx — password reset form for Shopify customerResetByUrl
// Handles the reset URL from email, collects new password, submits to worker.

const ResetPassword = ({ resetUrl, onLoggedIn, onSwitchToLogin }) => {
  const [password, setPassword] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [phase, setPhase] = React.useState('idle'); // idle | submitting | success | error
  const [err, setErr] = React.useState(null);
  const [turnstileToken, setTurnstileToken] = React.useState(null);
  const turnstileWidgetId = React.useRef(null);

  // Render Turnstile widget
  React.useEffect(() => {
    if (phase !== 'idle' || !window.turnstile) return;
    if (turnstileWidgetId.current != null) {
      try { window.turnstile.remove(turnstileWidgetId.current); } catch (e) { /* noop */ }
      turnstileWidgetId.current = null;
    }
    const el = document.getElementById('reset-turnstile');
    if (!el) return;
    turnstileWidgetId.current = window.turnstile.render('#reset-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();
    setErr(null);

    if (!resetUrl) { setErr('// invalid reset link. request a new one from the login page.'); setPhase('error'); return; }
    if (!password || !confirm) { setErr('// both fields required.'); return; }
    if (password.length < 8) { setErr('// password must be at least 8 characters.'); return; }
    if (password !== confirm) { setErr('// passwords do not match.'); return; }
    if (!turnstileToken && window.OBC_API.mode !== 'mock') { setErr('// complete captcha verification first.'); return; }

    setPhase('submitting');
    setErr('// resetting password...');

    try {
      const data = await window.OBC_API.resetPassword(resetUrl, password, turnstileToken);
      if (data.ok && data.customer) {
        setPhase('success');
        setErr(null);
        // Auto-login after 2s
        setTimeout(() => onLoggedIn(data.customer), 2000);
      } else if (data.ok) {
        setPhase('success');
        setErr(null);
      } else if (data.error === 'RESET_EXPIRED') {
        setPhase('error');
        setErr('// reset link has expired. request a new one.');
      } else if (data.error === 'PASSWORD_INVALID') {
        setPhase('idle');
        setErr('// ' + (data.detail || 'password does not meet requirements.'));
      } else {
        setPhase('error');
        setErr('// ' + (data.detail || 'reset failed. request a new link.'));
      }
    } catch (ex) {
      setPhase('error');
      setErr('// something went wrong. try requesting a new reset link.');
    }

    // Reset Turnstile
    if (window.turnstile && turnstileWidgetId.current != null) {
      window.turnstile.reset(turnstileWidgetId.current);
    }
    setTurnstileToken(null);
  };

  const fieldLabelStyle = { fontSize: 16, letterSpacing:'0.22em', color:'#E0E0E0', fontWeight: 700, marginBottom: 6 };
  const fieldInputStyle = {
    width: '100%', background:'#0A0A0A', border:'1px solid rgba(255,255,255,0.28)',
    color:'#FFF', fontFamily:'inherit', fontSize: 17, padding:'12px 14px', borderRadius: 2,
    boxSizing: 'border-box',
  };
  const handleFieldFocus = (e) => { e.target.style.borderColor = '#00FF41'; e.target.style.boxShadow = '0 0 0 1px #00FF41'; };
  const handleFieldBlur = (e) => { e.target.style.borderColor = 'rgba(255,255,255,0.28)'; e.target.style.boxShadow = 'none'; };

  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: 16, color:'#BFBFBF', letterSpacing:'0.12em' }}>operator@brew-co — /bin/auth</span>
        <span style={{ marginLeft:'auto', fontSize: 16, color:'#9A9A9A', letterSpacing:'0.1em' }}>PASSWORD RESET</span>
      </div>

      <div style={{ border:'1px solid rgba(255,255,255,0.22)', borderTop:'none', padding:'36px 32px', background:'#000' }}>
        {/* SUCCESS */}
        {phase === 'success' && (
          <div>
            <div style={{ fontSize: 16, color:'#00FF41', letterSpacing:'0.22em', marginBottom: 10 }}>$ ./auth --reset</div>
            <h2 style={{ fontSize: 32, fontWeight: 800, color:'#00FF41', letterSpacing:'0.04em', margin: '0 0 16px' }}>PASSWORD UPDATED</h2>
            <p style={{ fontSize: 17, color:'#BFBFBF', lineHeight: 1.6, letterSpacing:'0.04em', margin: '0 0 24px' }}>
              // credentials rotated successfully. redirecting to account...
            </p>
            <div style={{ borderTop:'1px solid rgba(255,255,255,0.12)', paddingTop: 20 }}>
              <a onClick={() => onSwitchToLogin()} style={{ fontSize: 16, color:'#00FF41', letterSpacing:'0.15em', cursor:'pointer' }}>{'>'} ./login</a>
            </div>
          </div>
        )}

        {/* ERROR — expired or invalid link */}
        {phase === 'error' && (
          <div>
            <div style={{ fontSize: 16, color:'#FF3344', letterSpacing:'0.22em', marginBottom: 10 }}>$ ./auth --reset</div>
            <h2 style={{ fontSize: 32, fontWeight: 800, color:'#FFF', letterSpacing:'0.04em', margin: '0 0 16px' }}>RESET FAILED</h2>
            {err && (
              <div role="alert" style={{ marginBottom: 20, padding: '10px 14px', border:'1px solid #FF3344', color:'#FF3344', fontSize: 16, letterSpacing:'0.06em' }}>
                {err}
              </div>
            )}
            <p style={{ fontSize: 17, color:'#BFBFBF', lineHeight: 1.6, letterSpacing:'0.04em', margin: '0 0 24px' }}>
              // use forgot password to request a fresh link.
            </p>
            <div style={{ borderTop:'1px solid rgba(255,255,255,0.12)', paddingTop: 20 }}>
              <a onClick={() => onSwitchToLogin()} style={{ fontSize: 16, color:'#00FF41', letterSpacing:'0.15em', cursor:'pointer' }}>{'>'} ./login</a>
            </div>
          </div>
        )}

        {/* IDLE / SUBMITTING — form */}
        {(phase === 'idle' || phase === 'submitting') && (
          <form onSubmit={submit}>
            <div style={{ fontSize: 16, color:'#00FF41', letterSpacing:'0.22em', marginBottom: 10 }}>$ ./auth --reset</div>
            <h2 style={{ fontSize: 32, fontWeight: 800, color:'#FFF', letterSpacing:'0.04em', margin: '0 0 8px' }}>SET NEW PASSWORD</h2>
            <p style={{ fontSize: 17, color:'#BFBFBF', lineHeight: 1.6, letterSpacing:'0.04em', margin: '0 0 28px' }}>
              // enter your new credentials below.
            </p>

            <div style={{ marginTop: 18 }}>
              <div style={fieldLabelStyle}>{'>'} NEW PASSWORD</div>
              <input type="password" value={password} onChange={(e) => setPassword(e.target.value)}
                placeholder="minimum 8 characters" autoFocus autoComplete="new-password" maxLength={256}
                style={fieldInputStyle} onFocus={handleFieldFocus} onBlur={handleFieldBlur} />
            </div>
            <div style={{ marginTop: 18 }}>
              <div style={fieldLabelStyle}>{'>'} CONFIRM PASSWORD</div>
              <input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)}
                placeholder="re-enter new password" autoComplete="new-password" maxLength={256}
                style={fieldInputStyle} onFocus={handleFieldFocus} onBlur={handleFieldBlur} />
            </div>

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

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

            <div style={{ display:'flex', alignItems:'center', gap: 12, marginTop: 24 }}>
              <button type="submit" disabled={phase === 'submitting' || (!turnstileToken && window.OBC_API.mode !== 'mock')} style={{
                background: (phase === 'submitting' || (!turnstileToken && window.OBC_API.mode !== 'mock')) ? '#3A3A3A' : '#00FF41',
                color:'#000', border: '1px solid ' + ((phase === 'submitting' || (!turnstileToken && window.OBC_API.mode !== 'mock')) ? '#3A3A3A' : '#00FF41'),
                padding:'14px 22px', fontFamily:'inherit', fontWeight: 800, fontSize: 17,
                letterSpacing:'0.22em', cursor: (phase === 'submitting' || (!turnstileToken && window.OBC_API.mode !== 'mock')) ? 'not-allowed' : 'pointer', borderRadius: 2,
                opacity: (phase === 'submitting' || (!turnstileToken && window.OBC_API.mode !== 'mock')) ? 0.5 : 1,
              }}>{'>'} ./reset</button>

              <a style={{ marginLeft: 'auto', fontSize: 16, color:'#BFBFBF', letterSpacing:'0.15em', cursor:'pointer' }} onClick={() => onSwitchToLogin()}>
                {'<'} back to login
              </a>
            </div>
          </form>
        )}
      </div>
    </section>
  );
};

window.ResetPassword = ResetPassword;
