// screens/Categories.jsx — Category management list + details/edit drawer.

const CATEGORIES_DATA = [
  { id:'WM-8421', name:'Tapis & Textile',     glyph:'shirt',         qty:120, earnings: 248300, status:'Actif',   featured:true,  created:'16 janv. 2026', updated:'il y a 2 jours', avgPrice: 2840, avgMargin: 38, sales: 4283, returnRate: 1.3 },
  { id:'UC-3990', name:'Cosmétique & Bien-être',glyph:'flask-conical',qty:245,earnings:1011000, status:'Actif',   featured:false, created:'12 déc. 2025',  updated:'il y a 5 jours', avgPrice:  189, avgMargin: 52, sales: 5340, returnRate: 0.8 },
  { id:'KB-8820', name:'Décoration & Maison',  glyph:'lamp',          qty:560, earnings: 594765, status:'Inactif', featured:false, created:'02 oct. 2025',  updated:'il y a 1 mois', avgPrice:  680, avgMargin: 42, sales: 1840, returnRate: 2.1 },
  { id:'LS-1033', name:'Électronique',         glyph:'cpu',           qty: 98, earnings:1023699, status:'Actif',   featured:true,  created:'18 août 2025',  updated:'aujourd\u2019hui',avgPrice: 2890, avgMargin: 22, sales:  928, returnRate: 3.4 },
  { id:'WC-5510', name:'Artisanat Marocain',   glyph:'flame',         qty: 33, earnings:  92900, status:'Actif',   featured:true,  created:'05 juill. 2025',updated:'il y a 3 jours', avgPrice:  450, avgMargin: 58, sales:  680, returnRate: 0.4 },
  { id:'GH-7312', name:'Mode & Caftan',        glyph:'shirt',         qty:140, earnings: 165900, status:'Inactif', featured:false, created:'22 mai 2025',   updated:'il y a 2 mois', avgPrice: 1240, avgMargin: 45, sales:  342, returnRate: 1.9 },
  { id:'UH-2300', name:'Services Digitaux',    glyph:'cloud',         qty:150, earnings: 707200, status:'Actif',   featured:true,  created:'14 mars 2025',  updated:'hier',           avgPrice:  780, avgMargin: 72, sales: 2148, returnRate: 0.0 },
  { id:'MS-8702', name:'Agroalimentaire',      glyph:'wheat',         qty: 65, earnings: 371190, status:'Actif',   featured:false, created:'09 févr. 2025', updated:'il y a 1 sem.', avgPrice:  240, avgMargin: 31, sales: 1542, returnRate: 1.1 },
  { id:'BS-6112', name:'Mobilier & Tapisserie',glyph:'armchair',      qty: 55, earnings:  49875, status:'Actif',   featured:true,  created:'28 janv. 2025', updated:'il y a 4 jours', avgPrice: 1820, avgMargin: 39, sales:  248, returnRate: 2.4 },
  { id:'HC-9031', name:'Sport & Outdoor',      glyph:'mountain',      qty:820, earnings:2304400, status:'Actif',   featured:true,  created:'11 janv. 2025', updated:'il y a 6 jours', avgPrice:  340, avgMargin: 28, sales: 6240, returnRate: 1.6 },
];

function Categories() {
  const [list, setList] = React.useState(CATEGORIES_DATA);
  const [search, setSearch] = React.useState('');
  const [selected, setSelected] = React.useState(null);
  const [editing, setEditing] = React.useState(false);
  const [checked, setChecked] = React.useState(new Set());

  const filtered = list.filter(c => search==='' || c.name.toLowerCase().includes(search.toLowerCase()) || c.id.toLowerCase().includes(search.toLowerCase()));
  const toggleFeatured = (id) => setList(l => l.map(c => c.id===id ? {...c, featured:!c.featured} : c));
  const toggleCheck = (id) => setChecked(s => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n; });

  const inactiveCount = list.filter(c => c.status==='Inactif').length;
  const inactivePct = Math.round((inactiveCount/list.length)*100);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1>Catégories</h1>
          <div className="sub">{list.length} catégories trouvées. {inactivePct}% nécessitent votre attention.</div>
        </div>
        <div className="spacer"></div>
        <button className="btn btn-ghost"><i data-lucide="download" style={{width:14,height:14}}></i> Export CSV</button>
        <button className="btn btn-warm" onClick={()=>{ setSelected({ id:'', name:'', glyph:'package', qty:0, earnings:0, status:'Actif', featured:false, created:'aujourd\u2019hui', updated:'maintenant', avgPrice:0, avgMargin:0, sales:0, returnRate:0 }); setEditing(true); }}>
          <i data-lucide="plus" style={{width:14,height:14}}></i> Ajouter une catégorie
        </button>
      </div>

      <Widget>
        <div style={{ display:'flex', gap:10, marginBottom:18, flexWrap:'wrap', alignItems:'center' }}>
          <div style={{ position:'relative', flex:'1 1 280px', minWidth:240 }}>
            <i data-lucide="search" style={{ position:'absolute', left:12, top:11, width:14, height:14, color:'var(--app-text-4)' }}></i>
            <input className="input" placeholder="Rechercher une catégorie…" value={search} onChange={e=>setSearch(e.target.value)} style={{ paddingLeft:34 }} />
          </div>
          {checked.size > 0 && (
            <>
              <span style={{ font:'600 12px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>{checked.size} sélectionnée(s)</span>
              <button className="btn btn-ghost"><i data-lucide="archive" style={{width:14,height:14}}></i> Archiver</button>
              <button className="btn btn-ghost" style={{ color:'#F8285A' }}><i data-lucide="trash-2" style={{width:14,height:14}}></i> Supprimer</button>
            </>
          )}
          <div style={{ flex:1 }}></div>
          <button className="btn btn-ghost"><i data-lucide="filter" style={{width:14,height:14}}></i> Filtres</button>
        </div>

        <table className="m-table">
          <thead><tr>
            <th style={{width:40}}><input type="checkbox" /></th>
            <th>Catégorie</th>
            <th style={{textAlign:'right'}}>Produits</th>
            <th style={{textAlign:'right'}}>CA total</th>
            <th>Statut</th>
            <th style={{textAlign:'center'}}>Mise en avant</th>
            <th></th>
          </tr></thead>
          <tbody>
            {filtered.map(c => (
              <tr key={c.id} onClick={()=>{ setSelected(c); setEditing(false); }} style={{ cursor:'pointer' }}>
                <td onClick={e=>e.stopPropagation()}>
                  <input type="checkbox" checked={checked.has(c.id)} onChange={()=>toggleCheck(c.id)} />
                </td>
                <td style={{ color:'var(--app-text)', fontWeight:700 }}>
                  <div style={{ display:'flex', alignItems:'center', gap:12 }}>
                    <div style={{ width:40, height:40, borderRadius:9, background:'var(--app-warm-soft)', color:'#C2410C', display:'grid', placeItems:'center' }}>
                      <i data-lucide={c.glyph} style={{ width:18, height:18 }}></i>
                    </div>
                    <div style={{ display:'flex', flexDirection:'column', gap:3 }}>
                      <span>{c.name}</span>
                      <span style={{ font:'500 11px/1 var(--m-font-mono)', color:'var(--app-text-3)' }}>ID · {c.id}</span>
                    </div>
                  </div>
                </td>
                <td style={{ textAlign:'right', color:'var(--app-text)', fontWeight:600 }}>{fmtNumber(c.qty)}</td>
                <td style={{ textAlign:'right', color:'var(--app-text)', fontWeight:700 }}>{fmtMAD(c.earnings, {compact:true})}</td>
                <td><StatusBadge status={c.status} /></td>
                <td style={{ textAlign:'center' }} onClick={e=>e.stopPropagation()}>
                  <input type="checkbox" checked={c.featured} onChange={()=>toggleFeatured(c.id)} style={{ accentColor:'#C2410C', width:16, height:16 }} />
                </td>
                <td onClick={e=>e.stopPropagation()} style={{ textAlign:'right' }}>
                  <div style={{ display:'inline-flex', gap:4 }}>
                    <button className="btn btn-ghost btn-icon" style={{ height:30, width:30 }} onClick={()=>{ setSelected(c); setEditing(false); }}><i data-lucide="eye" style={{width:14,height:14}}></i></button>
                    <button className="btn btn-ghost btn-icon" style={{ height:30, width:30 }} onClick={()=>{ setSelected(c); setEditing(true); }}><i data-lucide="edit-3" style={{width:14,height:14}}></i></button>
                    <button className="btn btn-ghost btn-icon" style={{ height:30, width:30, color:'#F8285A' }}><i data-lucide="trash-2" style={{width:14,height:14}}></i></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        <footer style={{ display:'flex', alignItems:'center', marginTop:18, font:'500 12px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>
          <span>1-{filtered.length} sur {list.length} catégories</span>
          <div style={{ flex:1 }}></div>
          <div style={{ display:'flex', gap:6 }}>
            {['‹','1','2','3','›'].map((p,i)=>(
              <button key={i} style={{
                width:32, height:32, border:'1px solid '+(p==='1'?'var(--app-warm)':'var(--app-border)'),
                background: p==='1'?'var(--app-warm)':'var(--app-surface)', color: p==='1'?'#fff':'var(--app-text-2)',
                borderRadius:6, font:'600 12px/1 var(--m-font-sans)'
              }}>{p}</button>
            ))}
          </div>
        </footer>
      </Widget>

      {selected && <CategoryDrawer category={selected} editing={editing} onEdit={()=>setEditing(true)} onClose={()=>{ setSelected(null); setEditing(false); }} onSave={(updated)=>{
        setList(l => {
          const exists = l.find(x=>x.id===updated.id);
          return exists ? l.map(x=>x.id===updated.id?updated:x) : [{...updated, id: updated.id || `NEW-${Date.now().toString(36).slice(-4).toUpperCase()}`}, ...l];
        });
        setSelected(null); setEditing(false);
      }} />}
    </div>
  );
}

function CategoryDrawer({ category, editing, onClose, onSave, onEdit }) {
  const [form, setForm] = React.useState({ ...category });
  React.useEffect(()=>{ setForm({ ...category }); }, [category.id, editing]);

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, zIndex:40, background:'rgba(7,20,55,.32)', display:'flex', justifyContent:'flex-end' }}>
      <div onClick={e=>e.stopPropagation()} className="card" style={{
        width:680, height:'100%', borderRadius:0, borderRight:0, borderTop:0, borderBottom:0,
        borderLeft:'1px solid var(--app-border)', overflowY:'auto', padding:0
      }}>
        <div style={{ padding:'18px 24px', display:'flex', alignItems:'center', borderBottom:'1px solid var(--app-border)' }}>
          <div style={{ font:'700 15px/1 var(--m-font-sans)', color:'var(--app-text)' }}>
            {editing ? (form.id ? 'Modifier la catégorie' : 'Nouvelle catégorie') : 'Détails de la catégorie'}
          </div>
          <div style={{ flex:1 }}></div>
          <button className="btn btn-ghost btn-icon" onClick={onClose}><i data-lucide="x" style={{width:16,height:16}}></i></button>
        </div>

        <div style={{ padding:'20px 24px 0' }}>
          <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:6 }}>
            <h2 style={{ margin:0, font:'700 22px/1.1 var(--m-font-sans)', color:'var(--app-text)', letterSpacing:'-.02em' }}>{form.name || 'Sans nom'}</h2>
            <StatusBadge status={form.status} />
          </div>
          <div style={{ font:'500 12px/1 var(--m-font-sans)', color:'var(--app-text-3)', display:'flex', gap:14, flexWrap:'wrap' }}>
            <span>ID · <span style={{ color:'var(--app-text-2)', fontFamily:'var(--m-font-mono)' }}>{form.id || '—'}</span></span>
            <span>Créé · <span style={{ color:'var(--app-text-2)' }}>{form.created}</span></span>
            <span>MAJ · <span style={{ color:'var(--app-text-2)' }}>{form.updated}</span></span>
          </div>
        </div>

        <div style={{ padding:'20px 24px', display:'grid', gridTemplateColumns:'1fr 240px', gap:20 }}>
          <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
            {/* Metrics */}
            <div className="card" style={{ padding:18 }}>
              <div style={{ font:'700 13px/1 var(--m-font-sans)', color:'var(--app-text)', marginBottom:14 }}>Métriques</div>
              <div style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:10 }}>
                {[
                  ['Quantité',     fmtNumber(form.qty)],
                  ['CA',           fmtMAD(form.earnings, {compact:true})],
                  ['Taux retour',  `${form.returnRate}%`],
                  ['Marge moy.',   `${form.avgMargin}%`],
                ].map(([l,v])=>(
                  <div key={l}>
                    <div className="eyebrow" style={{ fontSize:10 }}>{l}</div>
                    <div style={{ font:'700 16px/1 var(--m-font-sans)', color:'var(--app-text)', marginTop:6, letterSpacing:'-.01em' }}>{v}</div>
                  </div>
                ))}
              </div>
            </div>

            {/* Analytics */}
            <div className="card" style={{ padding:18 }}>
              <div style={{ font:'700 13px/1 var(--m-font-sans)', color:'var(--app-text)', marginBottom:14 }}>Analytique</div>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
                <div>
                  <div className="eyebrow" style={{ fontSize:10 }}>Prix moyen produit</div>
                  <div style={{ display:'flex', alignItems:'baseline', gap:6, marginTop:6 }}>
                    <span style={{ font:'700 18px/1 var(--m-font-sans)', color:'var(--app-text)', letterSpacing:'-.02em' }}>{fmtMAD(form.avgPrice, {compact:true})}</span>
                    <span className="pill" style={{ background:'rgba(25,199,129,.10)', color:'#19C781', height:18, padding:'0 6px', fontSize:10 }}>+3,5%</span>
                  </div>
                  <Sparkline color="#C2410C" />
                </div>
                <div>
                  <div className="eyebrow" style={{ fontSize:10 }}>Ventes catégorie</div>
                  <div style={{ display:'flex', alignItems:'baseline', gap:6, marginTop:6 }}>
                    <span style={{ font:'700 18px/1 var(--m-font-sans)', color:'var(--app-text)', letterSpacing:'-.02em' }}>{fmtNumber(form.sales)}</span>
                    <span className="pill" style={{ background:'rgba(25,199,129,.10)', color:'#19C781', height:18, padding:'0 6px', fontSize:10 }}>+4%</span>
                    <span style={{ font:'500 11px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>{fmtMAD(form.earnings, {compact:true})}</span>
                  </div>
                  <Sparkline color="#1379F0" />
                </div>
              </div>
            </div>

            {/* Items */}
            <div className="card" style={{ padding:18 }}>
              <div style={{ display:'flex', alignItems:'center', marginBottom:14 }}>
                <span style={{ font:'700 13px/1 var(--m-font-sans)', color:'var(--app-text)' }}>Produits de la catégorie</span>
                <div style={{ flex:1 }}></div>
                <a href="#/produits" style={{ font:'700 12px/1 var(--m-font-sans)', color:'var(--app-primary)' }}>Tout voir</a>
              </div>
              <table className="m-table">
                <thead><tr>
                  <th>Produit</th><th style={{textAlign:'right'}}>Ventes</th><th style={{textAlign:'right'}}>Mouv.</th>
                </tr></thead>
                <tbody>
                  {[
                    ['Tapis Berbère 200×300','TB-BO-200', 482300, '13 mai'],
                    ['Théière Émaillée Safi', 'TE-SF-12',  92300, '12 mai'],
                    ['Lanterne Marrakchi',   'LM-CU-22', 109750, '11 mai'],
                    ['Caftan Brodé Marine',  'CF-BM-MR',      0, '07 mai'],
                  ].map(([n,s,v,d])=>(
                    <tr key={s}>
                      <td>
                        <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                          <div style={{ width:28, height:28, borderRadius:6, background:'var(--app-warm-soft)' }}></div>
                          <div>
                            <div style={{ font:'600 12px/1.2 var(--m-font-sans)', color:'var(--app-text)' }}>{n}</div>
                            <div style={{ font:'500 11px/1 var(--m-font-mono)', color:'var(--app-text-3)', marginTop:3 }}>SKU · {s}</div>
                          </div>
                        </div>
                      </td>
                      <td style={{ textAlign:'right', color:'var(--app-text)', fontWeight:700 }}>{fmtMAD(v, {compact:true})}</td>
                      <td style={{ textAlign:'right', color:'var(--app-text-3)', font:'500 11px/1 var(--m-font-sans)' }}>{d}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Right column — edit panel */}
          <div className="card" style={{ padding:18, alignSelf:'flex-start' }}>
            <div style={{ height:120, borderRadius:9, background: 'var(--app-warm-soft)', display:'grid', placeItems:'center', color:'#C2410C', marginBottom:12 }}>
              <i data-lucide={form.glyph} style={{ width:48, height:48, strokeWidth:1.2 }}></i>
            </div>
            <button className="btn btn-ghost" style={{ width:'100%', justifyContent:'center', marginBottom:14 }} disabled={!editing}>
              <i data-lucide="upload" style={{width:14,height:14}}></i> Changer
            </button>

            <CatField label="Nom de la catégorie">
              <input className="input" value={form.name} disabled={!editing} onChange={e=>setForm({...form, name:e.target.value})} />
            </CatField>
            <div style={{ height:12 }}></div>
            <CatField label="Statut">
              <select className="input" value={form.status} disabled={!editing} onChange={e=>setForm({...form, status:e.target.value})}>
                <option>Actif</option><option>Inactif</option>
              </select>
            </CatField>
            <div style={{ height:12 }}></div>
            <CatField label="Description">
              <textarea className="input" rows={3} disabled={!editing} placeholder="Description de la catégorie…" style={{ height:80, padding:10, resize:'vertical' }}
                defaultValue={editing ? '' : 'Sélection de produits emblématiques de l\'artisanat marocain, sourcés directement auprès des coopératives partenaires.'} />
            </CatField>
            <div style={{ height:12 }}></div>
            <label style={{ display:'flex', alignItems:'center', gap:8, font:'600 12px/1 var(--m-font-sans)', color:'var(--app-text-2)' }}>
              <input type="checkbox" checked={form.featured} disabled={!editing} onChange={e=>setForm({...form, featured:e.target.checked})} style={{ accentColor:'#C2410C' }} />
              Mise en avant
            </label>
          </div>
        </div>

        {/* Footer */}
        <div style={{
          position:'sticky', bottom:0, background:'var(--app-surface)',
          borderTop:'1px solid var(--app-border)', padding:'14px 24px',
          display:'flex', alignItems:'center', gap:10
        }}>
          <div style={{ flex:1 }}></div>
          <button className="btn btn-ghost" onClick={onClose}>Fermer</button>
          {editing ? (
            <>
              <button className="btn btn-ghost" style={{ color:'#F8285A' }}><i data-lucide="trash-2" style={{width:14,height:14}}></i> Supprimer</button>
              <button className="btn btn-warm" onClick={()=>onSave(form)}><i data-lucide="check" style={{width:14,height:14}}></i> Enregistrer</button>
            </>
          ) : (
            <button className="btn btn-warm" onClick={onEdit}><i data-lucide="edit-3" style={{width:14,height:14}}></i> Modifier</button>
          )}
        </div>
      </div>
    </div>
  );
}

function Sparkline({ color = '#C2410C' }) {
  const data = Array.from({length:24}, ()=> 30 + Math.random()*60);
  const path = data.map((v,i)=>`${i?'L':'M'}${i*(200/(data.length-1))},${50-v*.5}`).join(' ');
  return (
    <svg viewBox="0 0 200 50" width="100%" height="42" style={{ marginTop:8, display:'block' }}>
      <defs>
        <linearGradient id={`spk-${color}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity=".22" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={`${path} L200,50 L0,50 Z`} fill={`url(#spk-${color})`} />
      <path d={path} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function CatField({ label, children }) {
  return (
    <div>
      <div style={{ font:'600 11px/1 var(--m-font-sans)', color:'var(--app-text-3)', textTransform:'uppercase', letterSpacing:'.06em', marginBottom:6 }}>{label}</div>
      {children}
    </div>
  );
}

Object.assign(window, { Categories });
