// admin-products.jsx — Gestionare produse

const { useState: useStateAP } = React;

const ADM_PRODUCTS = [
  { id: 1, name: 'iPhone 15 Pro 256GB', cat: 'Tehnologie', pts: 850, stock: 3, sold: 47, status: 'Activ', g1: '#1f2937', g2: '#52F20F' },
  { id: 2, name: 'AirPods Pro 2', cat: 'Tehnologie', pts: 220, stock: 24, sold: 89, status: 'Activ', g1: '#0E0E0E', g2: '#FFD700' },
  { id: 3, name: 'Weekend Maldive', cat: 'Călătorii', pts: 1200, stock: 3, sold: 12, status: 'Activ', g1: '#FFD700', g2: '#52F20F' },
  { id: 4, name: 'Geantă Louis Vuitton', cat: 'Modă', pts: 680, stock: 2, sold: 18, status: 'Activ', g1: '#3a2410', g2: '#FFD700' },
  { id: 5, name: 'PS5 Slim', cat: 'Tehnologie', pts: 380, stock: 18, sold: 64, status: 'Activ', g1: '#101820', g2: '#52F20F' },
  { id: 6, name: 'Pachet Dior Premium', cat: 'Cosmetice', pts: 145, stock: 32, sold: 121, status: 'Activ', g1: '#1a0f0c', g2: '#FFD700' },
  { id: 7, name: 'Cină Michelin București', cat: 'Experiențe', pts: 90, stock: 50, sold: 47, status: 'Activ', g1: '#0E0E0E', g2: '#52F20F' },
  { id: 8, name: 'Sneakers Off-White', cat: 'Modă', pts: 240, stock: 0, sold: 32, status: 'Stoc epuizat', g1: '#1a1a1a', g2: '#FFD700' },
  { id: 9, name: 'MacBook Air M3', cat: 'Tehnologie', pts: 1450, stock: 1, sold: 4, status: 'Activ', g1: '#0E0E0E', g2: '#52F20F' },
  { id: 10, name: 'City Break Roma', cat: 'Călătorii', pts: 480, stock: 8, sold: 21, status: 'Activ', g1: '#3a1f1a', g2: '#FFD700' },
  { id: 11, name: 'Apple Watch SE (Draft)', cat: 'Tehnologie', pts: 350, stock: 12, sold: 0, status: 'Inactiv', g1: '#1a1a1a', g2: '#52F20F' },
  { id: 12, name: 'Concert Untold VIP', cat: 'Experiențe', pts: 350, stock: 4, sold: 28, status: 'Activ', g1: '#1a0a2a', g2: '#52F20F' },
];

function AdminProductsPage({ onNav, user }) {
  const adminUser = { name: user?.name || 'Andrei Popescu' };
  const [view, setView] = useStateAP('grid');
  const [q, setQ] = useStateAP('');
  const [catF, setCatF] = useStateAP('Toate');
  const [statusF, setStatusF] = useStateAP('Toate');
  const [editing, setEditing] = useStateAP(null);
  const [Toast, toast] = useToast();

  let list = ADM_PRODUCTS;
  if (q) list = list.filter(p => p.name.toLowerCase().includes(q.toLowerCase()));
  if (catF !== 'Toate') list = list.filter(p => p.cat === catF);
  if (statusF !== 'Toate') list = list.filter(p => p.status === statusF);

  const totalActive = ADM_PRODUCTS.filter(p => p.status === 'Activ').length;
  const totalSales = ADM_PRODUCTS.reduce((s, p) => s + p.sold, 0);

  return (
    <div className="page" style={{ display: 'grid', gridTemplateColumns: '260px 1fr', minHeight: '100vh', background: 'linear-gradient(135deg, #0A0A0F, #0E0E0E)' }}>
      <DashSidebar active="admin-products" 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 · PRODUSE</span>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 16, marginBottom: 24 }}>
          <div>
            <h1 className="display" style={{ fontSize: 32, margin: 0 }}>Magazin Cadouri 4U</h1>
            <p style={{ fontSize: 14, color: 'var(--txt-2)', marginTop: 4 }}>{ADM_PRODUCTS.length} produse în catalog · {totalActive} active · {totalSales} vânzări totale</p>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-glass btn-sm">↑ Importă CSV</button>
            <button className="btn btn-primary btn-sm" onClick={() => setEditing({ isNew: true })}>+ Adaugă produs nou</button>
          </div>
        </div>

        <div className="card" style={{ padding: 16, marginBottom: 16, display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
          <input value={q} onChange={(e) => setQ(e.target.value)} className="input" placeholder="🔍 Caută produs..." style={{ flex: 1, minWidth: 220, height: 36 }} />
          <select value={catF} onChange={(e) => setCatF(e.target.value)} className="input" style={{ width: 'auto', height: 36 }}>
            {['Toate', 'Tehnologie', 'Modă', 'Călătorii', 'Experiențe', 'Cosmetice'].map(c => <option key={c}>{c}</option>)}
          </select>
          <select value={statusF} onChange={(e) => setStatusF(e.target.value)} className="input" style={{ width: 'auto', height: 36 }}>
            {['Toate', 'Activ', 'Inactiv', 'Stoc epuizat'].map(s => <option key={s}>{s}</option>)}
          </select>
          <div style={{ display: 'flex', gap: 4, padding: 3, background: 'var(--bg-2)', borderRadius: 8, border: '.5px solid var(--line)' }}>
            <button onClick={() => setView('grid')} className="btn btn-sm" style={{ background: view === 'grid' ? 'var(--accent-1)' : 'transparent', color: view === 'grid' ? '#0A0A0F' : 'var(--txt-2)', border: 0 }}>⊞ Grid</button>
            <button onClick={() => setView('table')} className="btn btn-sm" style={{ background: view === 'table' ? 'var(--accent-1)' : 'transparent', color: view === 'table' ? '#0A0A0F' : 'var(--txt-2)', border: 0 }}>≡ Tabel</button>
          </div>
        </div>

        {view === 'grid' ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }} className="adm-prod-grid">
            {list.map(p => <AdmProductCard key={p.id} p={p} onEdit={() => setEditing(p)} toast={toast} />)}
            <style>{`
              @media (max-width: 1200px) { .adm-prod-grid { grid-template-columns: repeat(3, 1fr) !important; } }
              @media (max-width: 900px) { .adm-prod-grid { grid-template-columns: 1fr 1fr !important; } }
            `}</style>
          </div>
        ) : (
          <AdmProductsTable list={list} setEditing={setEditing} />
        )}

        {/* Stats footer */}
        <div style={{ marginTop: 32, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }} className="adm-prod-stats">
          {[
            ['Total produse', ADM_PRODUCTS.length],
            ['Active', totalActive],
            ['Vânzări lună', totalSales],
            ['Cea mai populară', 'Cosmetice'],
          ].map(([l, v], i) => (
            <div key={i} style={{ padding: 16, background: 'var(--bg-2)', borderRadius: 12, border: '.5px solid var(--line)' }}>
              <div className="display mono" style={{ fontSize: 22, color: 'var(--accent-2)' }}>{v}</div>
              <div style={{ fontSize: 12, color: 'var(--txt-2)', marginTop: 4 }}>{l}</div>
            </div>
          ))}
          <style>{`@media (max-width: 900px) { .adm-prod-stats { grid-template-columns: 1fr 1fr !important; } }`}</style>
        </div>
      </main>

      {editing && <ProductEditor product={editing} onClose={() => setEditing(null)} toast={toast} />}
      {Toast}
    </div>
  );
}

function AdmProductCard({ p, onEdit, toast }) {
  const [menuOpen, setMenuOpen] = useStateAP(false);
  const lowStock = p.stock > 0 && p.stock < 5;
  const sColor = p.status === 'Activ' ? '#52F20F' : p.status === 'Stoc epuizat' ? '#ef4444' : 'var(--txt-3)';
  return (
    <div className="card" style={{ padding: 0, overflow: 'hidden', position: 'relative' }}>
      <div style={{ height: 160, background: `linear-gradient(135deg, ${p.g1}, ${p.g2})`, position: 'relative' }}>
        <div style={{ position: 'absolute', top: 10, left: 10, display: 'flex', gap: 6 }}>
          <span className="pill" style={{ fontSize: 9, background: 'rgba(0,0,0,.5)', borderColor: 'rgba(255,255,255,.2)' }}>{p.cat}</span>
          <span className="pill" style={{ fontSize: 9, color: sColor, borderColor: sColor + '60', background: 'rgba(0,0,0,.5)' }}>● {p.status}</span>
        </div>
        <div style={{ position: 'absolute', top: 10, right: 10 }}>
          <button onClick={(e) => { e.stopPropagation(); setMenuOpen(!menuOpen); }} className="btn btn-glass btn-sm" style={{ padding: '4px 8px' }}>⋯</button>
          {menuOpen && (
            <div style={{ position: 'absolute', top: 32, right: 0, background: 'var(--bg-1)', border: '.5px solid var(--line)', borderRadius: 8, padding: 4, minWidth: 140, zIndex: 10, boxShadow: '0 12px 32px rgba(0,0,0,.5)' }}>
              <button onClick={() => { onEdit(); setMenuOpen(false); }} className="btn btn-sm" style={{ width: '100%', justifyContent: 'flex-start', background: 'transparent', border: 0, color: 'var(--txt-1)', textAlign: 'left' }}>✏ Editează</button>
              <button onClick={() => { toast('Produs duplicat'); setMenuOpen(false); }} className="btn btn-sm" style={{ width: '100%', justifyContent: 'flex-start', background: 'transparent', border: 0, color: 'var(--txt-1)', textAlign: 'left' }}>⎘ Duplică</button>
              <button onClick={() => { toast('Produs dezactivat'); setMenuOpen(false); }} className="btn btn-sm" style={{ width: '100%', justifyContent: 'flex-start', background: 'transparent', border: 0, color: 'var(--txt-1)', textAlign: 'left' }}>○ Dezactivează</button>
              <button onClick={() => { toast('Produs șters'); setMenuOpen(false); }} className="btn btn-sm" style={{ width: '100%', justifyContent: 'flex-start', background: 'transparent', border: 0, color: '#ef4444', textAlign: 'left' }}>🗑 Șterge</button>
            </div>
          )}
        </div>
      </div>
      <div style={{ padding: 14 }}>
        <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 8 }}>{p.name}</div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span className="mono" style={{ fontSize: 13, color: 'var(--accent-1)' }}>💎 {p.pts}</span>
          <span style={{ fontSize: 11, color: lowStock ? '#ef4444' : 'var(--txt-3)' }}>
            {lowStock && '⚠ '}Stoc: {p.stock}
          </span>
        </div>
        <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', marginTop: 6 }}>{p.sold} vândute</div>
      </div>
    </div>
  );
}

function AdmProductsTable({ list, setEditing }) {
  return (
    <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, minWidth: 900 }}>
          <thead style={{ background: 'var(--bg-2)' }}>
            <tr>
              <th style={th(60)}></th>
              <th style={th()}>Nume</th>
              <th style={th(120)}>Categorie</th>
              <th style={th(90)}>Preț (pts)</th>
              <th style={th(80)}>Stoc</th>
              <th style={th(90)}>Vânzări</th>
              <th style={th(110)}>Status</th>
              <th style={th(80)}></th>
            </tr>
          </thead>
          <tbody>
            {list.map(p => (
              <tr key={p.id} className="hov" style={{ borderTop: '.5px solid var(--line-soft)' }}>
                <td style={td()}><div style={{ width: 40, height: 40, borderRadius: 8, background: `linear-gradient(135deg, ${p.g1}, ${p.g2})` }} /></td>
                <td style={{ ...td(), fontWeight: 500 }}>{p.name}</td>
                <td style={{ ...td(), color: 'var(--txt-2)' }}>{p.cat}</td>
                <td style={{ ...td(), fontFamily: 'JetBrains Mono', color: 'var(--accent-1)' }}>💎 {p.pts}</td>
                <td style={{ ...td(), color: p.stock < 5 ? '#ef4444' : 'var(--txt-2)' }}>{p.stock}</td>
                <td style={{ ...td(), color: 'var(--txt-2)' }}>{p.sold}</td>
                <td style={td()}><span style={{ fontSize: 11, color: p.status === 'Activ' ? 'var(--accent-1)' : p.status === 'Stoc epuizat' ? '#ef4444' : 'var(--txt-3)' }}>● {p.status}</span></td>
                <td style={td()}><button onClick={() => setEditing(p)} className="btn btn-glass btn-sm" style={{ padding: '4px 10px' }}>Edit</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ProductEditor({ product, onClose, toast }) {
  const isNew = product.isNew;
  const [tags, setTags] = useStateAP(product.tags || ['Premium']);
  const [tagInput, setTagInput] = useStateAP('');
  const [specs, setSpecs] = useStateAP([{ k: 'Garanție', v: '24 luni' }, { k: 'Origine', v: 'Apple Italia' }]);
  const [status, setStatus] = useStateAP(product.status || 'Activ');
  const [seoOpen, setSeoOpen] = useStateAP(false);

  const addTag = () => { if (tagInput.trim()) { setTags([...tags, tagInput.trim()]); setTagInput(''); } };
  const addSpec = () => setSpecs([...specs, { k: '', v: '' }]);

  return (
    <div onClick={onClose} 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: 760, width: '100%', maxHeight: '90vh', overflowY: 'auto', padding: 28 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
          <div>
            <span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>● {isNew ? 'PRODUS NOU' : 'EDITARE PRODUS'}</span>
            <div className="display" style={{ fontSize: 24, marginTop: 4 }}>{isNew ? 'Adaugă produs' : product.name}</div>
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: 0, fontSize: 24, color: 'var(--txt-2)', cursor: 'pointer' }}>×</button>
        </div>

        {/* Imagini */}
        <Section title="Imagini">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8 }}>
            {[0, 1, 2, 3, 4].map(i => (
              <div key={i} style={{
                aspectRatio: '1', borderRadius: 8, border: i === 0 ? '1px solid var(--accent-1)' : '1px dashed var(--line)',
                background: i < 2 ? `linear-gradient(135deg, ${product.g1 || '#1a1a1a'}, ${product.g2 || '#52F20F'})` : 'var(--bg-2)',
                display: 'grid', placeItems: 'center', position: 'relative', cursor: 'pointer',
              }}>
                {i === 0 && <span className="pill" style={{ fontSize: 8, position: 'absolute', top: 4, left: 4, background: 'var(--accent-1)', color: '#000', borderColor: 'transparent' }}>PRINCIPAL</span>}
                {i >= 2 && <span style={{ fontSize: 18, color: 'var(--txt-3)' }}>+</span>}
              </div>
            ))}
          </div>
          <p className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', marginTop: 8 }}>Drag & drop sau click. Max 5 imagini. Trage pentru reorder.</p>
        </Section>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <FieldP label="Titlu produs" placeholder="ex: iPhone 15 Pro" defaultValue={product.name} />
          <FieldP label="Slug URL" placeholder="iphone-15-pro" prefix="/shop/" />
          <FieldP label="Categorie" type="select" options={['Tehnologie', 'Modă', 'Călătorii', 'Experiențe', 'Cosmetice', 'Altceva']} defaultValue={product.cat} />
          <FieldP label="Preț în puncte 4U" type="number" prefix="💎 " defaultValue={product.pts} />
          <FieldP label="Echivalent RON" type="number" prefix="RON " placeholder="Opțional" />
          <FieldP label="Stoc disponibil" type="number" defaultValue={product.stock} />
          <FieldP label="Greutate (kg)" type="number" placeholder="0.5" />
          <FieldP label="Dimensiuni (cm)" placeholder="20 x 10 x 5" />
        </div>

        <div style={{ marginTop: 16 }}>
          <FieldP label="Descriere scurtă" type="textarea" placeholder="1-2 propoziții, max 200 chars" maxLength={200} small />
        </div>

        <Section title="Descriere completă">
          <div style={{ border: '.5px solid var(--line)', borderRadius: 8, background: 'var(--bg-2)' }}>
            <div style={{ padding: 8, borderBottom: '.5px solid var(--line)', display: 'flex', gap: 4 }}>
              {['B', 'I', 'U', '≡', '•', '🔗'].map(b => (
                <button key={b} className="btn btn-glass btn-sm" style={{ padding: '2px 8px', fontSize: 11, fontWeight: 600 }}>{b}</button>
              ))}
            </div>
            <textarea style={{ width: '100%', minHeight: 100, padding: 12, background: 'transparent', border: 0, color: 'var(--txt-1)', resize: 'vertical', fontFamily: 'inherit', fontSize: 13 }} placeholder="Descriere completă produs..." />
          </div>
        </Section>

        <Section title="Specificații">
          {specs.map((s, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 32px', gap: 8, marginBottom: 6 }}>
              <input className="input" placeholder="Cheie" defaultValue={s.k} style={{ height: 34 }} />
              <input className="input" placeholder="Valoare" defaultValue={s.v} style={{ height: 34 }} />
              <button onClick={() => setSpecs(specs.filter((_, j) => j !== i))} className="btn btn-glass btn-sm" style={{ padding: '4px 8px' }}>×</button>
            </div>
          ))}
          <button onClick={addSpec} className="btn btn-glass btn-sm">+ Adaugă specificație</button>
        </Section>

        <Section title="Tags">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 8 }}>
            {tags.map((t, i) => (
              <span key={i} className="pill" style={{ background: 'rgba(255,215,0,.08)', borderColor: 'rgba(255,215,0,.3)', color: 'var(--accent-2)', fontSize: 11 }}>
                {t} <button onClick={() => setTags(tags.filter((_, j) => j !== i))} style={{ background: 'transparent', border: 0, color: 'inherit', marginLeft: 4, cursor: 'pointer' }}>×</button>
              </span>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <input value={tagInput} onChange={(e) => setTagInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && addTag()} className="input" placeholder='ex: "Nou", "Stoc limitat"' style={{ height: 34 }} />
            <button onClick={addTag} className="btn btn-glass btn-sm">+</button>
          </div>
        </Section>

        <Section title="Status">
          <div style={{ display: 'flex', gap: 8 }}>
            {['Activ', 'Inactiv', 'Draft'].map(s => (
              <button key={s} onClick={() => setStatus(s)} className="btn btn-sm" style={{
                background: status === s ? 'var(--accent-1)' : 'transparent',
                color: status === s ? '#0A0A0F' : 'var(--txt-2)',
                border: status === s ? 'none' : '.5px solid var(--line)',
              }}>{s}</button>
            ))}
          </div>
        </Section>

        <button onClick={() => setSeoOpen(!seoOpen)} className="btn btn-glass btn-sm" style={{ marginTop: 12, width: '100%', justifyContent: 'space-between' }}>
          <span>SEO {seoOpen ? '▴' : '▾'}</span>
        </button>
        {seoOpen && (
          <div style={{ marginTop: 8, padding: 14, background: 'var(--bg-2)', borderRadius: 8 }}>
            <FieldP label="Meta title" placeholder="Titlu pentru Google" />
            <div style={{ marginTop: 8 }}><FieldP label="Meta description" type="textarea" placeholder="Descriere SEO" small /></div>
            <div style={{ marginTop: 8 }}><FieldP label="OG Image URL" placeholder="https://..." /></div>
          </div>
        )}

        <div style={{ display: 'flex', gap: 8, marginTop: 24 }}>
          <button className="btn btn-glass" style={{ flex: 1 }} onClick={onClose}>Anulează</button>
          <button className="btn btn-glass" style={{ flex: 1 }} onClick={() => { toast('Salvat ca draft'); onClose(); }}>Salvează ca draft</button>
          <button className="btn btn-primary" style={{ flex: 2 }} onClick={() => { toast(isNew ? 'Produs adăugat' : 'Modificări salvate'); onClose(); }}>{isNew ? 'Publică' : 'Salvează'}</button>
        </div>
      </div>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div style={{ marginTop: 16 }}>
      <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 8 }}>{title.toUpperCase()}</div>
      {children}
    </div>
  );
}

function FieldP({ label, type = 'text', placeholder, defaultValue, prefix, options, maxLength, small }) {
  return (
    <div>
      <label className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', display: 'block', marginBottom: 6 }}>{label.toUpperCase()}</label>
      {type === 'select' ? (
        <select className="input" style={{ height: 38 }} defaultValue={defaultValue}>{options.map(o => <option key={o}>{o}</option>)}</select>
      ) : type === 'textarea' ? (
        <textarea className="input" style={{ minHeight: small ? 60 : 100, padding: 10, resize: 'vertical' }} placeholder={placeholder} maxLength={maxLength} defaultValue={defaultValue} />
      ) : prefix ? (
        <div style={{ display: 'flex', alignItems: 'center', background: 'var(--bg-2)', border: '.5px solid var(--line)', borderRadius: 8, paddingLeft: 12 }}>
          <span className="mono" style={{ fontSize: 13, color: 'var(--txt-3)' }}>{prefix}</span>
          <input type={type} className="input" style={{ border: 0, background: 'transparent', height: 36 }} placeholder={placeholder} defaultValue={defaultValue} />
        </div>
      ) : (
        <input type={type} className="input" style={{ height: 38 }} placeholder={placeholder} defaultValue={defaultValue} />
      )}
    </div>
  );
}

window.AdminProductsPage = AdminProductsPage;
