// admin-orders.jsx — Gestionare comenzi (admin)

const { useState: useStateAO } = React;

const ADM_ORDERS = [
  { id: 'ORD-2402', date: '20 apr 2026 14:32', creator: 'Andra Mihăescu', user: '@andra.m', avatar: 'AM', country: '🇷🇴', products: [{ name: 'PS5 Slim', g1: '#101820', g2: '#52F20F' }], pts: 380, status: 'În pregătire', awb: '', step: 1 },
  { id: 'ORD-2398', date: '12 apr 2026 09:15', creator: 'Andra Mihăescu', user: '@andra.m', avatar: 'AM', country: '🇷🇴', products: [{ name: 'iPhone 15 Pro', g1: '#1f2937', g2: '#52F20F' }], pts: 850, status: 'Expediată', awb: 'SAM12498273RO', step: 2 },
  { id: 'ORD-2397', date: '11 apr 2026 18:42', creator: 'Sophia Lloyd', user: '@sophia_l', avatar: 'SL', country: '🇬🇧', products: [{ name: 'Geantă LV', g1: '#3a2410', g2: '#FFD700' }, { name: 'AirPods Pro 2', g1: '#0E0E0E', g2: '#FFD700' }], pts: 900, status: 'Expediată', awb: 'INTL9382010UK', step: 2 },
  { id: 'ORD-2391', date: '9 apr 2026 12:00', creator: 'Marco Rossi', user: '@marco.r', avatar: 'MR', country: '🇮🇹', products: [{ name: 'AirPods Pro 2', g1: '#0E0E0E', g2: '#FFD700' }], pts: 220, status: 'În pregătire', awb: '', step: 1 },
  { id: 'ORD-2386', date: '7 apr 2026 21:08', creator: 'Răzvan Popescu', user: '@razvan.live', avatar: 'RP', country: '🇷🇴', products: [{ name: 'PS5 Slim', g1: '#101820', g2: '#52F20F' }], pts: 380, status: 'Nouă', awb: '', step: 0 },
  { id: 'ORD-2371', date: '4 apr 2026 11:23', creator: 'Andra Mihăescu', user: '@andra.m', avatar: 'AM', country: '🇷🇴', products: [{ name: 'Sony WH-1000XM5', g1: '#0E0E0E', g2: '#FFD700' }], pts: 320, status: 'Livrată', awb: 'FAN98472301RO', step: 3 },
  { id: 'ORD-2356', date: '28 mar 2026 14:00', creator: 'Maria Iancu', user: '@maria.iancu', avatar: 'MI', country: '🇷🇴', products: [{ name: 'Pachet skincare', g1: '#2a0f1a', g2: '#FFD700' }], pts: 75, status: 'Livrată', awb: 'CARGUS73294RO', step: 3 },
  { id: 'ORD-2341', date: '21 mar 2026 16:45', creator: 'Elena Petrescu', user: '@elena.p', avatar: 'EP', country: '🇷🇴', products: [{ name: 'Maldive Voucher', g1: '#FFD700', g2: '#52F20F' }], pts: 1200, status: 'Livrată', awb: 'DIGITAL-VCH', step: 3 },
  { id: 'ORD-2310', date: '14 mar 2026 10:12', creator: 'Diego Sanchez', user: '@diego.s', avatar: 'DS', country: '🇪🇸', products: [{ name: 'AirPods Pro 2', g1: '#0E0E0E', g2: '#FFD700' }], pts: 220, status: 'Livrată', awb: 'INTLES84201ES', step: 3 },
  { id: 'ORD-2287', date: '6 mar 2026 19:30', creator: 'Carmen Albu', user: '@carmen.a', avatar: 'CA', country: '🇷🇴', products: [{ name: 'Cină Michelin', g1: '#0E0E0E', g2: '#52F20F' }], pts: 90, status: 'Livrată', awb: 'DIGITAL-VCH', step: 3 },
  { id: 'ORD-2241', date: '22 feb 2026 13:18', creator: 'Tom Jenkins', user: '@tomj_uk', avatar: 'TJ', country: '🇬🇧', products: [{ name: 'Sneakers OW', g1: '#1a1a1a', g2: '#FFD700' }], pts: 240, status: 'Anulată', awb: '—', step: -1 },
  { id: 'ORD-2403', date: '21 apr 2026 08:45', creator: 'Lukas Schmidt', user: '@lukas.s', avatar: 'LS', country: '🇩🇪', products: [{ name: 'Set Charlotte T.', g1: '#2a0f1a', g2: '#FFD700' }], pts: 65, status: 'Nouă', awb: '', step: 0 },
  { id: 'ORD-2404', date: '21 apr 2026 13:22', creator: 'João Silva', user: '@joao.s', avatar: 'JS', country: '🇵🇹', products: [{ name: 'Concert Untold', g1: '#1a0a2a', g2: '#52F20F' }], pts: 350, status: 'Nouă', awb: '', step: 0 },
  { id: 'ORD-2405', date: '21 apr 2026 18:01', creator: 'Lars van Berg', user: '@lars.vb', avatar: 'LV', country: '🇳🇱', products: [{ name: 'City Break Roma', g1: '#3a1f1a', g2: '#FFD700' }], pts: 480, status: 'În pregătire', awb: '', step: 1 },
  { id: 'ORD-2406', date: '22 apr 2026 09:10', creator: 'Pierre Dubois', user: '@pierre.d', avatar: 'PD', country: '🇫🇷', products: [{ name: 'AirPods Pro 2', g1: '#0E0E0E', g2: '#FFD700' }, { name: 'iPhone Charger', g1: '#1a1a1a', g2: '#52F20F' }, { name: 'Cable USB-C', g1: '#2a2a2a', g2: '#52F20F' }], pts: 290, status: 'Nouă', awb: '', step: 0 },
];

const ADM_STEPS = ['Comandată', 'În pregătire', 'Expediată', 'Livrată'];

function AdminOrdersPage({ onNav, user }) {
  const adminUser = { name: user?.name || 'Andrei Popescu' };
  const [tab, setTab] = useStateAO('Toate');
  const [q, setQ] = useStateAO('');
  const [selected, setSelected] = useStateAO([]);
  const [drawer, setDrawer] = useStateAO(null);
  const [Toast, toast] = useToast();

  const counts = {
    Toate: ADM_ORDERS.length,
    Nouă: ADM_ORDERS.filter(o => o.status === 'Nouă').length,
    'În pregătire': ADM_ORDERS.filter(o => o.status === 'În pregătire').length,
    Expediată: ADM_ORDERS.filter(o => o.status === 'Expediată').length,
    Livrată: ADM_ORDERS.filter(o => o.status === 'Livrată').length,
    Anulată: ADM_ORDERS.filter(o => o.status === 'Anulată').length,
  };

  let list = ADM_ORDERS;
  if (tab !== 'Toate') list = list.filter(o => o.status === tab);
  if (q) list = list.filter(o => o.id.toLowerCase().includes(q.toLowerCase()) || o.creator.toLowerCase().includes(q.toLowerCase()) || o.products.some(p => p.name.toLowerCase().includes(q.toLowerCase())));

  const toggleSel = (id) => setSelected(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);
  const toggleAll = () => setSelected(selected.length === list.length ? [] : list.map(o => o.id));

  const statusColor = { 'Nouă': '#63B3ED', 'În pregătire': '#FFD700', 'Expediată': '#FFD700', 'Livrată': '#52F20F', 'Anulată': '#ef4444' };

  return (
    <div className="page" style={{ display: 'grid', gridTemplateColumns: '260px 1fr', minHeight: '100vh', background: 'linear-gradient(135deg, #0A0A0F, #0E0E0E)' }}>
      <DashSidebar active="admin-orders" onNav={onNav} user={adminUser} admin />
      <main style={{ padding: '32px 40px', overflowY: 'auto' }} className="dash-main">
        <div className="pill" style={{ background: 'rgba(255,215,0,.08)', borderColor: 'rgba(255,215,0,.4)', color: 'var(--accent-2)', display: 'inline-flex', marginBottom: 12 }}>
          <span className="mono" style={{ fontSize: 10, letterSpacing: '0.15em' }}>● MOD ADMIN · COMENZI</span>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 16, marginBottom: 20 }}>
          <div>
            <h1 className="display" style={{ fontSize: 32, margin: 0 }}>Toate comenzile</h1>
            <p style={{ fontSize: 13, color: 'var(--txt-2)', marginTop: 4 }}>
              <span style={{ color: 'var(--accent-2)' }}>{counts['În pregătire'] + counts.Expediată} active</span> ·
              <span style={{ color: '#63B3ED' }}> {counts.Nouă} în așteptare</span> ·
              <span style={{ color: 'var(--accent-1)' }}> {counts.Livrată} livrate luna asta</span>
            </p>
          </div>
          <button className="btn btn-glass btn-sm">↓ Export comenzi</button>
        </div>

        {/* Filters */}
        <div className="card" style={{ padding: 14, marginBottom: 12, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <input value={q} onChange={(e) => setQ(e.target.value)} className="input" placeholder="🔍 Caută după ID, creator, produs..." style={{ flex: 1, minWidth: 220, height: 34 }} />
          <input type="date" className="input" style={{ width: 'auto', height: 34 }} />
          <select className="input" style={{ width: 'auto', height: 34 }}><option>Toate țările</option><option>🇷🇴 RO</option><option>🇬🇧 UK</option><option>🇩🇪 DE</option></select>
        </div>

        {/* Status tabs */}
        <div style={{ display: 'flex', gap: 6, overflowX: 'auto', marginBottom: 16, padding: '4px 0' }}>
          {Object.keys(counts).map(k => (
            <button key={k} onClick={() => setTab(k)} className="btn btn-sm" style={{
              background: tab === k ? 'var(--accent-1)' : 'transparent',
              color: tab === k ? '#0A0A0F' : 'var(--txt-2)',
              border: tab === k ? 'none' : '.5px solid', borderColor: tab === k ? 'transparent' : (tab === k ? 'var(--accent-2)' : 'var(--line)'),
              borderBottomWidth: tab === k ? 0 : 2, borderBottomColor: tab === k ? 'transparent' : 'var(--accent-2)',
              flexShrink: 0, display: 'flex', gap: 6, alignItems: 'center',
            }}>{k} <span className="mono" style={{ fontSize: 10, opacity: 0.7 }}>({counts[k]})</span></button>
          ))}
        </div>

        {/* Bulk */}
        {selected.length > 0 && (
          <div className="card-glass" style={{ padding: 12, marginBottom: 12, display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap', borderColor: 'var(--accent-2)' }}>
            <span className="mono" style={{ fontSize: 12, color: 'var(--accent-2)' }}>● {selected.length} comenzi selectate</span>
            <button className="btn btn-glass btn-sm" onClick={() => toast('Marcate ca expediate')}>Marchează expediate</button>
            <button className="btn btn-glass btn-sm">Export selecție</button>
            <button className="btn btn-glass btn-sm">Trimite update email</button>
            <button className="btn btn-glass btn-sm" style={{ marginLeft: 'auto' }} onClick={() => setSelected([])}>Anulează</button>
          </div>
        )}

        {/* Table */}
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, minWidth: 1100 }}>
              <thead style={{ background: 'var(--bg-2)' }}>
                <tr>
                  <th style={th(40)}><input type="checkbox" checked={selected.length === list.length && list.length > 0} onChange={toggleAll} /></th>
                  <th style={th(110)}>ID</th>
                  <th style={th(140)}>Data</th>
                  <th style={th(180)}>Creator</th>
                  <th style={th()}>Produse</th>
                  <th style={th(100)}>Total pts</th>
                  <th style={th(120)}>Status</th>
                  <th style={th(140)}>Tracking</th>
                  <th style={th(60)}></th>
                </tr>
              </thead>
              <tbody>
                {list.map(o => (
                  <tr key={o.id} onClick={() => setDrawer(o)} className="hov" style={{ cursor: 'pointer', borderTop: '.5px solid var(--line-soft)' }}
                      onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(82,242,15,.04)'}
                      onMouseLeave={(e) => e.currentTarget.style.background = ''}>
                    <td style={td()} onClick={(e) => { e.stopPropagation(); toggleSel(o.id); }}>
                      <input type="checkbox" checked={selected.includes(o.id)} onChange={() => {}} />
                    </td>
                    <td style={{ ...td(), fontFamily: 'JetBrains Mono', fontSize: 12, color: 'var(--accent-1)' }}>{o.id}</td>
                    <td style={{ ...td(), fontFamily: 'JetBrains Mono', fontSize: 11, color: 'var(--txt-3)' }}>{o.date}</td>
                    <td style={td()}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <div style={{ width: 28, height: 28, borderRadius: 999, background: 'linear-gradient(135deg, var(--accent-2), var(--accent-1))', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 600, color: '#0A0A0F', flexShrink: 0 }}>{o.avatar}</div>
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontSize: 12, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{o.creator}</div>
                          <div className="mono" style={{ fontSize: 10, color: 'var(--accent-1)' }}>{o.user} {o.country}</div>
                        </div>
                      </div>
                    </td>
                    <td style={td()}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        {o.products.slice(0, 2).map((p, i) => (
                          <div key={i} style={{ width: 28, height: 28, borderRadius: 6, background: `linear-gradient(135deg, ${p.g1}, ${p.g2})`, flexShrink: 0 }} title={p.name} />
                        ))}
                        {o.products.length > 2 && <span className="mono" style={{ fontSize: 10, color: 'var(--txt-3)' }}>+{o.products.length - 2}</span>}
                        <span style={{ fontSize: 12, color: 'var(--txt-2)', marginLeft: 4 }}>{o.products[0].name}{o.products.length > 1 ? '...' : ''}</span>
                      </div>
                    </td>
                    <td style={{ ...td(), fontFamily: 'JetBrains Mono', color: 'var(--accent-1)' }}>💎 {o.pts}</td>
                    <td style={td()} onClick={(e) => e.stopPropagation()}>
                      <select defaultValue={o.status} className="input" style={{ height: 28, fontSize: 11, padding: '2px 8px', border: '.5px solid', borderColor: statusColor[o.status] + '40', background: statusColor[o.status] + '12', color: statusColor[o.status] }}>
                        {['Nouă', 'În pregătire', 'Expediată', 'Livrată', 'Anulată'].map(s => <option key={s} style={{ background: '#0A0A0F', color: '#fff' }}>{s}</option>)}
                      </select>
                    </td>
                    <td style={{ ...td(), fontFamily: 'JetBrains Mono', fontSize: 11, color: 'var(--txt-3)' }}>{o.awb || '—'}</td>
                    <td style={td()}><button className="btn btn-glass btn-sm" style={{ padding: '4px 8px' }} onClick={(e) => e.stopPropagation()}>⋯</button></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <div style={{ marginTop: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>Afișare 1-{list.length} din {ADM_ORDERS.length}</div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-glass btn-sm">← Prev</button>
            <button className="btn btn-glass btn-sm">Next →</button>
          </div>
        </div>
      </main>

      {drawer && <OrderDrawer order={drawer} onClose={() => setDrawer(null)} toast={toast} statusColor={statusColor} onNav={onNav} />}
      {Toast}
    </div>
  );
}

function OrderDrawer({ order, onClose, toast, statusColor, onNav }) {
  const [awb, setAwb] = useStateAO(order.awb);
  const [step, setStep] = useStateAO(order.step);
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(4px)', zIndex: 100, display: 'flex', justifyContent: 'flex-end' }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: 'min(580px, 92vw)', height: '100%', background: 'var(--bg-1)', borderLeft: '.5px solid var(--line)',
        overflowY: 'auto', padding: 28, animation: 'slideR .3s ease-out',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
          <div>
            <span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>● COMANDĂ</span>
            <div className="display mono" style={{ fontSize: 22, color: 'var(--accent-1)', marginTop: 4 }}>{order.id}</div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 2 }}>{order.date}</div>
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: 0, fontSize: 24, color: 'var(--txt-2)', cursor: 'pointer' }}>×</button>
        </div>

        {/* Status */}
        <div style={{ padding: 12, background: statusColor[order.status] + '10', borderRadius: 10, border: '.5px solid', borderColor: statusColor[order.status] + '40', marginBottom: 20 }}>
          <span style={{ color: statusColor[order.status], fontSize: 14, fontWeight: 600 }}>● {order.status}</span>
        </div>

        {/* Timeline */}
        {order.status !== 'Anulată' && (
          <div style={{ marginBottom: 24 }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', marginBottom: 12 }}>FLOW STATUS</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', position: 'relative' }}>
              {ADM_STEPS.map((s, i) => {
                const done = i <= step;
                return (
                  <div key={s} style={{ textAlign: 'center', position: 'relative' }}>
                    {i < 3 && <div style={{ position: 'absolute', top: 12, left: '50%', right: '-50%', height: 2, background: i < step ? 'var(--accent-1)' : 'var(--line)' }} />}
                    <div style={{
                      width: 26, height: 26, borderRadius: 999, margin: '0 auto', position: 'relative', zIndex: 1,
                      background: done ? 'var(--accent-1)' : 'var(--bg-3)',
                      display: 'grid', placeItems: 'center', color: done ? '#0A0A0F' : 'var(--txt-3)', fontSize: 11, fontWeight: 600,
                    }}>{done ? '✓' : i + 1}</div>
                    <div style={{ marginTop: 6, fontSize: 10, color: done ? 'var(--txt-1)' : 'var(--txt-3)' }}>{s}</div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* Creator */}
        <div className="display" style={{ fontSize: 14, marginBottom: 8 }}>Creator</div>
        <div style={{ padding: 12, background: 'var(--bg-2)', borderRadius: 8, marginBottom: 16, display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 36, height: 36, borderRadius: 999, background: 'linear-gradient(135deg, var(--accent-2), var(--accent-1))', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 600, color: '#0A0A0F' }}>{order.avatar}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{order.creator}</div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--accent-1)' }}>{order.user} {order.country}</div>
          </div>
          <button onClick={() => { onClose(); onNav('admin-creators'); }} className="btn btn-glass btn-sm">Vezi profil →</button>
        </div>

        {/* Products */}
        <div className="display" style={{ fontSize: 14, marginBottom: 8 }}>Produse ({order.products.length})</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 16 }}>
          {order.products.map((p, i) => (
            <div key={i} style={{ padding: 10, background: 'var(--bg-2)', borderRadius: 8, display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 36, height: 36, borderRadius: 6, background: `linear-gradient(135deg, ${p.g1}, ${p.g2})`, flexShrink: 0 }} />
              <div style={{ flex: 1, fontSize: 13 }}>{p.name}</div>
              <span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>×1</span>
            </div>
          ))}
        </div>

        {/* Address */}
        <div className="display" style={{ fontSize: 14, marginBottom: 8 }}>Adresă livrare</div>
        <div style={{ padding: 12, background: 'var(--bg-2)', borderRadius: 8, marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
          <div style={{ fontSize: 13, lineHeight: 1.6 }}>
            {order.creator}<br/>
            Str. Polonă 38, Sect. 1<br/>
            București, 010494, RO<br/>
            <span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>+40 723 456 789</span>
          </div>
          <button onClick={() => { navigator.clipboard?.writeText(`${order.creator}, Str. Polonă 38, București`); toast('Copiată'); }} className="btn btn-glass btn-sm">Copiază</button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 16 }}>
          <Info label="Total puncte" val={'💎 ' + order.pts} />
          <Info label="Țară" val={order.country} />
        </div>

        {/* AWB */}
        <div className="display" style={{ fontSize: 14, marginBottom: 8 }}>Tracking AWB</div>
        <div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
          <input value={awb} onChange={(e) => setAwb(e.target.value)} className="input" placeholder="ex: SAM12498273RO" style={{ flex: 1, height: 36 }} />
          <button onClick={() => toast('AWB salvat')} className="btn btn-primary btn-sm">Salvează</button>
        </div>

        <div className="display" style={{ fontSize: 14, marginBottom: 8 }}>Note interne</div>
        <textarea className="input" style={{ minHeight: 60, padding: 10, marginBottom: 20 }} placeholder="Adaugă o notă..." />

        <div className="display" style={{ fontSize: 14, marginBottom: 8 }}>Workflow</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 16 }}>
          {step < 1 && <button onClick={() => { setStep(1); toast('Marcată: În pregătire'); }} className="btn btn-glass">▸ Marchează ca În pregătire</button>}
          {step < 2 && <button onClick={() => { if (!awb) { toast('Adaugă AWB mai întâi'); return; } setStep(2); toast('Marcată: Expediată'); }} className="btn btn-glass">📦 Marchează ca Expediată {!awb && '(necesită AWB)'}</button>}
          {step < 3 && step >= 0 && <button onClick={() => { setStep(3); toast('Marcată: Livrată'); }} className="btn btn-primary">✓ Marchează ca Livrată</button>}
          <button onClick={() => { if (confirm('Anulezi comanda? Punctele vor fi restituite.')) { toast('Comandă anulată, puncte restituite'); } }} className="btn btn-glass" style={{ color: '#ef4444', borderColor: '#ef4444' + '40' }}>✕ Anulează comanda (cu restituire)</button>
        </div>
      </div>
      <style>{`@keyframes slideR { from { transform: translateX(100%) } to { transform: translateX(0) } }`}</style>
    </div>
  );
}

window.AdminOrdersPage = AdminOrdersPage;
