// Tela: Auth (login / cadastro / esqueci a senha)
const { useState: useStateAuth } = React;

function Auth({ t, lang, setLang, mode = 'signin', onAuth, onBack, onToggle, onForgot }) {
  const [email, setEmail] = useStateAuth('');
  const [password, setPassword] = useStateAuth('');
  const [name, setName] = useStateAuth('');
  const [err, setErr] = useStateAuth('');
  const [loading, setLoading] = useStateAuth(false);
  const [showPw, setShowPw] = useStateAuth(false);
  const isSignup = mode === 'signup';

  async function submit(e) {
    e.preventDefault();
    setErr(''); setLoading(true);
    try {
      const res = isSignup
        ? await window.DB.signUp({ email, password, name })
        : await window.DB.signIn({ email, password });
      onAuth(res);
    } catch (e) {
      setErr(e.message || 'Erro ao autenticar.');
    } finally { setLoading(false); }
  }

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: 'var(--cream)', color: 'var(--ink)' }}>
      <div className="mv-auth-wrap">
        <button className="mv-back" onClick={onBack} aria-label="back">←</button>
        <div className="mv-auth-head">
          <div className="mv-brand-mark mv-auth-mark">✧</div>
          <h1 className="mv-h2">{isSignup ? t.auth_create : t.auth_welcome}</h1>
        </div>
        <form onSubmit={submit} className="mv-form">
          {isSignup && (
            <label className="mv-field">
              <span>{t.auth_name}</span>
              <input value={name} onChange={e => setName(e.target.value)} required autoComplete="name" />
            </label>
          )}
          <label className="mv-field">
            <span>{t.auth_email}</span>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)} required autoComplete="email" />
          </label>
          <label className="mv-field mv-field-pw">
            <span>{t.auth_password}</span>
            <div className="mv-pw-wrap">
              <input type={showPw ? 'text' : 'password'} value={password} onChange={e => setPassword(e.target.value)} required minLength={6} autoComplete={isSignup ? 'new-password' : 'current-password'} />
              <button type="button" className="mv-pw-eye" onClick={() => setShowPw(v => !v)} aria-label={showPw ? 'hide password' : 'show password'} tabIndex={-1}>
                {showPw ? (
                  <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
                ) : (
                  <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                )}
              </button>
            </div>
          </label>
          {!isSignup && (
            <div className="mv-auth-forgot-row">
              <button type="button" className="mv-link mv-link-soft" onClick={onForgot}>{t.auth_forgot}</button>
            </div>
          )}
          {err && <div className="mv-err">{err}</div>}
          <button className="mv-btn-primary mv-btn-lg" type="submit" disabled={loading}>
            {loading ? '…' : (isSignup ? t.auth_register : t.auth_login)}
          </button>
        </form>
        <p className="mv-auth-toggle">
          {isSignup ? t.auth_have : t.auth_no}
          {' '}
          <button className="mv-link" onClick={onToggle}>{isSignup ? t.auth_login : t.auth_register}</button>
        </p>
        <p className="mv-fineprint mv-auth-terms">
          {t.auth_terms} <a href={t.terms_url} style={{color:'var(--gold-deep)'}}>{t.nav_terms}</a> · <a href={t.privacy_url} style={{color:'var(--gold-deep)'}}>{t.nav_privacy}</a>
        </p>
        <div className="mv-auth-lang">
          <LangSwitch lang={lang} setLang={setLang} />
        </div>
      </div>
    </div>
  );
}

function ForgotPassword({ t, lang, setLang, onBack }) {
  const [email, setEmail] = useStateAuth('');
  const [err, setErr] = useStateAuth('');
  const [loading, setLoading] = useStateAuth(false);
  const [sent, setSent] = useStateAuth(false);

  async function submit(e) {
    e.preventDefault();
    setErr(''); setLoading(true);
    try {
      await window.DB.resetPassword({ email });
      setSent(true);
    } catch (e) {
      setErr(e.message || 'Erro ao enviar.');
    } finally { setLoading(false); }
  }

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: 'var(--cream)', color: 'var(--ink)' }}>
      <div className="mv-auth-wrap">
        <button className="mv-back" onClick={onBack} aria-label="back">←</button>
        <div className="mv-auth-head">
          <div className="mv-brand-mark mv-auth-mark">✧</div>
          <h1 className="mv-h2">{sent ? t.forgot_sent_title : t.forgot_title}</h1>
          <p className="mv-lead" style={{ marginTop: 6, fontSize: 14 }}>
            {sent ? t.forgot_sent_sub : t.forgot_sub}
          </p>
        </div>
        {!sent ? (
          <form onSubmit={submit} className="mv-form">
            <label className="mv-field">
              <span>{t.auth_email}</span>
              <input type="email" value={email} onChange={e => setEmail(e.target.value)} required autoComplete="email" autoFocus />
            </label>
            {err && <div className="mv-err">{err}</div>}
            <button className="mv-btn-primary mv-btn-lg" type="submit" disabled={loading}>
              {loading ? '…' : t.forgot_send}
            </button>
          </form>
        ) : (
          <div className="mv-form">
            <div className="mv-forgot-mark">✉</div>
            <button className="mv-btn-primary mv-btn-lg" onClick={onBack}>{t.forgot_back}</button>
          </div>
        )}
        <p className="mv-auth-toggle" style={{ marginTop: 18 }}>
          <button className="mv-link" onClick={onBack}>← {t.forgot_back}</button>
        </p>
        <div className="mv-auth-lang">
          <LangSwitch lang={lang} setLang={setLang} />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Auth, ForgotPassword });
