// Login + registrazione con Supabase Auth

const GoogleMark = () => (
  <svg aria-hidden="true" width="18" height="18" viewBox="0 0 18 18" style={{ flexShrink: 0 }}>
    <path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92c1.7-1.57 2.68-3.88 2.68-6.62z"/>
    <path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.81.54-1.84.86-3.04.86-2.35 0-4.34-1.59-5.05-3.72H.93v2.33A9 9 0 0 0 9 18z"/>
    <path fill="#FBBC05" d="M3.95 10.7A5.4 5.4 0 0 1 3.67 9c0-.59.1-1.16.28-1.7V4.97H.93A9 9 0 0 0 0 9c0 1.45.35 2.82.93 4.03l3.02-2.33z"/>
    <path fill="#EA4335" d="M9 3.58c1.32 0 2.5.45 3.44 1.34l2.58-2.58C13.46.89 11.43 0 9 0A9 9 0 0 0 .93 4.97L3.95 7.3C4.66 5.17 6.65 3.58 9 3.58z"/>
  </svg>
);

function authRedirectUrl() {
  return window.TT_CONFIG?.logoutRedirectUrl || `${window.location.origin}/app`;
}

const AuthScreen = ({ supabaseClient, onAuth, initialMessage = '' }) => {
  const [mode, setMode] = React.useState('login');
  const [email, setEmail] = React.useState('');
  const [pwd, setPwd] = React.useState('');
  const [name, setName] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [message, setMessage] = React.useState('');

  React.useEffect(() => {
    setMessage(initialMessage);
  }, [initialMessage]);

  const signInWithGoogle = async () => {
    if (loading) return;

    setLoading(true);
    setMessage('');

    try {
      const { error } = await supabaseClient.auth.signInWithOAuth({
        provider: 'google',
        options: {
          redirectTo: authRedirectUrl(),
        },
      });
      if (error) throw error;
    } catch (error) {
      setLoading(false);
      setMessage(error.message || 'Non siamo riusciti ad aprire Google. Riprova.');
    }
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!email || loading) return;
    if (mode !== 'recover' && !pwd) return;

    setLoading(true);
    setMessage('');

    try {
      if (mode === 'recover') {
        const { error } = await supabaseClient.auth.resetPasswordForEmail(email, {
          redirectTo: window.TT_CONFIG?.passwordResetRedirectUrl || `${window.location.origin}/app?recovery=1`,
        });
        if (error) throw error;
        setMessage('Link di recupero inviato. Controlla la tua email.');
      } else if (mode === 'login') {
        const { data, error } = await supabaseClient.auth.signInWithPassword({
          email,
          password: pwd,
        });
        if (error) throw error;
        onAuth(data.user);
      } else {
        const { data, error } = await supabaseClient.auth.signUp({
          email,
          password: pwd,
          options: {
            data: { name: name || email.split('@')[0] },
          },
        });
        if (error) throw error;
        if (data.session && data.user) {
          onAuth(data.user);
        } else {
          setMessage('Account creato. Controlla la tua email per confermare l’accesso.');
        }
      }
    } catch (error) {
      setMessage(error.message || 'Non siamo riusciti ad accedere. Riprova.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div data-screen-label={mode === 'login' ? 'Login' : 'Registrazione'}
      className="auth-grid"
      style={{ minHeight:'100vh' }}>
      <div style={{
        position:'relative', overflow:'hidden',
        borderRight:'2px solid var(--ink)',
        padding:'40px 56px', display:'flex', flexDirection:'column',
        background: 'var(--cream)',
      }}>
        <Logo size={40} />

        <div style={{ flex: 1, display:'flex', flexDirection:'column', justifyContent:'center', position:'relative', paddingRight: 24 }}>
          <Sticker kind="circle"   style={{ bottom: 80, right: 10 }} />
          <Sticker kind="sun"      style={{ top: 10, right: 60, transform: 'rotate(12deg)' }} />
          <Sticker kind="star"     style={{ width: 22, height: 22, top: 200, right: 110 }} />

          <h1 className="display" style={{ fontSize: 'clamp(36px, 5.4vw, 84px)', margin: 0 }}>
            DAL <span className="hl">PARLATO</span><br/>
            AL <span className="outline-text">TESTO.</span><br/>
            <span style={{ display:'inline-block', marginTop: 8 }}>
              IN <span className="hl sun" style={{ transform:'rotate(1deg)' }}>UN CLICK</span>.
            </span>
          </h1>
          <p style={{ fontSize: 18, maxWidth: 460, marginTop: 32, lineHeight: 1.5 }}>
            Carica un audio o video. Scegli la lingua. Ricevi un testo pronto
            da copiare, rileggere o esportare.
          </p>

          <div style={{ display:'flex', gap: 18, marginTop: 36, alignItems:'center' }}>
            <div style={{ display:'flex', gap:-8 }}>
              {['#FF6B6B','#FFE56B','#B6E8C8','#DDD6F5'].map((c,i) => (
                <div key={i} style={{
                  width: 36, height: 36, borderRadius: '50%',
                  background: c, border: '2px solid var(--ink)',
                  marginLeft: i ? -10 : 0,
                }} />
              ))}
            </div>
            <div style={{ fontSize: 13 }}>
              <strong>30 minuti</strong> inclusi<br/>
              <span
                className="hl mint"
                style={{
                  display: 'inline-block',
                  marginTop: 8,
                  fontSize: 10,
                  fontWeight: 700,
                  letterSpacing: '0.12em',
                  textTransform: 'uppercase',
                }}
              >
                Nessun abbonamento richiesto
              </span>
            </div>
          </div>
        </div>

        <div className="mono" style={{ fontSize: 11, color:'#5a554c', letterSpacing:'0.12em' }}>
          +250.000 ore trascritte
        </div>
      </div>

      <div style={{
        background: 'var(--cream-deep)',
        backgroundImage:
          'radial-gradient(rgba(19,18,17,0.08) 1px, transparent 1px)',
        backgroundSize: '18px 18px',
        padding: '40px 56px',
        display:'flex', alignItems:'center', justifyContent:'center',
        position:'relative',
      }}>
        <Sticker kind="mint" style={{ top: 60, left: 40 }} />
        <Sticker kind="star" style={{ width: 28, height: 28, bottom: 80, right: 80 }} />

        <form onSubmit={submit} style={{
          width: '100%', maxWidth: 460,
          background: 'var(--paper)', border: '2px solid var(--ink)',
          boxShadow: 'var(--shadow-lg)', padding: 36,
          position: 'relative',
        }}>
          <div style={{
            display:'inline-flex', border:'2px solid var(--ink)', boxShadow:'var(--shadow-sm)',
            background:'var(--cream)', marginBottom: 28,
          }}>
            {['login','register'].map(m => (
              <button key={m} type="button" onClick={() => { setMode(m); setMessage(''); }}
                style={{
                  background: mode === m ? 'var(--ink)' : 'transparent',
                  color: mode === m ? '#FFFCEC' : 'var(--ink)',
                  border:'none', padding:'10px 22px',
                  fontSize: 12, fontWeight: 700, letterSpacing:'0.12em', textTransform:'uppercase',
                }}>
                {m === 'login' ? 'Accedi' : 'Registrati'}
              </button>
            ))}
          </div>

          <h2 className="display" style={{ fontSize: 36, margin: '0 0 8px' }}>
            {mode === 'login' ? <>Bentornato.</> : mode === 'recover' ? <>Recupero.</> : <>Iniziamo.</>}
          </h2>
          <p style={{ margin: '0 0 28px', color:'#5a554c', fontSize: 14 }}>
            {mode === 'login'
              ? 'Accedi per vedere lo storico e caricare nuovi audio.'
              : mode === 'recover'
                ? 'Ricevi via email il link per impostare una nuova password.'
                : 'Crea l’account e ricevi 15 crediti iniziali una tantum.'}
          </p>

          <div style={{ display:'grid', gap: 18 }}>
            {mode !== 'recover' && (
              <>
                <button type="button" onClick={signInWithGoogle} disabled={loading}
                  style={{
                    width: '100%',
                    minHeight: 48,
                    background: 'var(--paper)',
                    color: 'var(--ink)',
                    border: '2px solid var(--ink)',
                    boxShadow: 'var(--shadow-sm)',
                    display: 'inline-flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: 10,
                    padding: '12px 16px',
                    fontSize: 14,
                    fontWeight: 800,
                    letterSpacing: '0.04em',
                    textTransform: 'uppercase',
                    cursor: loading ? 'default' : 'pointer',
                    opacity: loading ? 0.55 : 1,
                  }}>
                  <GoogleMark />
                  {loading ? 'Apertura Google...' : 'Continua con Google'}
                </button>
                <div style={{ display:'grid', gridTemplateColumns:'1fr auto 1fr', alignItems:'center', gap: 12, color:'#5a554c', fontSize: 11, fontWeight: 700, letterSpacing:'0.12em', textTransform:'uppercase' }}>
                  <span style={{ height: 2, background:'var(--ink)', opacity: 0.18 }} />
                  <span>oppure</span>
                  <span style={{ height: 2, background:'var(--ink)', opacity: 0.18 }} />
                </div>
              </>
            )}
            {mode === 'register' && (
              <Field label="Nome">
                <TextInput value={name} onChange={e => setName(e.target.value)} placeholder="Come ti chiami?" />
              </Field>
            )}
            <Field label="Email">
              <TextInput type="email" required value={email} onChange={e => setEmail(e.target.value)} placeholder="tu@dominio.it" />
            </Field>
            {mode !== 'recover' && (
              <Field label="Password">
                <TextInput type="password" required minLength={6} value={pwd} onChange={e => setPwd(e.target.value)} placeholder={'•'.repeat(8)} />
              </Field>
            )}
          </div>

          {message && (
            <div style={{
              marginTop: 18, padding: 12,
              background: message.toLowerCase().includes('creato') || message.toLowerCase().includes('inviato') ? 'var(--mint)' : 'var(--coral-soft)',
              border:'2px solid var(--ink)',
              fontSize: 13,
            }}>{message}</div>
          )}

          <div style={{ marginTop: 28 }}>
            <Btn type="submit" variant="primary" size="lg" full disabled={loading}>
              {loading ? 'Attendi...' : mode === 'login' ? 'Accedi →' : mode === 'recover' ? 'Invia link →' : 'Crea account →'}
            </Btn>
          </div>

          <div style={{
            marginTop: 18, fontSize: 13, textAlign:'center', color:'#5a554c'
          }}>
            {mode === 'login' ? (
              <>
                Nuovo qui? <a onClick={() => setMode('register')} style={{ fontWeight: 700, color:'var(--ink)', cursor:'pointer', textDecoration:'underline' }}>Crea un account</a>
                <span style={{ margin:'0 8px' }}>·</span>
                <a onClick={() => { setMode('recover'); setMessage(''); }} style={{ fontWeight: 700, color:'var(--ink)', cursor:'pointer', textDecoration:'underline' }}>Password dimenticata?</a>
              </>
            ) : mode === 'recover' ? (
              <>Tornare all’accesso? <a onClick={() => { setMode('login'); setMessage(''); }} style={{ fontWeight: 700, color:'var(--ink)', cursor:'pointer', textDecoration:'underline' }}>Accedi</a></>
            ) : (
              <>Hai già un account? <a onClick={() => setMode('login')} style={{ fontWeight: 700, color:'var(--ink)', cursor:'pointer', textDecoration:'underline' }}>Accedi</a></>
            )}
          </div>
        </form>
      </div>
    </div>
  );
};

Object.assign(window, { AuthScreen });
