// ADMIN PANEL — mobile ready
function AdminPage({ lang, session, setPage, showToast }) {
  const [tab, setTab] = React.useState('stats');
  const [products, setProducts] = React.useState(Store.getProducts());
  const [categories, setCategories] = React.useState(Store.getCategories());
  const [orders, setOrders] = React.useState(Store.getOrders());
  const [users, setUsers] = React.useState(Store.getUsers());
  const [editProduct, setEditProduct] = React.useState(null);
  const [editCat, setEditCat] = React.useState(null);
  const [newCat, setNewCat] = React.useState({ id: '', label: '' });

  if (!session || session.role !== 'admin') return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)', paddingTop: 70, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ color: '#c84040', fontFamily: 'Lato, sans-serif', fontSize: 16 }}>Acesso negado</div>
    </div>
  );

  const t = lang === 'pt' ? {
    title: 'Painel Admin', products: 'Produtos', orders: 'Encomendas',
    users: 'Utilizadores', cats: 'Categorias', stats: 'Estatísticas',
    save: 'Guardar', cancel: 'Cancelar', addProduct: 'Novo Produto',
    available: 'Disponível', unavailable: 'Esgotado',
    name: 'Nome', price: 'Preço (€)', desc: 'Descrição', cat: 'Categoria', featured: 'Destaque',
    statuses: { pending: 'Pendente', processing: 'Em Preparação', delivered: 'Entregue', cancelled: 'Cancelado' }
  } : {
    title: 'Admin Panel', products: 'Products', orders: 'Orders',
    users: 'Users', cats: 'Categories', stats: 'Statistics',
    save: 'Save', cancel: 'Cancel', addProduct: 'New Product',
    available: 'Available', unavailable: 'Sold Out',
    name: 'Name', price: 'Price (€)', desc: 'Description', cat: 'Category', featured: 'Featured',
    statuses: { pending: 'Pending', processing: 'Processing', delivered: 'Delivered', cancelled: 'Cancelled' }
  };

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

  const saveProduct = (p) => {
    const updated = p.id ? products.map(x => x.id === p.id ? p : x) : [...products, { ...p, id: Store.nextId(products) }];
    Store.saveProducts(updated); setProducts(updated); setEditProduct(null);
    showToast(lang==='pt'?'Produto guardado!':'Product saved!');
  };

  const deleteProduct = (id) => {
    const updated = products.filter(p => p.id !== id);
    Store.saveProducts(updated); setProducts(updated);
    showToast(lang==='pt'?'Produto eliminado.':'Product deleted.', 'info');
  };

  const toggleAvailable = (id) => {
    const updated = products.map(p => p.id === id ? { ...p, available: !p.available } : p);
    Store.saveProducts(updated); setProducts(updated);
  };

  const updateOrderStatus = (id, status) => {
    const updated = orders.map(o => o.id === id ? { ...o, status } : o);
    Store.saveOrders(updated); setOrders(updated);
    showToast(lang==='pt'?'Estado atualizado!':'Status updated!');
  };

  const saveCat = (cat) => {
    const updated = editCat ? categories.map(c => c.id === cat.id ? cat : c) : [...categories, cat];
    Store.saveCategories(updated); setCategories(updated);
    setEditCat(null); setNewCat({ id: '', label: '' });
  };

  const totalRevenue = orders.filter(o => o.status !== 'cancelled').reduce((s, o) => s + o.total, 0);
  const statCards = [
    { icon: '💰', label: lang==='pt'?'Receita':'Revenue', value: `${totalRevenue.toFixed(2)}€` },
    { icon: '📦', label: lang==='pt'?'Encomendas':'Orders', value: orders.length },
    { icon: '⏳', label: lang==='pt'?'Pendentes':'Pending', value: orders.filter(o=>o.status==='pending').length },
    { icon: '👥', label: lang==='pt'?'Clientes':'Customers', value: users.filter(u=>u.role!=='admin').length },
  ];

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

  const thStyle = { padding: '13px 14px', textAlign: 'left', fontFamily: 'Lato, sans-serif', color: 'var(--gold)', fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', fontWeight: 600 };
  const tdStyle = { padding: '11px 14px', fontFamily: 'Lato, sans-serif', fontSize: 13 };

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)', paddingTop: 70 }}>
      <div className="admin-layout" style={{ display: 'flex' }}>

        {/* Sidebar */}
        <aside className="admin-sidebar" style={{ width: 210, background: 'var(--footer-bg)', borderRight: '1px solid var(--border)', minHeight: 'calc(100vh - 70px)', padding: '20px 0', flexShrink: 0, display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '0 18px 20px', borderBottom: '1px solid var(--border)', marginBottom: 12 }}>
            <div style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 15 }}>{t.title}</div>
            <div style={{ fontFamily: 'Lato, sans-serif', color: 'var(--gold)', fontSize: 9, letterSpacing: 2, textTransform: 'uppercase', marginTop: 2 }}>Dom Papança</div>
          </div>
          {[['stats','📊',t.stats],['products','🍮',t.products],['orders','📦',t.orders],['users','👥',t.users],['cats','🏷️',t.cats]].map(([k,icon,label]) => (
            <button key={k} onClick={() => setTab(k)}
              style={{ display: 'flex', alignItems: 'center', gap: 9, width: '100%', padding: '11px 18px', background: tab===k?'rgba(212,153,58,0.12)':'transparent', border: 'none', borderLeft: `3px solid ${tab===k?'var(--gold)':'transparent'}`, color: tab===k?'var(--gold)':'var(--muted)', fontFamily: 'Lato, sans-serif', fontSize: 13, cursor: 'pointer', textAlign: 'left', transition: 'all 0.2s', minHeight: 44 }}>
              <span>{icon}</span><span>{label}</span>
            </button>
          ))}
          <div style={{ padding: '16px 18px 0', marginTop: 'auto', borderTop: '1px solid var(--border)' }}>
            <button onClick={() => setPage('home')}
              style={{ background: 'none', border: 'none', color: 'var(--dim)', fontFamily: 'Lato, sans-serif', fontSize: 12, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}>
              ← {lang==='pt'?'Voltar ao site':'Back to site'}
            </button>
          </div>
        </aside>

        {/* Main content */}
        <main style={{ flex: 1, padding: 'clamp(16px,3vw,28px)', overflow: 'auto', minWidth: 0 }}>

          {/* STATS */}
          {tab === 'stats' && (
            <div>
              <h2 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 26, margin: '0 0 24px' }}>{t.stats}</h2>
              <div className="stat-cards" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(160px,1fr))', gap: 16, marginBottom: 32 }}>
                {statCards.map(s => (
                  <div key={s.label} style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, padding: '20px', textAlign: 'center' }}>
                    <div style={{ fontSize: 28, marginBottom: 6 }}>{s.icon}</div>
                    <div style={{ fontFamily: "'Playfair Display', serif", color: 'var(--gold)', fontSize: 26, fontWeight: 700 }}>{s.value}</div>
                    <div style={{ fontFamily: 'Lato, sans-serif', color: 'var(--muted)', fontSize: 11, marginTop: 3, letterSpacing: 1, textTransform: 'uppercase' }}>{s.label}</div>
                  </div>
                ))}
              </div>
              <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, padding: 22 }}>
                <h3 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 18, margin: '0 0 16px' }}>
                  {lang==='pt'?'Últimas Encomendas':'Recent Orders'}
                </h3>
                {orders.length === 0 && <div style={{ color: 'var(--dim)', fontFamily: 'Lato, sans-serif', fontSize: 13 }}>{lang==='pt'?'Sem encomendas ainda.':'No orders yet.'}</div>}
                {[...orders].reverse().slice(0,5).map(o => (
                  <div key={o.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '11px 0', borderBottom: '1px solid rgba(212,153,58,0.07)', fontFamily: 'Lato, sans-serif', fontSize: 13, flexWrap: 'wrap', gap: 6 }}>
                    <span style={{ color: 'var(--cream)' }}>#{o.id} — {o.userName}</span>
                    <span style={{ color: statusColors[o.status] }}>{t.statuses[o.status]}</span>
                    <span style={{ color: 'var(--gold)', fontWeight: 700 }}>{o.total.toFixed(2)}€</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* PRODUCTS */}
          {tab === 'products' && (
            <div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, flexWrap: 'wrap', gap: 10 }}>
                <h2 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 26, margin: 0 }}>{t.products}</h2>
                <BtnPrimary small onClick={() => setEditProduct({ name:'', category: categories[0]?.id||'', price:'', description:'', available:true, featured:false, image:'nata' })}>
                  + {t.addProduct}
                </BtnPrimary>
              </div>
              <div className="table-wrap" style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, overflow: 'hidden' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 540 }}>
                  <thead>
                    <tr style={{ borderBottom: '1px solid var(--border)' }}>
                      {[t.name, t.cat, t.price, t.available, t.featured, ''].map(h => (
                        <th key={h} style={thStyle}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {products.map(p => (
                      <tr key={p.id} style={{ borderBottom: '1px solid rgba(212,153,58,0.06)' }}>
                        <td style={{ ...tdStyle, color: 'var(--cream)' }}>{p.name}</td>
                        <td style={{ ...tdStyle, color: 'var(--muted)' }}>{p.category}</td>
                        <td style={{ ...tdStyle, fontFamily: "'Playfair Display', serif", color: 'var(--gold)', fontSize: 15 }}>{parseFloat(p.price).toFixed(2)}€</td>
                        <td style={tdStyle}>
                          <button onClick={() => toggleAvailable(p.id)}
                            style={{ background: p.available ? 'rgba(74,154,48,0.15)' : 'rgba(200,64,64,0.15)', border: `1px solid ${p.available?'#4a9a3044':'#c8404044'}`, borderRadius: 4, color: p.available?'#4a9a30':'#c84040', padding: '3px 9px', fontSize: 11, fontFamily: 'Lato, sans-serif', cursor: 'pointer', letterSpacing: 1, textTransform: 'uppercase', whiteSpace: 'nowrap' }}>
                            {p.available ? t.available : t.unavailable}
                          </button>
                        </td>
                        <td style={{ ...tdStyle, color: p.featured ? 'var(--gold)' : 'var(--dim)' }}>{p.featured ? '★' : '☆'}</td>
                        <td style={tdStyle}>
                          <div style={{ display: 'flex', gap: 7 }}>
                            <BtnGhost small onClick={() => setEditProduct({ ...p })}>✎</BtnGhost>
                            <button onClick={() => deleteProduct(p.id)}
                              style={{ background: 'rgba(200,40,40,0.1)', border: '1px solid rgba(200,40,40,0.3)', color: '#c84040', borderRadius: 4, padding: '5px 10px', cursor: 'pointer', fontSize: 13 }}>✕</button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* ORDERS */}
          {tab === 'orders' && (
            <div>
              <h2 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 26, margin: '0 0 20px' }}>{t.orders}</h2>
              {orders.length === 0 ? (
                <div style={{ color: 'var(--dim)', fontFamily: 'Lato, sans-serif', padding: '40px 0', textAlign: 'center' }}>
                  {lang==='pt'?'Sem encomendas.':'No orders yet.'}
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  {[...orders].reverse().map(o => (
                    <div key={o.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 }}>Encomenda #{o.id}</span>
                          <span style={{ fontFamily: 'Lato, sans-serif', color: 'var(--dim)', fontSize: 12, marginLeft: 10 }}>
                            {new Date(o.createdAt).toLocaleString('pt-PT')}
                          </span>
                        </div>
                        <select value={o.status} onChange={e => updateOrderStatus(o.id, e.target.value)}
                          style={{ ...inputStyle, width: 'auto', fontSize: 12, padding: '6px 10px', minWidth: 130 }}>
                          {Object.entries(t.statuses).map(([k,v]) => <option key={k} value={k}>{v}</option>)}
                        </select>
                      </div>
                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(140px,1fr))', gap: 12, marginBottom: 12 }}>
                        {[
                          [lang==='pt'?'Cliente':'Customer', `${o.userName}\n${o.phone}`],
                          [lang==='pt'?'Morada':'Address', o.address],
                          ['Total', `${o.total.toFixed(2)}€ · ${o.payMethod}`],
                        ].map(([k,v]) => (
                          <div key={k}>
                            <div style={{ fontFamily: 'Lato, sans-serif', color: 'var(--dim)', fontSize: 10, letterSpacing: 1.5, textTransform: 'uppercase', marginBottom: 2 }}>{k}</div>
                            <div style={{ fontFamily: 'Lato, sans-serif', color: 'var(--cream)', fontSize: 13, whiteSpace: 'pre-line' }}>{v}</div>
                          </div>
                        ))}
                      </div>
                      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
                        {o.items.map(i => (
                          <span key={i.id} style={{ background: 'rgba(212,153,58,0.08)', border: '1px solid var(--border)', borderRadius: 3, padding: '3px 8px', fontFamily: 'Lato, sans-serif', color: 'var(--muted)', fontSize: 11 }}>
                            {i.name} ×{i.qty}
                          </span>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* USERS */}
          {tab === 'users' && (
            <div>
              <h2 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 26, margin: '0 0 20px' }}>{t.users}</h2>
              <div className="table-wrap" style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, overflow: 'hidden' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 400 }}>
                  <thead>
                    <tr style={{ borderBottom: '1px solid var(--border)' }}>
                      {['ID', lang==='pt'?'Nome':'Name', 'Email', 'Role', lang==='pt'?'Registo':'Registered'].map(h => (
                        <th key={h} style={thStyle}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {users.map(u => (
                      <tr key={u.id} style={{ borderBottom: '1px solid rgba(212,153,58,0.06)' }}>
                        <td style={{ ...tdStyle, color: 'var(--dim)' }}>{u.id}</td>
                        <td style={{ ...tdStyle, color: 'var(--cream)' }}>{u.name}</td>
                        <td style={{ ...tdStyle, color: 'var(--muted)' }}>{u.email}</td>
                        <td style={tdStyle}>
                          <span style={{ background: u.role==='admin'?'rgba(212,153,58,0.15)':'rgba(74,144,210,0.15)', border: `1px solid ${u.role==='admin'?'rgba(212,153,58,0.4)':'rgba(74,144,210,0.4)'}`, color: u.role==='admin'?'var(--gold)':'#4a90d2', borderRadius: 3, padding: '2px 8px', fontFamily: 'Lato, sans-serif', fontSize: 11, letterSpacing: 1, textTransform: 'uppercase' }}>{u.role}</span>
                        </td>
                        <td style={{ ...tdStyle, color: 'var(--dim)' }}>{u.createdAt}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* CATEGORIES */}
          {tab === 'cats' && (
            <div>
              <h2 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 26, margin: '0 0 20px' }}>{t.cats}</h2>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(260px,1fr))', gap: 24 }}>
                <div className="table-wrap" style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, overflow: 'hidden' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 240 }}>
                    <thead>
                      <tr style={{ borderBottom: '1px solid var(--border)' }}>
                        <th style={thStyle}>ID</th>
                        <th style={thStyle}>{lang==='pt'?'Nome':'Name'}</th>
                        <th style={thStyle}></th>
                      </tr>
                    </thead>
                    <tbody>
                      {categories.map(c => (
                        <tr key={c.id} style={{ borderBottom: '1px solid rgba(212,153,58,0.06)' }}>
                          <td style={{ ...tdStyle, color: 'var(--dim)' }}>{c.id}</td>
                          <td style={{ ...tdStyle, color: 'var(--cream)' }}>{c.label}</td>
                          <td style={tdStyle}>
                            <div style={{ display: 'flex', gap: 6 }}>
                              <BtnGhost small onClick={() => setEditCat({ ...c })}>✎</BtnGhost>
                              <button onClick={() => { const u = categories.filter(x=>x.id!==c.id); Store.saveCategories(u); setCategories(u); }}
                                style={{ background: 'rgba(200,40,40,0.1)', border: '1px solid rgba(200,40,40,0.3)', color: '#c84040', borderRadius: 4, padding: '4px 8px', cursor: 'pointer', fontSize: 12 }}>✕</button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, padding: 22 }}>
                  <h3 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 17, margin: '0 0 18px' }}>
                    {editCat ? (lang==='pt'?'Editar':'Edit') : (lang==='pt'?'Nova Categoria':'New Category')}
                  </h3>
                  <label style={lbl}>ID (slug)</label>
                  <div style={{ marginBottom: 13 }}>
                    <input value={editCat?editCat.id:newCat.id} disabled={!!editCat}
                      onChange={e => editCat?setEditCat(c=>({...c,id:e.target.value})):setNewCat(c=>({...c,id:e.target.value}))} />
                  </div>
                  <label style={lbl}>{lang==='pt'?'Nome visível':'Display name'}</label>
                  <div style={{ marginBottom: 18 }}>
                    <input value={editCat?editCat.label:newCat.label}
                      onChange={e => editCat?setEditCat(c=>({...c,label:e.target.value})):setNewCat(c=>({...c,label:e.target.value}))} />
                  </div>
                  <div style={{ display: 'flex', gap: 8 }}>
                    <BtnPrimary small onClick={() => saveCat(editCat||newCat)}>{t.save}</BtnPrimary>
                    {editCat && <BtnGhost small onClick={() => setEditCat(null)}>{t.cancel}</BtnGhost>}
                  </div>
                </div>
              </div>
            </div>
          )}
        </main>
      </div>

      {/* Product edit modal */}
      {editProduct && (
        <Modal title={editProduct.id ? (lang==='pt'?'Editar Produto':'Edit Product') : (lang==='pt'?'Novo Produto':'New Product')}
          onClose={() => setEditProduct(null)} wide>
          <ProductEditForm product={editProduct} categories={categories}
            onSave={saveProduct} onCancel={() => setEditProduct(null)} lang={lang} t={t} />
        </Modal>
      )}
    </div>
  );
}

function ProductEditForm({ product, categories, onSave, onCancel, lang, t }) {
  const [form, setForm] = React.useState({ ...product });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const lbl = { display: 'block', fontFamily: 'Lato, sans-serif', color: 'var(--muted)', fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', marginBottom: 5 };
  const fld = { ...inputStyle, marginBottom: 13 };
  const imageOptions = ['nata','bolo','rissol','coxinha','choco','custom','chamuca','tematico','empada','feijao'];

  return (
    <div>
      <div className="prod-edit-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
        <div>
          <label style={lbl}>{t.name} *</label>
          <input style={fld} value={form.name} onChange={e => set('name', e.target.value)} />
          <label style={lbl}>{t.price} *</label>
          <input style={fld} type="number" step="0.01" min="0" value={form.price} onChange={e => set('price', parseFloat(e.target.value)||0)} inputMode="decimal" />
          <label style={lbl}>{t.cat}</label>
          <select style={fld} value={form.category} onChange={e => set('category', e.target.value)}>
            {categories.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
          </select>
          <label style={lbl}>{lang==='pt'?'Imagem':'Image'}</label>
          <select style={fld} value={form.image} onChange={e => set('image', e.target.value)}>
            {imageOptions.map(o => <option key={o} value={o}>{o}</option>)}
          </select>
        </div>
        <div>
          <label style={lbl}>{t.desc}</label>
          <textarea style={{ ...inputStyle, height: 96, resize: 'vertical', marginBottom: 13 }} value={form.description} onChange={e => set('description', e.target.value)} />
          <div style={{ display: 'flex', gap: 20, marginBottom: 14 }}>
            {[['available', t.available], ['featured', t.featured]].map(([k, lbl2]) => (
              <label key={k} style={{ display: 'flex', alignItems: 'center', gap: 7, cursor: 'pointer', fontFamily: 'Lato, sans-serif', color: 'var(--muted)', fontSize: 13 }}>
                <input type="checkbox" checked={form[k]} onChange={e => set(k, e.target.checked)} />
                {lbl2}
              </label>
            ))}
          </div>
          <div style={{ borderRadius: 8, overflow: 'hidden', border: '1px solid var(--border)' }}>
            <ProductImage type={form.image} size={150} />
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 10, marginTop: 10 }}>
        <BtnPrimary onClick={() => onSave(form)}>{t.save}</BtnPrimary>
        <BtnGhost onClick={onCancel}>{t.cancel}</BtnGhost>
      </div>
    </div>
  );
}

Object.assign(window, { AdminPage, ProductEditForm });
