// Loij Flow — Authentication
// ── Tài khoản mặc định — thêm/xóa tại đây ───────────────────────────────────
const _AUTH_ACCOUNTS = [
  { user: 'admin',    pass: 'admin2026' },
  { user: 'huyduong', pass: 'admin2026' },
];
// ─────────────────────────────────────────────────────────────────────────────

const _AUTH_KEY     = 'loij_session';
const _AUTH_REG_KEY = 'loij_accounts';
const _AUTH_TTL     = 3 * 24 * 60 * 60 * 1000; // 3 ngày

// ── Storage helpers ───────────────────────────────────────────────────────────

function _authGetRegistered() {
  try { return JSON.parse(localStorage.getItem(_AUTH_REG_KEY)) || []; }
  catch { return []; }
}

function _authCheck(username, password) {
  const all = [..._AUTH_ACCOUNTS, ..._authGetRegistered()];
  return all.some(a => a.user === username.trim() && a.pass === password.trim());
}

function _authRegister(user, pass, email) {
  const registered = _authGetRegistered();
  const all = [..._AUTH_ACCOUNTS, ...registered];
  if (all.some(a => a.user === user))
    return { field: 'user', msg: 'Tên đăng nhập đã tồn tại.' };
  if (registered.some(a => a.email && a.email.toLowerCase() === email.toLowerCase()))
    return { field: 'email', msg: 'Email này đã được sử dụng.' };
  registered.push({ user, pass, email: email.toLowerCase(), createdAt: Date.now() });
  localStorage.setItem(_AUTH_REG_KEY, JSON.stringify(registered));
  return null;
}

function _authSave(username) {
  localStorage.setItem(_AUTH_KEY, JSON.stringify({ user: username, exp: Date.now() + _AUTH_TTL }));
}

function _authClear() { localStorage.removeItem(_AUTH_KEY); }

function _authGet() {
  try {
    const s = JSON.parse(localStorage.getItem(_AUTH_KEY));
    if (!s || !s.exp || Date.now() > s.exp) { _authClear(); return null; }
    return s;
  } catch { return null; }
}

// ── Shared UI pieces ──────────────────────────────────────────────────────────

const _inputBase = (focused, hasError) => ({
  width: '100%', boxSizing: 'border-box',
  height: 44, padding: '0 14px 0 40px',
  background: 'var(--bg-elevated)',
  border: `1.5px solid ${hasError ? 'var(--error)' : focused ? 'var(--accent-cyan)' : 'var(--border)'}`,
  borderRadius: 10, fontSize: 13.5, color: 'var(--fg-primary)',
  fontFamily: 'var(--font-body)', outline: 'none', transition: 'border-color 0.15s',
});

const _Label = ({ children }) => (
  <label style={{
    display: 'block', fontSize: 11, fontWeight: 700, color: 'var(--fg-secondary)',
    marginBottom: 6, letterSpacing: '0.06em', textTransform: 'uppercase',
  }}>{children}</label>
);

const _FieldError = ({ msg }) => msg ? (
  <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 5, fontSize: 11.5, color: 'var(--error)' }}>
    <Icon name="alert-circle" size={11} color="var(--error)" />
    {msg}
  </div>
) : null;

const _Brand = () => (
  <div style={{ textAlign: 'center', marginBottom: 26 }}>
    <div style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      width: 54, height: 54, borderRadius: 15,
      background: 'linear-gradient(135deg,#7B4FD4,#2E9DF7)',
      marginBottom: 14, boxShadow: '0 8px 24px rgba(123,79,212,0.33)',
    }}>
      <svg width="27" height="27" viewBox="0 0 24 24" fill="none"
        stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/>
      </svg>
    </div>
    <div style={{ fontFamily:'var(--font-display)', fontSize:22, fontWeight:800,
      color:'var(--fg-primary)', letterSpacing:'-0.03em', marginBottom:4 }}>
      Loij Flow
    </div>
    <div style={{ fontSize:12, color:'var(--fg-muted)' }}>Meta Ads Pipeline · AI Intelligence</div>
  </div>
);

const _Glows = () => (
  <React.Fragment>
    <div style={{ position:'fixed', width:700, height:700, borderRadius:'50%', pointerEvents:'none',
      background:'radial-gradient(circle,rgba(123,79,212,0.10) 0%,transparent 65%)',
      top:'-180px', right:'-180px' }} />
    <div style={{ position:'fixed', width:500, height:500, borderRadius:'50%', pointerEvents:'none',
      background:'radial-gradient(circle,rgba(46,157,247,0.07) 0%,transparent 65%)',
      bottom:'-120px', left:'-120px' }} />
  </React.Fragment>
);

const _pageWrap = {
  minHeight:'100vh', width:'100%',
  display:'flex', alignItems:'center', justifyContent:'center',
  background:'var(--bg-base)', fontFamily:'var(--font-body)',
  position:'relative', overflow:'hidden',
};

const _card = (maxWidth = 400) => ({
  width:'100%', maxWidth,
  padding:'36px 34px 28px',
  background:'var(--bg-surface)', border:'1px solid var(--border)',
  borderRadius:20, boxShadow:'0 32px 80px rgba(0,0,0,0.45)',
  position:'relative', zIndex:1, margin:'0 16px',
});

// ── Login screen ──────────────────────────────────────────────────────────────

const LoginScreen = ({ onLogin, onSwitchToRegister }) => {
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError]       = React.useState('');
  const [showPass, setShowPass] = React.useState(false);
  const [loading, setLoading]   = React.useState(false);
  const [focusU, setFocusU]     = React.useState(false);
  const [focusP, setFocusP]     = React.useState(false);

  const submit = async () => {
    if (!username.trim() || !password.trim()) { setError('Vui lòng nhập đầy đủ thông tin.'); return; }
    setLoading(true); setError('');
    await new Promise(r => setTimeout(r, 550));
    if (_authCheck(username, password)) {
      _authSave(username.trim()); onLogin(username.trim());
    } else {
      setError('Tên đăng nhập hoặc mật khẩu không đúng.');
      setLoading(false);
    }
  };

  return (
    <div style={_pageWrap}>
      <_Glows />
      <div style={_card(400)}>
        <_Brand />
        <div style={{ height:1, background:'var(--border)', marginBottom:22 }} />
        <div style={{ fontSize:16, fontWeight:700, color:'var(--fg-primary)',
          fontFamily:'var(--font-display)', marginBottom:18, letterSpacing:'-0.01em' }}>
          Đăng nhập
        </div>

        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          {/* Username */}
          <div>
            <_Label>Tên đăng nhập</_Label>
            <div style={{ position:'relative' }}>
              <span style={{ position:'absolute', left:12, top:'50%', transform:'translateY(-50%)',
                display:'flex', alignItems:'center', pointerEvents:'none', opacity:0.55 }}>
                <Icon name="user" size={15} color="var(--fg-secondary)" />
              </span>
              <input type="text" value={username} autoComplete="username" placeholder="Nhập username"
                onChange={e => { setUsername(e.target.value); setError(''); }}
                onKeyDown={e => e.key==='Enter' && submit()}
                onFocus={() => setFocusU(true)} onBlur={() => setFocusU(false)}
                style={_inputBase(focusU, !!error)}
              />
            </div>
          </div>

          {/* Password */}
          <div>
            <_Label>Mật khẩu</_Label>
            <div style={{ position:'relative' }}>
              <span style={{ position:'absolute', left:12, top:'50%', transform:'translateY(-50%)',
                display:'flex', alignItems:'center', pointerEvents:'none', opacity:0.55 }}>
                <Icon name="lock" size={15} color="var(--fg-secondary)" />
              </span>
              <input type={showPass ? 'text' : 'password'} value={password}
                autoComplete="current-password" placeholder="••••••••"
                onChange={e => { setPassword(e.target.value); setError(''); }}
                onKeyDown={e => e.key==='Enter' && submit()}
                onFocus={() => setFocusP(true)} onBlur={() => setFocusP(false)}
                style={{ ..._inputBase(focusP, !!error), paddingRight:44 }}
              />
              <button type="button" onClick={() => setShowPass(v => !v)}
                style={{ position:'absolute', right:10, top:'50%', transform:'translateY(-50%)',
                  background:'none', border:'none', cursor:'pointer',
                  display:'flex', alignItems:'center', padding:5, color:'var(--fg-muted)' }}>
                <Icon name={showPass ? 'eye-off' : 'eye'} size={15} />
              </button>
            </div>
          </div>

          {error && (
            <div style={{ display:'flex', alignItems:'center', gap:7, padding:'9px 12px',
              borderRadius:9, background:'rgba(248,113,113,0.08)',
              border:'1px solid rgba(248,113,113,0.28)', fontSize:12.5, color:'var(--error)' }}>
              <Icon name="alert-circle" size={13} color="var(--error)" />
              {error}
            </div>
          )}

          <button onClick={submit} disabled={loading}
            style={{ height:46, borderRadius:11, marginTop:2,
              background: loading ? 'var(--bg-elevated)' : 'linear-gradient(135deg,#7B4FD4,#2E9DF7)',
              color: loading ? 'var(--fg-muted)' : '#fff',
              border:'none', cursor: loading ? 'not-allowed' : 'pointer',
              fontFamily:'var(--font-body)', fontWeight:700, fontSize:14,
              display:'flex', alignItems:'center', justifyContent:'center', gap:8,
              transition:'all 0.15s', boxShadow: loading ? 'none' : '0 6px 20px rgba(123,79,212,0.28)',
            }}>
            {loading
              ? <React.Fragment><Icon name="loader" size={16} />Đang xác thực…</React.Fragment>
              : <React.Fragment><Icon name="log-in" size={16} />Đăng nhập</React.Fragment>}
          </button>
        </div>

        <div style={{ marginTop:22, textAlign:'center', fontSize:12.5, color:'var(--fg-muted)' }}>
          Chưa có tài khoản?{' '}
          <button onClick={onSwitchToRegister}
            style={{ background:'none', border:'none', cursor:'pointer', padding:0,
              fontSize:12.5, color:'var(--accent-cyan)', fontWeight:600, fontFamily:'var(--font-body)' }}>
            Đăng ký ngay
          </button>
        </div>
        <div style={{ marginTop:8, textAlign:'center', fontSize:11, color:'var(--fg-muted)', opacity:0.55 }}>
          Session duy trì <strong>3 ngày</strong>
        </div>
      </div>
    </div>
  );
};

// ── Register screen ───────────────────────────────────────────────────────────

const RegisterScreen = ({ onSwitchToLogin, onRegisterSuccess }) => {
  const [form, setForm]           = React.useState({ user:'', email:'', pass:'', confirm:'' });
  const [errors, setErrors]       = React.useState({});
  const [showPass, setShowPass]   = React.useState(false);
  const [showCfm, setShowCfm]     = React.useState(false);
  const [loading, setLoading]     = React.useState(false);
  const [focus, setFocus]         = React.useState({});

  const set = (k, v) => { setForm(f => ({ ...f, [k]: v })); setErrors(e => ({ ...e, [k]: '' })); };

  const validate = () => {
    const e = {};
    const u = form.user.trim();
    if (!u)                                    e.user    = 'Vui lòng nhập tên đăng nhập.';
    else if (u.length < 3)                     e.user    = 'Tối thiểu 3 ký tự.';
    else if (!/^[a-zA-Z0-9_]+$/.test(u))       e.user    = 'Chỉ dùng chữ, số, dấu gạch dưới (_).';

    const em = form.email.trim();
    if (!em)                                   e.email   = 'Vui lòng nhập Gmail.';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(em)) e.email = 'Email không hợp lệ.';

    if (!form.pass)                            e.pass    = 'Vui lòng nhập mật khẩu.';
    else if (form.pass.length < 6)             e.pass    = 'Mật khẩu tối thiểu 6 ký tự.';

    if (!form.confirm)                         e.confirm = 'Vui lòng xác nhận mật khẩu.';
    else if (form.pass !== form.confirm)       e.confirm = 'Mật khẩu xác nhận không khớp.';
    return e;
  };

  const [success, setSuccess] = React.useState('');

  const submit = async () => {
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    setLoading(true);
    await new Promise(r => setTimeout(r, 550));
    const err = _authRegister(form.user.trim(), form.pass, form.email.trim());
    if (err) { setErrors({ [err.field]: err.msg }); setLoading(false); return; }
    setSuccess(form.user.trim());
    setLoading(false);
    await new Promise(r => setTimeout(r, 1600));
    onSwitchToLogin();
  };

  const onFocus = k => setFocus(f => ({ ...f, [k]: true }));
  const onBlur  = k => setFocus(f => ({ ...f, [k]: false }));

  return (
    <div style={_pageWrap}>
      <_Glows />
      <div style={_card(440)}>
        <_Brand />
        <div style={{ height:1, background:'var(--border)', marginBottom:20 }} />
        <div style={{ fontSize:16, fontWeight:700, color:'var(--fg-primary)',
          fontFamily:'var(--font-display)', marginBottom:18, letterSpacing:'-0.01em' }}>
          Tạo tài khoản mới
        </div>

        <div style={{ display:'flex', flexDirection:'column', gap:13 }}>

          {/* Tên đăng nhập */}
          <div>
            <_Label>Tên đăng nhập</_Label>
            <div style={{ position:'relative' }}>
              <span style={{ position:'absolute', left:12, top:'50%', transform:'translateY(-50%)',
                display:'flex', alignItems:'center', pointerEvents:'none', opacity:0.55 }}>
                <Icon name="user" size={15} color="var(--fg-secondary)" />
              </span>
              <input type="text" value={form.user} autoComplete="username"
                placeholder="vd: nguyen_van_a"
                onChange={e => set('user', e.target.value)}
                onKeyDown={e => e.key==='Enter' && submit()}
                onFocus={() => onFocus('user')} onBlur={() => onBlur('user')}
                style={_inputBase(focus.user, !!errors.user)}
              />
            </div>
            <_FieldError msg={errors.user} />
          </div>

          {/* Gmail */}
          <div>
            <_Label>Gmail</_Label>
            <div style={{ position:'relative' }}>
              <span style={{ position:'absolute', left:12, top:'50%', transform:'translateY(-50%)',
                display:'flex', alignItems:'center', pointerEvents:'none', opacity:0.55 }}>
                <Icon name="mail" size={15} color="var(--fg-secondary)" />
              </span>
              <input type="email" value={form.email} autoComplete="email"
                placeholder="example@gmail.com"
                onChange={e => set('email', e.target.value)}
                onKeyDown={e => e.key==='Enter' && submit()}
                onFocus={() => onFocus('email')} onBlur={() => onBlur('email')}
                style={_inputBase(focus.email, !!errors.email)}
              />
            </div>
            <_FieldError msg={errors.email} />
          </div>

          {/* Mật khẩu */}
          <div>
            <_Label>Mật khẩu</_Label>
            <div style={{ position:'relative' }}>
              <span style={{ position:'absolute', left:12, top:'50%', transform:'translateY(-50%)',
                display:'flex', alignItems:'center', pointerEvents:'none', opacity:0.55 }}>
                <Icon name="lock" size={15} color="var(--fg-secondary)" />
              </span>
              <input type={showPass ? 'text' : 'password'} value={form.pass}
                autoComplete="new-password" placeholder="Tối thiểu 6 ký tự"
                onChange={e => set('pass', e.target.value)}
                onKeyDown={e => e.key==='Enter' && submit()}
                onFocus={() => onFocus('pass')} onBlur={() => onBlur('pass')}
                style={{ ..._inputBase(focus.pass, !!errors.pass), paddingRight:44 }}
              />
              <button type="button" onClick={() => setShowPass(v => !v)}
                style={{ position:'absolute', right:10, top:'50%', transform:'translateY(-50%)',
                  background:'none', border:'none', cursor:'pointer',
                  display:'flex', alignItems:'center', padding:5, color:'var(--fg-muted)' }}>
                <Icon name={showPass ? 'eye-off' : 'eye'} size={15} />
              </button>
            </div>
            <_FieldError msg={errors.pass} />
          </div>

          {/* Xác nhận mật khẩu */}
          <div>
            <_Label>Xác nhận mật khẩu</_Label>
            <div style={{ position:'relative' }}>
              <span style={{ position:'absolute', left:12, top:'50%', transform:'translateY(-50%)',
                display:'flex', alignItems:'center', pointerEvents:'none', opacity:0.55 }}>
                <Icon name="shield-check" size={15} color="var(--fg-secondary)" />
              </span>
              <input type={showCfm ? 'text' : 'password'} value={form.confirm}
                autoComplete="new-password" placeholder="Nhập lại mật khẩu"
                onChange={e => set('confirm', e.target.value)}
                onKeyDown={e => e.key==='Enter' && submit()}
                onFocus={() => onFocus('confirm')} onBlur={() => onBlur('confirm')}
                style={{ ..._inputBase(focus.confirm, !!errors.confirm), paddingRight:44 }}
              />
              <button type="button" onClick={() => setShowCfm(v => !v)}
                style={{ position:'absolute', right:10, top:'50%', transform:'translateY(-50%)',
                  background:'none', border:'none', cursor:'pointer',
                  display:'flex', alignItems:'center', padding:5, color:'var(--fg-muted)' }}>
                <Icon name={showCfm ? 'eye-off' : 'eye'} size={15} />
              </button>
            </div>
            <_FieldError msg={errors.confirm} />
          </div>

          {success ? (
            <div style={{
              padding:'18px 16px', borderRadius:12, textAlign:'center',
              background:'rgba(74,222,128,0.08)', border:'1px solid rgba(74,222,128,0.28)',
              display:'flex', flexDirection:'column', alignItems:'center', gap:10,
            }}>
              <div style={{
                width:44, height:44, borderRadius:12,
                background:'rgba(74,222,128,0.15)',
                display:'flex', alignItems:'center', justifyContent:'center',
              }}>
                <Icon name="check-circle" size={22} color="#4ADE80" />
              </div>
              <div style={{ fontSize:14, fontWeight:700, color:'var(--fg-primary)' }}>
                Tạo tài khoản thành công!
              </div>
              <div style={{ fontSize:12.5, color:'var(--fg-secondary)', lineHeight:1.6 }}>
                Tài khoản <strong style={{ color:'var(--accent-cyan)' }}>{success}</strong> đã được tạo.
                <br />Đang chuyển sang trang đăng nhập…
              </div>
              <div style={{ display:'flex', gap:5 }}>
                {[0,1,2].map(i => (
                  <div key={i} style={{
                    width:6, height:6, borderRadius:'50%',
                    background: '#4ADE80', opacity: 0.4 + i * 0.3,
                    animation: 'none',
                  }} />
                ))}
              </div>
            </div>
          ) : (
            <button onClick={submit} disabled={loading}
              style={{ height:46, borderRadius:11, marginTop:4,
                background: loading ? 'var(--bg-elevated)' : 'linear-gradient(135deg,#7B4FD4,#2E9DF7)',
                color: loading ? 'var(--fg-muted)' : '#fff',
                border:'none', cursor: loading ? 'not-allowed' : 'pointer',
                fontFamily:'var(--font-body)', fontWeight:700, fontSize:14,
                display:'flex', alignItems:'center', justifyContent:'center', gap:8,
                transition:'all 0.15s', boxShadow: loading ? 'none' : '0 6px 20px rgba(123,79,212,0.28)',
              }}>
              {loading
                ? <React.Fragment><Icon name="loader" size={16} />Đang tạo tài khoản…</React.Fragment>
                : <React.Fragment><Icon name="user-plus" size={16} />Tạo tài khoản</React.Fragment>}
            </button>
          )}
        </div>

        <div style={{ marginTop:20, textAlign:'center', fontSize:12.5, color:'var(--fg-muted)' }}>
          Đã có tài khoản?{' '}
          <button onClick={onSwitchToLogin}
            style={{ background:'none', border:'none', cursor:'pointer', padding:0,
              fontSize:12.5, color:'var(--accent-cyan)', fontWeight:600, fontFamily:'var(--font-body)' }}>
            Đăng nhập
          </button>
        </div>

        <div style={{ marginTop:12, padding:'9px 12px', borderRadius:8,
          background:'rgba(102,252,241,0.04)', border:'1px solid rgba(102,252,241,0.10)',
          display:'flex', alignItems:'flex-start', gap:7,
          fontSize:11.5, color:'var(--fg-muted)', lineHeight:1.65 }}>
          <Icon name="info" size={12} color="var(--accent-cyan)" />
          <span>Tài khoản được lưu trong trình duyệt này. Session duy trì <strong style={{ color:'var(--fg-secondary)' }}>3 ngày</strong>.</span>
        </div>
      </div>
    </div>
  );
};

// ── Auth gate — quản lý login ↔ register ─────────────────────────────────────

const AuthGate = ({ onLogin }) => {
  const [view, setView] = React.useState('login');
  return view === 'login'
    ? <LoginScreen onLogin={onLogin} onSwitchToRegister={() => setView('register')} />
    : <RegisterScreen onSwitchToLogin={() => setView('login')} />;
};

Object.assign(window, { AuthGate, _authGet, _authClear });
