'use client';

/**
 * app/share/space/[token]/space-otp-gate.jsx — Email-OTP gate for shared spaces.
 * Mirrors app/share/[token]/otp-gate.jsx. On successful verification it fetches
 * GET /api/share/space/[token] (the live artifact list) and renders the gallery.
 */

import { useState } from 'react';
import PublicSpaceCanvas from './public-space-canvas.jsx';

export default function SpaceOtpGate({ token, spaceName }) {
  const [stage, setStage] = useState('email'); // 'email' | 'code' | 'verified'
  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [artifacts, setArtifacts] = useState(null);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [expiresIn, setExpiresIn] = useState(null);

  async function handleRequestCode(e) {
    e.preventDefault();
    if (!email.trim() || !email.includes('@')) { setError('Please enter a valid email address.'); return; }
    setLoading(true); setError('');
    try {
      const res = await fetch(`/api/share/space/${token}/otp`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim().toLowerCase() }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.error || 'Failed to send verification code.'); return; }
      setExpiresIn(data.expires_in);
      if (data.warning) setError(data.warning);
      setStage('code');
    } catch { setError('Network error. Please try again.'); }
    finally { setLoading(false); }
  }

  async function handleVerifyCode(e) {
    e.preventDefault();
    if (code.trim().length !== 6) { setError('Please enter the 6-digit code from your email.'); return; }
    setLoading(true); setError('');
    try {
      const verifyRes = await fetch(`/api/share/space/${token}/verify`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim().toLowerCase(), code: code.trim() }),
      });
      if (verifyRes.status === 429) { setError('Too many failed attempts. Please wait and request a new code.'); setStage('email'); return; }
      if (verifyRes.status === 401) { setError('Incorrect code. Please try again.'); return; }
      if (!verifyRes.ok) { const d = await verifyRes.json().catch(() => ({})); setError(d.error || 'Verification failed.'); return; }

      const res = await fetch(`/api/share/space/${token}`, { method: 'GET' });
      if (!res.ok) { const d = await res.json().catch(() => ({})); setError(d.error || 'Failed to load space.'); return; }
      const data = await res.json();
      setArtifacts(data.artifacts || []);
      setStage('verified');
    } catch { setError('Network error. Please try again.'); }
    finally { setLoading(false); }
  }

  const inputStyle = { width: '100%', padding: '0.625rem 0.875rem', border: '1px solid #d1d5db', borderRadius: '6px', fontSize: '0.9375rem', outline: 'none', fontFamily: 'inherit' };
  const btnStyle = { width: '100%', padding: '0.625rem 1rem', background: '#1a1a1a', color: '#fff', border: 'none', borderRadius: '6px', fontSize: '0.9375rem', cursor: 'pointer', fontFamily: 'inherit', marginTop: '0.75rem' };
  const errorStyle = { color: '#dc2626', fontSize: '0.8125rem', marginTop: '0.5rem' };

  if (stage === 'verified' && artifacts !== null) {
    if (artifacts.length === 0) {
      return <p className="space-empty">This space has no artifacts yet. New artifacts will appear here automatically.</p>;
    }
    return (
      <PublicSpaceCanvas
        token={token}
        space={{ name: spaceName || 'Shared space' }}
        artifacts={artifacts}
        link={null}
      />
    );
  }

  return (
    <div style={{ maxWidth: '360px', margin: '0 auto', padding: '2rem 0' }}>
      <h2 style={{ fontSize: '1.125rem', fontWeight: 600, marginBottom: '0.5rem' }}>Verify your email</h2>
      <p style={{ fontSize: '0.875rem', color: '#555', marginBottom: '1.5rem', lineHeight: 1.5 }}>
        {stage === 'email'
          ? `This shared space requires email verification. Enter your email to receive a code.`
          : `A 6-digit code was sent to ${email}. Enter it below.${expiresIn ? ` Valid for ${Math.ceil(expiresIn / 60)} minutes.` : ''}`}
      </p>

      {stage === 'email' && (
        <form onSubmit={handleRequestCode}>
          <label style={{ fontSize: '0.8125rem', fontWeight: 500, display: 'block', marginBottom: '0.375rem' }}>Email address</label>
          <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@example.com" style={inputStyle} disabled={loading} />
          {error && <p style={errorStyle}>{error}</p>}
          <button type="submit" style={btnStyle} disabled={loading}>{loading ? 'Sending...' : 'Send verification code'}</button>
        </form>
      )}

      {stage === 'code' && (
        <form onSubmit={handleVerifyCode}>
          <label style={{ fontSize: '0.8125rem', fontWeight: 500, display: 'block', marginBottom: '0.375rem' }}>Verification code</label>
          <input type="text" required inputMode="numeric" pattern="[0-9]{6}" maxLength={6} value={code}
            onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))} placeholder="123456"
            style={{ ...inputStyle, letterSpacing: '0.25em', textAlign: 'center', fontSize: '1.25rem' }} disabled={loading} autoFocus />
          {error && <p style={errorStyle}>{error}</p>}
          <button type="submit" style={btnStyle} disabled={loading}>{loading ? 'Verifying...' : 'Verify code'}</button>
          <button type="button" onClick={() => { setStage('email'); setCode(''); setError(''); }}
            style={{ ...btnStyle, background: 'transparent', color: '#555', border: '1px solid #d1d5db', marginTop: '0.5rem' }} disabled={loading}>
            Use a different email
          </button>
        </form>
      )}
    </div>
  );
}
