// AUTH PAGE — mobile ready
function AuthPage({ lang, onLogin, setPage }) {
  const [mode, setMode] = React.useState('login');
  const [form, setForm] = React.useState({ name: '', email: '', password: '', confirm: '' });
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const t = lang === 'pt' ? {
    loginTitle: 'Bem-vindo de volta', registerTitle: 'Criar Conta',
    name: 'Nome completo', email: 'Email', password: 'Password', confirm: 'Confirmar Password',
    login: 'Entrar', register: 'Registar',
    errEmail: 'Email já registado.', errPass: 'Passwords não coincidem.',
    errFields: 'Preencha todos os campos.', errLogin: 'Email ou password incorretos.',
    adminHint: 'Admin: admin@dompapanca.pt / admin123'
  } : {
    loginTitle: 'Welcome back', registerTitle: 'Create Account',
    name: 'Full name', email: 'Email', password: 'Password', confirm: 'Confirm Password',
    login: 'Sign In', register: 'Register',
    errEmail: 'Email already registered.', errPass: 'Passwords do not match.',
    errFields: 'Please fill in all fields.', errLogin: 'Incorrect email or password.',
    adminHint: 'Admin: admin@dompapanca.pt / admin123'
  };

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

  const handleSubmit = (e) => {
    e.preventDefault();
    setLoading(true);
    setTimeout(() => {
      const users = Store.getUsers();
      if (mode === 'login') {
        const user = users.find(u => u.email === form.email && u.password === form.password);
        if (!user) { setError(t.errLogin); setLoading(false); return; }
        onLogin(user);
        setPage(user.role === 'admin' ? 'admin' : 'account');
      } else {
        if (!form.name || !form.email || !form.password) { setError(t.errFields); setLoading(false); return; }
        if (form.password !== form.confirm) { setError(t.errPass); setLoading(false); return; }
        if (users.find(u => u.email === form.email)) { setError(t.errEmail); setLoading(false); return; }
        const newUser = { id: Store.nextId(users), name: form.name, email: form.email, password: form.password, role: 'user', createdAt: new Date().toISOString().split('T')[0] };
        Store.saveUsers([...users, newUser]);
        onLogin(newUser);
        setPage('account');
      }
      setLoading(false);
    }, 600);
  };

  const lbl = { display: 'block', fontFamily: 'Lato, sans-serif', color: 'var(--muted)', fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', marginBottom: 6 };

  return (
    <div style={{ minHeight: '100vh', background: 'radial-gradient(ellipse at 50% 30%, #3d2210 0%, var(--bg) 65%)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'clamp(90px,10vw,120px) 16px 40px' }}>
      <div style={{ width: '100%', maxWidth: 420 }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <Logo size={68} />
          <div style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 20, marginTop: 10 }}>Dom Papança</div>
        </div>

        <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 12, padding: 'clamp(24px,5vw,36px)' }}>
          {/* Tab switcher */}
          <div style={{ display: 'flex', gap: 0, marginBottom: 24, background: 'rgba(0,0,0,0.25)', borderRadius: 6, padding: 4 }}>
            {[['login', t.login], ['register', t.register]].map(([k, v]) => (
              <button key={k} onClick={() => { setMode(k); setError(''); }}
                style={{ flex: 1, padding: '9px', borderRadius: 4, border: 'none', background: mode === k ? 'rgba(212,153,58,0.2)' : 'transparent', color: mode === k ? 'var(--gold)' : 'var(--muted)', fontFamily: 'Lato, sans-serif', fontSize: 13, fontWeight: mode === k ? 700 : 400, letterSpacing: 1, textTransform: 'uppercase', cursor: 'pointer', transition: 'all 0.2s', minHeight: 42 }}>
                {v}
              </button>
            ))}
          </div>

          <h2 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 21, margin: '0 0 22px', textAlign: 'center' }}>
            {mode === 'login' ? t.loginTitle : t.registerTitle}
          </h2>

          <form onSubmit={handleSubmit}>
            {mode === 'register' && (
              <div style={{ marginBottom: 14 }}>
                <label style={lbl}>{t.name}</label>
                <input value={form.name} onChange={e => set('name', e.target.value)} autoComplete="name" />
              </div>
            )}
            <div style={{ marginBottom: 14 }}>
              <label style={lbl}>{t.email}</label>
              <input type="email" value={form.email} onChange={e => set('email', e.target.value)} autoComplete="email" inputMode="email" />
            </div>
            <div style={{ marginBottom: 14 }}>
              <label style={lbl}>{t.password}</label>
              <input type="password" value={form.password} onChange={e => set('password', e.target.value)} autoComplete={mode==='login'?'current-password':'new-password'} />
            </div>
            {mode === 'register' && (
              <div style={{ marginBottom: 14 }}>
                <label style={lbl}>{t.confirm}</label>
                <input type="password" value={form.confirm} onChange={e => set('confirm', e.target.value)} autoComplete="new-password" />
              </div>
            )}
            {error && (
              <div style={{ background: 'rgba(200,40,40,0.12)', border: '1px solid rgba(200,40,40,0.35)', borderRadius: 5, padding: '10px 14px', marginBottom: 14, fontFamily: 'Lato, sans-serif', color: '#e08080', fontSize: 13 }}>{error}</div>
            )}
            <div style={{ marginTop: 6 }}>
              <BtnPrimary type="submit" full disabled={loading}>
                {loading ? '...' : (mode === 'login' ? t.login : t.register)}
              </BtnPrimary>
            </div>
          </form>

          <div style={{ marginTop: 18, padding: '10px 14px', background: 'rgba(212,153,58,0.06)', border: '1px solid rgba(212,153,58,0.12)', borderRadius: 5, fontFamily: 'Lato, sans-serif', fontSize: 11, color: 'var(--dim)', textAlign: 'center' }}>
            {t.adminHint}
          </div>
        </div>
      </div>
    </div>
  );
}

// ACCOUNT PAGE — mobile ready
function AccountPage({ lang, session, setPage }) {
  const [tab, setTab] = React.useState('orders');
  const orders = Store.getOrders().filter(o => o.userId === session.id).reverse();

  const t = lang === 'pt' ? {
    title: 'A Minha Conta', orders: 'Encomendas', profile: 'Perfil',
    noOrders: 'Ainda não tem encomendas.', shopNow: 'Ir às Compras',
    statuses: { pending: 'Pendente', processing: 'Em Preparação', delivered: 'Entregue', cancelled: 'Cancelado' },
  } : {
    title: 'My Account', orders: 'Orders', profile: 'Profile',
    noOrders: 'You have no orders yet.', shopNow: 'Go Shopping',
    statuses: { pending: 'Pending', processing: 'Processing', delivered: 'Delivered', cancelled: 'Cancelled' },
  };

  const statusColors = { pending: '#d4993a', processing: '#4a90d9', delivered: '#4a9a30', cancelled: '#c84040' };

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)', paddingTop: 70 }}>
      <div style={{ maxWidth: 900, margin: '0 auto', padding: 'clamp(24px,5vw,50px) clamp(16px,4vw,40px)' }}>

        {/* Header */}
        <div className="account-header" style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 36 }}>
          <div style={{ width: 52, height: 52, borderRadius: '50%', background: 'rgba(212,153,58,0.18)', border: '2px solid rgba(212,153,58,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: "'Playfair Display', serif", color: 'var(--gold)', fontSize: 22, flexShrink: 0 }}>
            {session.name.charAt(0)}
          </div>
          <div>
            <h2 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 'clamp(18px,4vw,24px)', margin: '0 0 3px' }}>{session.name}</h2>
            <div style={{ fontFamily: 'Lato, sans-serif', color: 'var(--muted)', fontSize: 13 }}>{session.email}</div>
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', gap: 0, marginBottom: 28, borderBottom: '1px solid var(--border)' }}>
          {[['orders', t.orders], ['profile', t.profile]].map(([k, v]) => (
            <button key={k} onClick={() => setTab(k)}
              style={{ background: 'none', border: 'none', borderBottom: `2px solid ${tab===k?'var(--gold)':'transparent'}`, color: tab===k?'var(--gold)':'var(--muted)', fontFamily: 'Lato, sans-serif', fontSize: 13, letterSpacing: 1, textTransform: 'uppercase', padding: '10px 20px', cursor: 'pointer', marginBottom: -1, transition: 'all 0.2s', fontWeight: tab===k?700:400, minHeight: 44 }}>
              {v}
            </button>
          ))}
        </div>

        {tab === 'orders' && (
          orders.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '56px 0' }}>
              <div style={{ fontSize: 48, marginBottom: 14 }}>📦</div>
              <p style={{ fontFamily: 'Lato, sans-serif', color: 'var(--muted)', marginBottom: 20 }}>{t.noOrders}</p>
              <BtnPrimary onClick={() => setPage('shop')}>{t.shopNow}</BtnPrimary>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {orders.map(order => (
                <div key={order.id} style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, padding: 'clamp(16px,3vw,22px)' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12, flexWrap: 'wrap', gap: 8 }}>
                    <div>
                      <span style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 15 }}>
                        {lang==='pt'?'Encomenda':'Order'} #{order.id}
                      </span>
                      <span style={{ fontFamily: 'Lato, sans-serif', color: 'var(--dim)', fontSize: 12, marginLeft: 10 }}>
                        {new Date(order.createdAt).toLocaleDateString(lang==='pt'?'pt-PT':'en-GB')}
                      </span>
                    </div>
                    <span style={{ background: `${statusColors[order.status]}22`, border: `1px solid ${statusColors[order.status]}55`, color: statusColors[order.status], fontFamily: 'Lato, sans-serif', fontSize: 10, letterSpacing: 1.5, textTransform: 'uppercase', padding: '4px 10px', borderRadius: 4 }}>
                      {t.statuses[order.status]}
                    </span>
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 12 }}>
                    {order.items.map(item => (
                      <span key={item.id} style={{ background: 'rgba(212,153,58,0.08)', border: '1px solid var(--border)', borderRadius: 4, padding: '3px 9px', fontFamily: 'Lato, sans-serif', color: 'var(--muted)', fontSize: 12 }}>
                        {item.name} ×{item.qty}
                      </span>
                    ))}
                  </div>
                  <div style={{ textAlign: 'right', fontFamily: "'Playfair Display', serif", color: 'var(--gold)', fontSize: 17 }}>
                    Total: {order.total.toFixed(2)}€
                  </div>
                </div>
              ))}
            </div>
          )
        )}

        {tab === 'profile' && (
          <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, padding: 'clamp(20px,4vw,28px)', maxWidth: 400 }}>
            {[
              [lang==='pt'?'Nome':'Name', session.name],
              ['Email', session.email],
              [lang==='pt'?'Membro desde':'Member since', session.createdAt],
              ['Role', session.role]
            ].map(([k, v]) => (
              <div key={k} style={{ marginBottom: 18 }}>
                <div style={{ fontFamily: 'Lato, sans-serif', color: 'var(--dim)', fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', marginBottom: 3 }}>{k}</div>
                <div style={{ fontFamily: 'Lato, sans-serif', color: 'var(--cream)', fontSize: 15 }}>{v}</div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AuthPage, AccountPage });
