// Auth.jsx — Login / Register screen
(function () {
  const { useState } = React;
  const { register: apiRegister, login: apiLogin } = window.AliaAPI;

  function AuthScreen({ onComplete }) {
    const [mode, setMode]       = useState('login');
    const [lang, setLang]       = useState(() => localStorage.getItem('alia_lang') || 'ru');
    const [name, setName]       = useState('');
    const [email, setEmail]     = useState('');
    const [password, setPassword]   = useState('');
    const [confirmPw, setConfirmPw] = useState('');
    const [error, setError]     = useState('');
    const [loading, setLoading] = useState(false);
    const [accepted, setAccepted] = useState(false);
    const [docView, setDocView]   = useState(null);

    const L = {
      ru: { login:'Войти', register:'Регистрация', nameLabel:'Ваше имя', emailLabel:'Email',
            pwLabel:'Пароль', confirmLabel:'Подтвердите пароль', btnLogin:'Войти',
            btnReg:'Создать аккаунт', btnGuest:'Войти без аккаунта',
            tagline:'Ваш тёплый помощник',
            errName:'Введите ваше имя', errEmail:'Введите email',
            errPw:'Минимум 6 символов', errMatch:'Пароли не совпадают', errFill:'Заполните все поля',
            errAccept:'Примите условия, чтобы продолжить', consentPre:'Я принимаю ' },
      en: { login:'Sign In', register:'Sign Up', nameLabel:'Your name', emailLabel:'Email',
            pwLabel:'Password', confirmLabel:'Confirm password', btnLogin:'Sign In',
            btnReg:'Create Account', btnGuest:'Continue as Guest',
            tagline:'Your warm companion',
            errName:'Enter your name', errEmail:'Enter email',
            errPw:'Min 6 characters', errMatch:'Passwords do not match', errFill:'Fill in all fields',
            errAccept:'Please accept the terms to continue', consentPre:'I accept the ' },
    };
    const l = L[lang] || L.ru;

    async function handleSubmit() {
      setError('');
      if (mode === 'register') {
        if (!name.trim())           { setError(l.errName);  return; }
        if (!email.trim())          { setError(l.errEmail); return; }
        if (password.length < 6)    { setError(l.errPw);    return; }
        if (password !== confirmPw) { setError(l.errMatch); return; }
        if (!accepted)              { setError(l.errAccept); return; }
      } else {
        if (!email.trim() || !password) { setError(l.errFill); return; }
      }

      setLoading(true);
      try {
        let userData;
        if (mode === 'register') {
          userData = await apiRegister(name.trim(), email.trim(), password);
          try { localStorage.setItem('alia_legal_accepted', '1'); } catch (e) {}
        } else {
          userData = await apiLogin(email.trim(), password);
        }
        userData.lang = lang;
        localStorage.setItem('alia_lang', lang);
        onComplete(userData);
      } catch (err) {
        const knownErrors = {
          'email already registered': lang === 'ru' ? 'Email уже зарегистрирован' : 'Email already registered',
          'invalid email or password': lang === 'ru' ? 'Неверный email или пароль' : 'Invalid email or password',
        };
        setError(knownErrors[err.message] || err.message);
      } finally {
        setLoading(false);
      }
    }

    const s = {
      wrap: { display:'flex', flexDirection:'column', height:'100dvh', overflowY:'auto', background:'var(--bg)' },
      topBar: { display:'flex', justifyContent:'flex-end',
                padding:'14px 20px', paddingTop:'calc(14px + env(safe-area-inset-top))' },
      langBtn: { background:'var(--primary-light)', border:'none', borderRadius:8,
                 padding:'6px 14px', fontSize:12, fontWeight:800, color:'var(--primary)',
                 cursor:'pointer', fontFamily:'Nunito,sans-serif', letterSpacing:'0.3px' },
      inner: { flex:1, display:'flex', flexDirection:'column', alignItems:'center',
               justifyContent:'flex-start', padding:'24px 20px 48px' },
      logo: { fontSize:56, marginBottom:6, textAlign:'center' },
      appName: { fontSize:36, fontWeight:900, color:'var(--primary)', letterSpacing:'-0.5px',
                 marginBottom:6, textAlign:'center' },
      tagline: { fontSize:15, color:'var(--text-2)', textAlign:'center', marginBottom:32,
                 lineHeight:1.5, maxWidth:260 },
      card: { background:'var(--bg-card)', borderRadius:24, padding:'24px 22px',
              width:'100%', maxWidth:380, boxShadow:'0 4px 28px var(--shadow)' },
      tabs: { display:'flex', gap:4, marginBottom:22, background:'var(--bg)',
              borderRadius:14, padding:4 },
      tab: (a) => ({ flex:1, padding:'10px 0', borderRadius:11, border:'none',
        background: a ? 'var(--bg-card)' : 'transparent',
        color: a ? 'var(--primary)' : 'var(--text-2)',
        fontSize:15, fontWeight:700, cursor:'pointer', fontFamily:'Nunito,sans-serif',
        boxShadow: a ? '0 1px 6px var(--shadow)' : 'none', transition:'all .2s' }),
      field: { marginBottom:14 },
      label: { fontSize:11, fontWeight:700, color:'var(--text-2)', letterSpacing:'0.5px',
               textTransform:'uppercase', marginBottom:6, display:'block' },
      input: { width:'100%', padding:'13px 15px', borderRadius:13,
               border:'2px solid var(--border)', background:'var(--bg)', color:'var(--text)',
               fontSize:16, fontFamily:'Nunito,sans-serif', outline:'none',
               boxSizing:'border-box', transition:'border-color .2s' },
      errTxt: { fontSize:13, color:'#E05070', fontWeight:700, marginBottom:10, marginTop:-6 },
      btnPrimary: { width:'100%', padding:'15px 0', borderRadius:15, border:'none',
                   background:'var(--primary)', color:'#fff', fontSize:17, fontWeight:800,
                   cursor:'pointer', fontFamily:'Nunito,sans-serif', display:'block',
                   marginTop:6, marginBottom:10, boxShadow:'0 4px 16px var(--shadow)',
                   transition:'transform .15s' },
      btnGuest: { width:'100%', padding:'13px 0', borderRadius:15,
                  border:'2px solid var(--border)', background:'transparent',
                  color:'var(--text-2)', fontSize:14, fontWeight:700,
                  cursor:'pointer', fontFamily:'Nunito,sans-serif', display:'block' },
      consentRow: { display:'flex', alignItems:'flex-start', gap:10, margin:'2px 0 14px', cursor:'pointer' },
      checkbox: (a) => ({ flexShrink:0, width:22, height:22, borderRadius:7, border:'2px solid',
        borderColor: a ? 'var(--primary)' : 'var(--border)', background: a ? 'var(--primary)' : 'transparent',
        color:'#fff', fontSize:14, fontWeight:900, display:'flex', alignItems:'center', justifyContent:'center', transition:'all .2s' }),
      consentTxt: { fontSize:13, color:'var(--text-2)', lineHeight:1.5 },
      consentLink: { color:'var(--primary)', fontWeight:700, textDecoration:'underline', cursor:'pointer' },
      docOverlay: { position:'fixed', inset:0, background:'rgba(0,0,0,0.45)', zIndex:300, display:'flex',
        alignItems:'flex-end', backdropFilter:'blur(4px)' },
      docSheet: { width:'100%', maxWidth:520, margin:'0 auto', background:'var(--bg-card)', borderRadius:'24px 24px 0 0',
        padding:'20px 24px', paddingBottom:'calc(28px + env(safe-area-inset-bottom))', maxHeight:'86vh',
        display:'flex', flexDirection:'column', gap:14, boxShadow:'0 -4px 24px rgba(0,0,0,0.15)' },
      docHandle: { width:40, height:4, borderRadius:2, background:'var(--border)', margin:'0 auto' },
      docTitle: { fontSize:17, fontWeight:800, color:'var(--text)' },
      docBody: { overflowY:'auto', whiteSpace:'pre-wrap', fontSize:14, lineHeight:1.65, color:'var(--text)' },
      docClose: { marginTop:4, padding:'13px 0', borderRadius:14, border:'none', background:'var(--primary)', color:'#fff',
        fontSize:15, fontWeight:800, cursor:'pointer', fontFamily:'Nunito,sans-serif' },
    };

    const docDef = docView && window.AliaLegal
      ? window.AliaLegal.docs.find(d => d.id === docView) : null;

    return (
      <div style={s.wrap}>
        {docDef && (
          <div style={s.docOverlay} onClick={() => setDocView(null)}>
            <div style={s.docSheet} onClick={e => e.stopPropagation()}>
              <span style={s.docHandle}></span>
              <div style={s.docTitle}>{docDef.icon + ' ' + docDef.title[lang]}</div>
              <div style={s.docBody}>{docDef.body[lang]}</div>
              <button style={s.docClose} onClick={() => setDocView(null)}>{lang === 'ru' ? 'Закрыть' : 'Close'}</button>
            </div>
          </div>
        )}
        <div style={s.topBar}>
          <button style={s.langBtn}
            onClick={() => setLang(lg => lg === 'ru' ? 'en' : 'ru')}>
            {lang === 'ru' ? 'EN' : 'RU'}
          </button>
        </div>

        <div style={s.inner}>
          <div style={s.logo}>🌸</div>
          <div style={s.appName}>Alia</div>
          <div style={s.tagline}>{l.tagline}</div>

          <div style={s.card}>
            {/* Login / Register tabs */}
            <div style={s.tabs}>
              <button style={s.tab(mode==='login')}
                onClick={() => { setMode('login'); setError(''); }}>
                {l.login}
              </button>
              <button style={s.tab(mode==='register')}
                onClick={() => { setMode('register'); setError(''); }}>
                {l.register}
              </button>
            </div>

            {mode === 'register' && (
              <div style={s.field}>
                <label style={s.label}>{l.nameLabel}</label>
                <input style={s.input} type="text" value={name}
                  placeholder={lang === 'ru' ? 'Анна' : 'Anna'}
                  onChange={e => { setName(e.target.value); setError(''); }} />
              </div>
            )}

            <div style={s.field}>
              <label style={s.label}>{l.emailLabel}</label>
              <input style={s.input} type="email" value={email}
                placeholder="example@mail.com"
                onChange={e => { setEmail(e.target.value); setError(''); }} />
            </div>

            <div style={s.field}>
              <label style={s.label}>{l.pwLabel}</label>
              <input style={s.input} type="password" value={password}
                placeholder="••••••••"
                onChange={e => { setPassword(e.target.value); setError(''); }} />
            </div>

            {mode === 'register' && (
              <div style={s.field}>
                <label style={s.label}>{l.confirmLabel}</label>
                <input style={s.input} type="password" value={confirmPw}
                  placeholder="••••••••"
                  onChange={e => { setConfirmPw(e.target.value); setError(''); }} />
              </div>
            )}

            {mode === 'register' && (
              <div style={s.consentRow} onClick={() => { setAccepted(a => !a); setError(''); }}>
                <span style={s.checkbox(accepted)}>{accepted ? '✓' : ''}</span>
                <span style={s.consentTxt}>
                  {l.consentPre}
                  {(window.AliaLegal ? window.AliaLegal.docs : []).map((d, i, arr) => (
                    <React.Fragment key={d.id}>
                      <span style={s.consentLink}
                        onClick={e => { e.stopPropagation(); setDocView(d.id); }}>{d.title[lang]}</span>
                      {i < arr.length - 1 ? (lang === 'ru' ? (i === arr.length - 2 ? ' и ' : ', ') : (i === arr.length - 2 ? ' and ' : ', ')) : ''}
                    </React.Fragment>
                  ))}
                </span>
              </div>
            )}

            {error && <div style={s.errTxt}>{error}</div>}

            <button style={{ ...s.btnPrimary, opacity: loading ? 0.7 : 1 }}
              onClick={handleSubmit} disabled={loading}
              onMouseDown={e => e.currentTarget.style.transform='scale(0.97)'}
              onMouseUp={e => e.currentTarget.style.transform=''}>
              {loading ? '...' : (mode === 'login' ? l.btnLogin : l.btnReg)}
            </button>
          </div>
        </div>
      </div>
    );
  }

  Object.assign(window, { AuthScreen });
})();
