// screen-auth.jsx — Sign in / Sign up screen

function AuthScreen({ go, params }) {
  const [mode, setMode] = React.useState(params?.mode || 'signup');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [showPw, setShowPw] = React.useState(false);
  const [errors, setErrors] = React.useState({});

  const validate = () => {
    const e = {};
    if (!email) e.email = 'Email obbligatoria';
    else if (!/^\S+@\S+\.\S+$/.test(email)) e.email = 'Email non valida';
    if (!password) e.password = 'Password obbligatoria';
    else if (mode === 'signup' && password.length < 8) e.password = 'Almeno 8 caratteri';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    if (mode === 'signup') {
      go('register', { email });
    } else {
      // For demo: signin goes straight to dashboard
      go('dashboard-v2', { mockUser: true });
    }
  };

  return (
    <div style={{
      minHeight: '100%',
      display: 'flex',
      flexDirection: 'column',
    }}>
      {/* Top bar */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '20px clamp(20px, 5vw, 40px)',
      }}>
        <button onClick={() => go('landing')} style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          padding: 0,
        }}>
          <Logo size={20} />
        </button>
        <Button size="sm" variant="ghost" onClick={() => go('landing')}>← Indietro</Button>
      </div>

      <div style={{
        flex: 1,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 'clamp(20px, 4vw, 40px) clamp(20px, 5vw, 40px) 60px',
      }}>
        <div style={{ width: '100%', maxWidth: 420 }}>
          <h1 style={{
            fontFamily: '"Instrument Serif", Georgia, serif',
            fontSize: 'clamp(36px, 5vw, 52px)',
            fontWeight: 400,
            letterSpacing: '-0.02em',
            margin: 0,
            color: 'var(--ink)',
            lineHeight: 1.05,
          }}>
            {mode === 'signup' ? (
              <>Benvenuto su <em style={{ color: 'var(--accent-strong)' }}>Trygo</em></>
            ) : (
              <>Bentornato su <em style={{ color: 'var(--accent-strong)' }}>Trygo</em></>
            )}
          </h1>
          <p style={{
            color: 'var(--muted)', fontSize: 15, marginTop: 8,
            letterSpacing: '-0.005em',
          }}>
            {mode === 'signup'
              ? 'Crea un account in pochi secondi. Poi costruisci il tuo profilo.'
              : 'Accedi per continuare a migliorare il tuo gioco.'}
          </p>

          {/* Tab switch */}
          <div style={{ marginTop: 28, marginBottom: 24 }}>
            <Segmented
              fullWidth
              value={mode}
              onChange={(v) => { setMode(v); setErrors({}); }}
              options={[
                { value: 'signup', label: 'Registrati' },
                { value: 'signin', label: 'Accedi' },
              ]}
            />
          </div>

          <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Field label="Email" required error={errors.email}>
              <Input
                type="email"
                placeholder="tu@esempio.it"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                icon={<EmailIcon />}
              />
            </Field>
            <Field label="Password" required error={errors.password}
                   hint={mode === 'signup' ? 'Almeno 8 caratteri' : null}>
              <Input
                type={showPw ? 'text' : 'password'}
                placeholder="••••••••"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                icon={<LockIcon2 />}
                suffix={
                  <button type="button" onClick={() => setShowPw((s) => !s)}
                    style={{
                      background: 'none', border: 'none', cursor: 'pointer',
                      color: 'var(--muted)', fontSize: 13, padding: 0,
                      fontFamily: 'inherit',
                    }}>
                    {showPw ? 'Nascondi' : 'Mostra'}
                  </button>
                }
              />
            </Field>

            {mode === 'signin' && (
              <div style={{ textAlign: 'right', marginTop: -4 }}>
                <a href="#" style={{
                  color: 'var(--accent-strong)', fontSize: 13, textDecoration: 'none',
                }}>Password dimenticata?</a>
              </div>
            )}

            <Button type="submit" size="lg" fullWidth>
              {mode === 'signup' ? 'Continua →' : 'Accedi'}
            </Button>
          </form>

          {/* Divider */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12,
            margin: '24px 0', color: 'var(--muted)', fontSize: 12,
          }}>
            <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
            OPPURE
            <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Button variant="secondary" fullWidth icon={<GoogleG />}>
              Continua con Google
            </Button>
            <Button variant="secondary" fullWidth icon={<AppleLogo />}>
              Continua con Apple
            </Button>
          </div>

          <p style={{
            fontSize: 12, color: 'var(--muted)',
            marginTop: 24, textAlign: 'center', lineHeight: 1.5,
          }}>
            Continuando accetti i nostri <a href="#" style={{ color: 'var(--ink)' }}>Termini</a> e la
            {' '}<a href="#" style={{ color: 'var(--ink)' }}>Privacy Policy</a>.
          </p>
        </div>
      </div>
    </div>
  );
}

function EmailIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
      <rect x="2" y="4" width="14" height="10" rx="2" stroke="currentColor" strokeWidth="1.4" />
      <path d="M2.5 5l6.5 5 6.5-5" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" />
    </svg>
  );
}
function LockIcon2() {
  return (
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
      <rect x="3" y="8" width="12" height="8" rx="2" stroke="currentColor" strokeWidth="1.4" />
      <path d="M5.5 8V5.5a3.5 3.5 0 1 1 7 0V8" stroke="currentColor" strokeWidth="1.4" />
    </svg>
  );
}
function GoogleG() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24">
      <path fill="#4285F4" d="M22.6 12.2c0-.7-.1-1.4-.2-2H12v3.8h6c-.3 1.4-1.1 2.6-2.3 3.4v2.8h3.7c2.2-2 3.2-4.9 3.2-8z"/>
      <path fill="#34A853" d="M12 23c3.1 0 5.7-1 7.6-2.8L15.9 17c-1 .7-2.3 1.1-3.9 1.1-3 0-5.5-2-6.4-4.7H1.8v2.9C3.7 20 7.5 23 12 23z"/>
      <path fill="#FBBC04" d="M5.6 13.4c-.2-.7-.4-1.4-.4-2.2s.1-1.5.4-2.2V6.1H1.8C1 7.6.5 9.3.5 11.2s.5 3.6 1.3 5.1l3.8-2.9z"/>
      <path fill="#EA4335" d="M12 4.6c1.7 0 3.2.6 4.4 1.7l3.3-3.3C17.7 1.1 15.1 0 12 0 7.5 0 3.7 3 1.8 6.1l3.8 2.9C6.5 6.6 9 4.6 12 4.6z"/>
    </svg>
  );
}
function AppleLogo() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
      <path d="M12.5 8.4c0-2.2 1.8-3.3 1.9-3.4-1-1.5-2.6-1.7-3.2-1.7-1.4-.1-2.7.8-3.3.8s-1.7-.8-2.9-.8c-1.5 0-2.9.9-3.6 2.2-1.6 2.7-.4 6.7 1 8.9.7 1.1 1.6 2.3 2.8 2.3 1.1 0 1.5-.7 2.9-.7s1.7.7 2.9.7c1.2 0 2-1.1 2.7-2.2.8-1.3 1.1-2.5 1.2-2.6-.1 0-2.3-.9-2.4-3.5zM10.4 1.8c.6-.7 1-1.7.9-2.7-.9 0-2 .6-2.6 1.3-.5.6-1 1.7-.9 2.7 1 .1 2-.6 2.6-1.3z"/>
    </svg>
  );
}

Object.assign(window, { AuthScreen });
