// screens/Produits.jsx — products grid (catalogue) + list view + detail drawer.

const PRODUCT_GRADIENTS = {
  'Textile':            'linear-gradient(135deg,#C2410C,#7C2D12)',
  'Artisanat':          'linear-gradient(135deg,#D97706,#92400E)',
  'Électronique':       'linear-gradient(135deg,#1379F0,#1E3A8A)',
  'Cosmétique':         'linear-gradient(135deg,#19C781,#065F46)',
  'Services digitaux':  'linear-gradient(135deg,#0F766E,#0F3D3A)',
  'Décoration':         'linear-gradient(135deg,#9747FF,#5B21B6)',
};

const PRODUCT_GLYPHS = {
  'Textile':'shirt','Artisanat':'flame','Électronique':'cpu','Cosmétique':'flask-conical','Services digitaux':'cloud','Décoration':'lamp',
};

function Produits() {
  const [view, setView] = React.useState('grid');
  const [cat, setCat] = React.useState('Toutes');
  const [search, setSearch] = React.useState('');
  const [selected, setSelected] = React.useState(null);
  const cats = ['Toutes', ...new Set(PRODUCTS.map(p=>p.cat))];

  const filtered = PRODUCTS.filter(p =>
    (cat==='Toutes' || p.cat===cat) &&
    (search==='' || p.name.toLowerCase().includes(search.toLowerCase()))
  );

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1>Produits & Catalogue</h1>
          <div className="sub">{PRODUCTS.length} produits · {new Set(PRODUCTS.map(p=>p.cat)).size} catégories</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"><i data-lucide="plus" style={{width:14,height:14}}></i> Nouveau produit</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 un produit, SKU…" value={search} onChange={e=>setSearch(e.target.value)} style={{ paddingLeft:34 }} />
          </div>
          <div style={{ display:'flex', gap:6 }}>
            {cats.map(c=>(
              <button key={c} onClick={()=>setCat(c)} style={{
                height:36, padding:'0 12px', borderRadius:8,
                border:'1px solid '+(cat===c?'var(--app-warm)':'var(--app-border)'),
                background: cat===c?'var(--app-warm-soft)':'var(--app-surface)',
                color: cat===c?'#C2410C':'var(--app-text-2)',
                font:'600 12px/1 var(--m-font-sans)'
              }}>{c}</button>
            ))}
          </div>
          <div style={{ flex:1 }}></div>
          <div style={{ display:'flex', padding:3, background:'var(--app-surface-2)', borderRadius:8, border:'1px solid var(--app-border)' }}>
            {[['grid','grid-3x3'],['list','list']].map(([k,ic])=>(
              <button key={k} onClick={()=>setView(k)} style={{
                width:32, height:30, borderRadius:6, display:'grid', placeItems:'center',
                background: view===k ? 'var(--app-surface)' : 'transparent',
                color: view===k ? 'var(--app-text)' : 'var(--app-text-3)',
                boxShadow: view===k ? '0 1px 2px rgba(0,0,0,.05)' : 'none'
              }}>
                <i data-lucide={ic} style={{ width:14, height:14 }}></i>
              </button>
            ))}
          </div>
        </div>

        {view === 'grid' && (
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(220px, 1fr))', gap:14 }}>
            {filtered.map(p => (
              <div key={p.id} onClick={()=>setSelected(p)} className="lift" style={{
                background:'var(--app-surface)', border:'1px solid var(--app-border)', borderRadius:10,
                padding:12, cursor:'pointer'
              }}>
                <div style={{
                  height:120, borderRadius:8, marginBottom:12,
                  background: PRODUCT_GRADIENTS[p.cat] || 'linear-gradient(135deg,#78829D,#4B5675)',
                  display:'grid', placeItems:'center', color:'#fff', position:'relative', overflow:'hidden'
                }}>
                  <i data-lucide={PRODUCT_GLYPHS[p.cat] || 'package'} style={{ width:36, height:36, opacity:.85, strokeWidth:1.4 }}></i>
                  <div style={{ position:'absolute', top:8, left:8 }}>
                    <StatusBadge status={p.status} />
                  </div>
                </div>
                <div style={{ font:'500 10px/1 var(--m-font-sans)', color:'var(--app-text-3)', marginBottom:6, letterSpacing:'.04em', textTransform:'uppercase' }}>{p.cat}</div>
                <div style={{ font:'700 13px/1.3 var(--m-font-sans)', color:'var(--app-text)', minHeight:34 }}>{p.name}</div>
                <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginTop:10 }}>
                  <span style={{ font:'700 14px/1 var(--m-font-sans)', color:'#C2410C' }}>{fmtMAD(p.price)}</span>
                  <span style={{ font:'500 11px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>{p.stock>=999?'∞':`Stock ${p.stock}`}</span>
                </div>
              </div>
            ))}
          </div>
        )}

        {view === 'list' && (
          <table className="m-table">
            <thead><tr>
              <th>Produit</th><th>SKU</th><th>Catégorie</th><th>Entrepôt</th><th>Stock</th><th>Statut</th><th style={{textAlign:'right'}}>Prix</th><th></th>
            </tr></thead>
            <tbody>
              {filtered.map(p=>(
                <tr key={p.id} onClick={()=>setSelected(p)} style={{ cursor:'pointer' }}>
                  <td style={{ color:'var(--app-text)', fontWeight:700 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:12 }}>
                      <div style={{ width:36, height:36, borderRadius:8, background: PRODUCT_GRADIENTS[p.cat], display:'grid', placeItems:'center', color:'#fff' }}>
                        <i data-lucide={PRODUCT_GLYPHS[p.cat] || 'package'} style={{ width:16, height:16 }}></i>
                      </div>
                      {p.name}
                    </div>
                  </td>
                  <td style={{ font:'500 12px/1 var(--m-font-mono)', color:'var(--app-text-3)' }}>{p.sku}</td>
                  <td>{p.cat}</td>
                  <td>{p.warehouse}</td>
                  <td style={{ color:'var(--app-text)', fontWeight:600 }}>{p.stock>=999?'∞':p.stock}</td>
                  <td><StatusBadge status={p.status} /></td>
                  <td style={{ textAlign:'right', color:'var(--app-text)', fontWeight:700 }}>{fmtMAD(p.price)}</td>
                  <td onClick={e=>e.stopPropagation()} style={{ textAlign:'right' }}>
                    <button className="btn btn-ghost btn-icon" style={{ height:30, width:30 }}><i data-lucide="more-horizontal" style={{width:14,height:14}}></i></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Widget>

      {selected && <ProductDetail product={selected} onClose={()=>setSelected(null)} />}
    </div>
  );
}

function ProductDetail({ product, onClose }) {
  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()} style={{
        width:520, height:'100%', background:'var(--app-surface)', borderLeft:'1px solid var(--app-border)', overflowY:'auto'
      }}>
        <div style={{
          height:220, background: PRODUCT_GRADIENTS[product.cat], display:'grid', placeItems:'center', color:'#fff', position:'relative'
        }}>
          <i data-lucide={PRODUCT_GLYPHS[product.cat] || 'package'} style={{ width:60, height:60, opacity:.9, strokeWidth:1.2 }}></i>
          <button className="btn btn-icon" onClick={onClose} style={{ position:'absolute', top:14, right:14, background:'rgba(255,255,255,.2)', color:'#fff' }}>
            <i data-lucide="x" style={{ width:16, height:16 }}></i>
          </button>
          <div style={{ position:'absolute', top:14, left:14 }}>
            <StatusBadge status={product.status} />
          </div>
        </div>

        <div style={{ padding:24, display:'flex', flexDirection:'column', gap:18 }}>
          <div>
            <div className="eyebrow">{product.cat}</div>
            <h2 style={{ margin:'8px 0 6px', font:'700 22px/1.2 var(--m-font-sans)', color:'var(--app-text)', letterSpacing:'-.02em' }}>{product.name}</h2>
            <div style={{ font:'500 12px/1 var(--m-font-mono)', color:'var(--app-text-3)' }}>SKU · {product.sku} · ID {product.id}</div>
          </div>

          <div style={{ display:'flex', alignItems:'baseline', gap:14 }}>
            <span style={{ font:'700 32px/1 var(--m-font-sans)', color:'#C2410C', letterSpacing:'-.02em' }}>{fmtMAD(product.price)}</span>
            <span style={{ font:'500 11px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>HT · TVA 20%</span>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:10 }}>
            <div className="card" style={{ padding:14 }}>
              <div className="eyebrow">En stock</div>
              <div style={{ font:'700 18px/1 var(--m-font-sans)', color:'var(--app-text)', marginTop:8 }}>{product.stock>=999?'∞':product.stock}</div>
            </div>
            <div className="card" style={{ padding:14 }}>
              <div className="eyebrow">Entrepôt</div>
              <div style={{ font:'700 13px/1.2 var(--m-font-sans)', color:'var(--app-text)', marginTop:8 }}>{product.warehouse}</div>
            </div>
            <div className="card" style={{ padding:14 }}>
              <div className="eyebrow">Ventes 30j</div>
              <div style={{ font:'700 18px/1 var(--m-font-sans)', color:'var(--app-text)', marginTop:8 }}>{Math.floor(Math.random()*40)+12}</div>
            </div>
          </div>

          <div className="card" style={{ padding:18 }}>
            <div style={{ font:'700 13px/1 var(--m-font-sans)', color:'var(--app-text)', marginBottom:10 }}>Description</div>
            <div style={{ font:'500 13px/1.6 var(--m-font-sans)', color:'var(--app-text-2)' }}>
              Produit issu de l'artisanat marocain authentique. Fabrication traditionnelle, matériaux nobles sourcés localement.
              Disponible en plusieurs variantes — contactez-nous pour personnalisation.
            </div>
          </div>

          <div style={{ display:'flex', gap:8 }}>
            <button className="btn btn-warm" style={{ flex:1, justifyContent:'center' }}><i data-lucide="edit-3" style={{width:14,height:14}}></i> Modifier</button>
            <button className="btn btn-ghost" style={{ flex:1, justifyContent:'center' }}><i data-lucide="copy" style={{width:14,height:14}}></i> Dupliquer</button>
            <button className="btn btn-ghost btn-icon"><i data-lucide="trash-2" style={{width:16,height:16}}></i></button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Produits });
