// orders.jsx — Istoric comenzi (user account)

const { useState: useStateO } = React;

const ORDERS = [
  { id: 'ORD-2398', date: '12 apr 2026', name: 'iPhone 15 Pro 256GB', pts: 850, status: 'Expediată', tracking: 'SAM12498273RO', g1: '#1f2937', g2: '#52F20F', steps: 2 },
  { id: 'ORD-2371', date: '4 apr 2026', name: 'Sony WH-1000XM5', pts: 320, status: 'Livrată', tracking: 'FAN98472301RO', g1: '#0E0E0E', g2: '#FFD700', steps: 3 },
  { id: 'ORD-2356', date: '28 mar 2026', name: 'Pachet skincare premium', pts: 75, status: 'Livrată', tracking: 'CARGUS73294RO', g1: '#2a0f1a', g2: '#FFD700', steps: 3 },
  { id: 'ORD-2341', date: '21 mar 2026', name: 'Weekend Maldive (voucher)', pts: 1200, status: 'Livrată', tracking: 'DIGITAL-VCH', g1: '#FFD700', g2: '#52F20F', steps: 3 },
  { id: 'ORD-2310', date: '14 mar 2026', name: 'AirPods Pro 2', pts: 220, status: 'Livrată', tracking: 'FAN84736201RO', g1: '#0E0E0E', g2: '#FFD700', steps: 3 },
  { id: 'ORD-2287', date: '6 mar 2026', name: 'Cină Michelin București', pts: 90, status: 'Livrată', tracking: 'DIGITAL-VCH', g1: '#0E0E0E', g2: '#52F20F', steps: 3 },
  { id: 'ORD-2241', date: '22 feb 2026', name: 'Sneakers Off-White', pts: 240, status: 'Anulată', tracking: '—', g1: '#1a1a1a', g2: '#FFD700', steps: 0 },
  { id: 'ORD-2198', date: '14 feb 2026', name: 'Concert Untold VIP', pts: 350, status: 'Livrată', tracking: 'DIGITAL-VCH', g1: '#1a0a2a', g2: '#52F20F', steps: 3 },
  { id: 'ORD-2156', date: '3 feb 2026', name: 'Set Charlotte Tilbury', pts: 65, status: 'Livrată', tracking: 'CARGUS41203RO', g1: '#2a0f1a', g2: '#FFD700', steps: 3 },
  { id: 'ORD-2402', date: '20 apr 2026', name: 'PS5 Slim', pts: 380, status: 'În pregătire', tracking: 'În curs de generare', g1: '#101820', g2: '#52F20F', steps: 1 },
];

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

function OrdersPage({ onNav, user }) {
  const [tab, setTab] = useStateO('Toate');
  const [sort, setSort] = useStateO('Recente');
  const [q, setQ] = useStateO('');
  const [detail, setDetail] = useStateO(null);
  const [Toast, toast] = useToast();

  const tabs = ['Toate', 'În pregătire', 'Expediate', 'Livrate', 'Anulate'];
  const tabMap = { 'În pregătire': 'În pregătire', 'Expediate': 'Expediată', 'Livrate': 'Livrată', 'Anulate': 'Anulată' };

  let list = ORDERS.filter(o => tab === 'Toate' || o.status === tabMap[tab]);
  if (q) list = list.filter(o => o.name.toLowerCase().includes(q.toLowerCase()) || o.id.toLowerCase().includes(q.toLowerCase()));
  if (sort === 'Cele mai vechi') list = [...list].reverse();
  if (sort === 'Preț ↑') list = [...list].sort((a, b) => a.pts - b.pts);
  if (sort === 'Preț ↓') list = [...list].sort((a, b) => b.pts - a.pts);

  const total = ORDERS.length;
  const ptsUsed = ORDERS.filter(o => o.status !== 'Anulată').reduce((s, o) => s + o.pts, 0);
  const inTransit = ORDERS.filter(o => o.status === 'În pregătire' || o.status === 'Expediată').length;

  const statusColor = { 'Expediată': '#FFD700', 'Livrată': '#52F20F', 'În pregătire': '#FFD700', 'Anulată': 'var(--txt-3)' };

  return (
    <div className="page" style={{ display: 'grid', gridTemplateColumns: '260px 1fr', minHeight: '100vh' }}>
      <DashSidebar active="orders" onNav={onNav} user={user} />
      <main style={{ padding: '32px 48px', overflowY: 'auto', background: 'var(--bg-1)' }} className="dash-main">
        {/* Header */}
        <div style={{ marginBottom: 32 }}>
          <div className="mono" style={{ fontSize: 11, color: 'var(--accent-1)', letterSpacing: '0.15em', marginBottom: 10 }}>● ISTORIC COMENZI</div>
          <h1 className="display" style={{ fontSize: 40, margin: 0 }}>Comenzile tale 4U</h1>
          <p style={{ fontSize: 15, color: 'var(--txt-2)', marginTop: 8 }}>Toate produsele răscumpărate cu 4U Points.</p>
        </div>

        {/* Stats */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 32 }} className="ord-stats">
          {[
            { ico: '📦', label: 'Total comenzi', val: total, c: 'var(--txt-1)' },
            { ico: '💎', label: 'Puncte folosite', val: ptsUsed, c: 'var(--accent-1)' },
            { ico: '⏳', label: 'În tranzit', val: inTransit, c: 'var(--accent-2)' },
          ].map((s, i) => (
            <div key={i} className="card" style={{ padding: 20, display: 'flex', alignItems: 'center', gap: 16 }}>
              <div style={{ width: 48, height: 48, borderRadius: 12, background: 'var(--bg-3)', display: 'grid', placeItems: 'center', fontSize: 22 }}>{s.ico}</div>
              <div>
                <div className="display mono" style={{ fontSize: 28, color: s.c, lineHeight: 1 }}><Counter to={s.val} /></div>
                <div style={{ fontSize: 12, color: 'var(--txt-2)', marginTop: 4 }}>{s.label}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Filtre */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12, marginBottom: 20 }}>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {tabs.map(t => (
              <button key={t} onClick={() => setTab(t)} className="btn btn-sm" style={{
                background: tab === t ? 'var(--accent-1)' : 'transparent',
                color: tab === t ? '#0A0A0F' : 'var(--txt-2)',
                border: tab === t ? 'none' : '.5px solid var(--line)',
                fontWeight: tab === t ? 600 : 400,
              }}>{t}</button>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <input value={q} onChange={(e) => setQ(e.target.value)} className="input" placeholder="Caută comandă..." style={{ height: 36, width: 180, fontSize: 13 }} />
            <select value={sort} onChange={(e) => setSort(e.target.value)} className="input" style={{ height: 36, width: 'auto', fontSize: 13 }}>
              {['Recente', 'Cele mai vechi', 'Preț ↑', 'Preț ↓'].map(o => <option key={o}>{o}</option>)}
            </select>
          </div>
        </div>

        {/* Lista */}
        {list.length === 0 ? (
          <div className="card" style={{ padding: 64, textAlign: 'center' }}>
            <div style={{ fontSize: 56 }}>📦</div>
            <div className="display" style={{ fontSize: 22, marginTop: 16 }}>Nicio comandă încă</div>
            <p style={{ color: 'var(--txt-2)', marginTop: 8 }}>Răscumpără punctele tale 4U pentru produse premium.</p>
            <button className="btn btn-primary" style={{ marginTop: 20 }} onClick={() => onNav('shop')}>Mergi la magazin →</button>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {list.map(o => (
              <div key={o.id} onClick={() => setDetail(o)} className="card hov" style={{
                padding: 16, display: 'grid', gridTemplateColumns: '64px 1fr 120px 140px 100px', alignItems: 'center', gap: 16,
                cursor: 'pointer', transition: 'all .2s',
              }} onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(82,242,15,.04)'}
                 onMouseLeave={(e) => e.currentTarget.style.background = ''}>
                <div style={{ width: 64, height: 64, borderRadius: 10, background: `linear-gradient(135deg, ${o.g1}, ${o.g2})`, position: 'relative', overflow: 'hidden' }}>
                  <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 30% 30%, rgba(255,255,255,.2), transparent)' }} />
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 500 }}>{o.name}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 4 }}>{o.id} · {o.date}</div>
                </div>
                <div className="mono" style={{ fontSize: 14, color: 'var(--accent-1)' }}>💎 {o.pts.toLocaleString('ro-RO')}</div>
                <div>
                  <span className="pill" style={{ fontSize: 10, color: statusColor[o.status], borderColor: statusColor[o.status] + '40', background: statusColor[o.status] + '12' }}>● {o.status}</span>
                </div>
                <button className="btn btn-glass btn-sm" style={{ width: '100%' }}>Detalii →</button>
              </div>
            ))}
          </div>
        )}

        {/* Paginare */}
        {list.length > 0 && (
          <div style={{ marginTop: 32, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div className="mono" style={{ fontSize: 12, color: 'var(--txt-3)' }}>Pagina 1 din 3</div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button className="btn btn-glass btn-sm" disabled style={{ opacity: 0.4 }}>← Prev</button>
              <button className="btn btn-glass btn-sm">Next →</button>
            </div>
          </div>
        )}
      </main>

      {/* Detail Modal */}
      {detail && (
        <div onClick={() => setDetail(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)', zIndex: 100, display: 'grid', placeItems: 'center', padding: 24 }}>
          <div onClick={(e) => e.stopPropagation()} className="card-glass" style={{ maxWidth: 720, width: '100%', maxHeight: '90vh', overflowY: 'auto', padding: 32, position: 'relative' }}>
            <button onClick={() => setDetail(null)} style={{ position: 'absolute', top: 16, right: 16, background: 'transparent', border: 0, color: 'var(--txt-2)', fontSize: 22, cursor: 'pointer' }}>×</button>
            <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', letterSpacing: '0.1em' }}>{detail.id}</div>
            <div className="display" style={{ fontSize: 26, marginTop: 6 }}>{detail.name}</div>

            <div style={{ display: 'grid', gridTemplateColumns: '160px 1fr', gap: 24, marginTop: 24 }}>
              <div style={{ width: 160, height: 160, borderRadius: 14, background: `linear-gradient(135deg, ${detail.g1}, ${detail.g2})`, position: 'relative', overflow: 'hidden' }}>
                <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 30% 30%, rgba(255,255,255,.25), transparent)' }} />
              </div>
              <div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>STATUS</div>
                <div style={{ fontSize: 18, color: statusColor[detail.status], marginTop: 4 }}>● {detail.status}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 16 }}>PUNCTE FOLOSITE</div>
                <div className="display mono" style={{ fontSize: 24, color: 'var(--accent-1)', marginTop: 4 }}>💎 {detail.pts.toLocaleString('ro-RO')}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 16 }}>DATA COMANDĂ</div>
                <div style={{ fontSize: 14, marginTop: 4 }}>{detail.date}</div>
              </div>
            </div>

            {/* Status timeline */}
            {detail.status !== 'Anulată' && (
              <div style={{ marginTop: 32 }}>
                <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', marginBottom: 16 }}>PROGRES COMANDĂ</div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, position: 'relative' }}>
                  {STEPS.map((s, i) => {
                    const done = i <= detail.steps;
                    const current = i === detail.steps;
                    return (
                      <div key={s} style={{ textAlign: 'center', position: 'relative' }}>
                        {i < 3 && <div style={{ position: 'absolute', top: 14, left: '50%', right: '-50%', height: 2, background: i < detail.steps ? 'var(--accent-1)' : 'var(--line)', zIndex: 0 }} />}
                        <div style={{
                          width: 30, height: 30, borderRadius: 999, margin: '0 auto', position: 'relative', zIndex: 1,
                          background: done ? 'var(--accent-1)' : 'var(--bg-3)',
                          border: '.5px solid', borderColor: done ? 'var(--accent-1)' : 'var(--line)',
                          display: 'grid', placeItems: 'center', color: done ? '#0A0A0F' : 'var(--txt-3)', fontSize: 13, fontWeight: 600,
                          boxShadow: current ? '0 0 16px rgba(82,242,15,.6)' : 'none',
                        }}>{done ? '✓' : i + 1}</div>
                        <div style={{ marginTop: 8, fontSize: 11, color: done ? 'var(--txt-1)' : 'var(--txt-3)', fontWeight: current ? 600 : 400 }}>{s}</div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Tracking */}
            <div style={{ marginTop: 24, padding: 16, background: 'var(--bg-2)', borderRadius: 10, border: '.5px solid var(--line)' }}>
              <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', marginBottom: 6 }}>TRACKING NUMBER</div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
                <code className="mono" style={{ fontSize: 14, color: 'var(--accent-1)' }}>{detail.tracking}</code>
                <button onClick={() => { navigator.clipboard?.writeText(detail.tracking); toast('Tracking copiat'); }} className="btn btn-glass btn-sm">Copiază</button>
              </div>
            </div>

            {/* Adresa */}
            <div style={{ marginTop: 16, padding: 16, background: 'var(--bg-2)', borderRadius: 10, border: '.5px solid var(--line)' }}>
              <div className="mono" style={{ fontSize: 11, color: 'var(--txt-3)', marginBottom: 6 }}>ADRESĂ LIVRARE</div>
              <div style={{ fontSize: 14, lineHeight: 1.6 }}>
                {user?.name || 'Andra Mihăescu'}<br/>
                Str. Polonă 38, Sector 1<br/>
                București, 010494, România<br/>
                <span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>+40 723 456 789</span>
              </div>
            </div>

            {detail.status === 'Expediată' && (
              <div style={{ marginTop: 16, padding: 12, background: 'rgba(255,215,0,.06)', borderRadius: 10, border: '.5px solid rgba(255,215,0,.25)', fontSize: 13 }}>
                <strong>📅 Livrare estimată:</strong> 22-24 aprilie 2026
              </div>
            )}

            <div style={{ marginTop: 24, display: 'flex', gap: 12 }}>
              <button className="btn btn-glass" style={{ flex: 1 }} onClick={() => { onNav('contact'); }}>Contactează suport</button>
              <button className="btn btn-primary" style={{ flex: 1 }} onClick={() => { setDetail(null); onNav('shop'); }}>Răscumpără din nou →</button>
            </div>
          </div>
        </div>
      )}

      {Toast}
      <style>{`
        @media (max-width: 1100px) { .ord-stats { grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

window.OrdersPage = OrdersPage;
