/* crm-products.jsx — Products list (grid) + inline edit panel */

function ProductsList() {
  const [catFilter, setCatFilter] = React.useState('all');
  const [view, setView] = React.useState('grid'); // grid | table
  const [selected, setSelected] = React.useState(null);

  // Per-product: in how many active contracts (base)
  const byProduct = React.useMemo(() => {
    const m = {};
    CRM_PRODUCTS.forEach(p => { m[p.code] = {product: p, contracts: 0, qty: 0}; });
    CRM_CONTRACTS.forEach(c => {
      if (c.state !== 'active' && c.state !== 'renew') return;
      (c.base || []).forEach(([code, q]) => {
        if (!m[code]) return;
        m[code].contracts += 1;
        m[code].qty += q;
      });
    });
    return m;
  }, []);

  const cats = ['cabelo','barba','corpo','vestuário'];
  const catCounts = React.useMemo(() => {
    const c = {all: CRM_PRODUCTS.length};
    cats.forEach(k => { c[k] = CRM_PRODUCTS.filter(p => p.cat === k).length; });
    return c;
  }, []);

  let list = CRM_PRODUCTS;
  if (catFilter !== 'all') list = list.filter(p => p.cat === catFilter);

  const total = list.length;
  const totalRevenue = list.reduce((s, p) => {
    const m = byProduct[p.code]; if (!m) return s;
    return s + m.qty * p.price;
  }, 0);

  return (
    <div className="content stack gap-5">
      <div className="flex between" style={{alignItems:'flex-end'}}>
        <div>
          <h1 className="page-title">Produtos</h1>
          <div className="page-sub">{total} SKUs · {CRM_FMT_EUR(totalRevenue)} em circulação trimestral nas linhas base</div>
        </div>
        <div className="row gap-2">
          <div className="row gap-1" style={{border:'0.5px solid var(--rule)', borderRadius:5, padding:2}}>
            <button className={'btn ghost sm'} style={{height:24, padding:'0 10px', fontSize:11, background: view==='grid' ? 'var(--surface-2)' : 'transparent'}} onClick={() => setView('grid')}>Grelha</button>
            <button className={'btn ghost sm'} style={{height:24, padding:'0 10px', fontSize:11, background: view==='table' ? 'var(--surface-2)' : 'transparent'}} onClick={() => setView('table')}>Tabela</button>
          </div>
          <button className="btn outline sm"><Icon k="download" size={13}/> Exportar</button>
          <button className="btn primary sm"><Icon k="plus" size={13}/> Novo produto</button>
        </div>
      </div>

      {/* Category KPIs */}
      <div className="grid gap-3" style={{gridTemplateColumns:'repeat(4, 1fr)'}}>
        {cats.map((c, i) => {
          const ps = CRM_PRODUCTS.filter(p => p.cat === c);
          const rev = ps.reduce((s, p) => s + (byProduct[p.code]?.qty || 0) * p.price, 0);
          return (
            <div key={c} className="card" style={{padding:'14px 16px', cursor:'pointer', background: catFilter===c ? 'var(--surface-2)' : 'var(--bone)'}} onClick={() => setCatFilter(catFilter===c ? 'all' : c)}>
              <div className="smallcaps">{c}</div>
              <div className="row between items-c mt-2">
                <span className="display tab" style={{fontSize:24, lineHeight:1}}>{ps.length}</span>
                <span className="mono tab" style={{fontSize:11, color:'var(--ink-3)'}}>{CRM_FMT_EUR(rev)}</span>
              </div>
            </div>
          );
        })}
      </div>

      {/* Filter row */}
      <div className="row gap-2" style={{flexWrap:'wrap'}}>
        <div className={'pill ' + (catFilter==='all' ? 'active' : '')} onClick={() => setCatFilter('all')}>
          Todas <span className="count">{catCounts.all}</span>
        </div>
        {cats.map(c => (
          <div key={c} className={'pill ' + (catFilter===c ? 'active' : '')} onClick={() => setCatFilter(c)}>
            {c} <span className="count">{catCounts[c]}</span>
          </div>
        ))}
      </div>

      {/* Body */}
      {view === 'grid' ? (
        <div className="grid gap-4" style={{gridTemplateColumns:'repeat(4, 1fr)'}}>
          {list.map(p => {
            const m = byProduct[p.code];
            return (
              <div key={p.code} className="card" style={{padding:14, cursor:'pointer'}} onClick={() => setSelected(p.code)}>
                <div className="flex between items-c">
                  <span className="mono" style={{fontSize:10, color:'var(--ink-3)', letterSpacing:0.06}}>{p.code}</span>
                  <span className="mono" style={{fontSize:10, color:'var(--ink-3)'}}>IVA {p.vat}%</span>
                </div>
                <div style={{height:120, background:'var(--surface-3)', borderRadius:3, marginTop:10, display:'flex', alignItems:'center', justifyContent:'center', position:'relative'}}>
                  <ProductPlaceholder kind={p.kind}/>
                  <span className="smallcaps" style={{position:'absolute', top:8, left:8, fontSize:9}}>{p.cat}</span>
                </div>
                <div className="mt-3">
                  <div style={{fontFamily:'var(--display)', fontSize:18, lineHeight:1.15}}>{p.name}</div>
                  <div style={{fontFamily:'var(--display)', fontStyle:'italic', fontSize:13, color:'var(--ink-3)', marginTop:2}}>{p.scent}</div>
                </div>
                <hr style={{border:0, borderTop:'0.5px solid var(--rule-2)', margin:'10px 0'}}/>
                <div className="flex between items-baseline">
                  <div style={{fontSize:11, color:'var(--ink-3)'}}>{p.fmt}</div>
                  <div className="mono tab" style={{fontSize:13, fontWeight:600}}>{p.price.toFixed(2).replace('.',',')} €</div>
                </div>
                <div className="mt-2 row gap-2" style={{fontSize:10.5, color:'var(--ink-3)'}}>
                  <span className="mono">em {m.contracts} contrato{m.contracts!==1?'s':''}</span>
                  <span>·</span>
                  <span className="mono tab">{m.qty} un/trim</span>
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        <div style={{border:'0.5px solid var(--rule)', borderRadius:6, overflow:'hidden', background:'var(--bone)'}}>
          <table className="t">
            <thead>
              <tr>
                <th style={{width:130}}>Ref.</th>
                <th>Produto · fragrância</th>
                <th style={{width:170}}>Formato</th>
                <th style={{width:100}}>Categoria</th>
                <th style={{width:60}}>IVA</th>
                <th className="num" style={{width:100}}>PU s/ IVA</th>
                <th className="num" style={{width:90}}>Contratos</th>
                <th className="num" style={{width:90}}>Un/trim.</th>
                <th style={{width:40}}/>
              </tr>
            </thead>
            <tbody>
              {list.map(p => {
                const m = byProduct[p.code];
                return (
                  <tr key={p.code} className="clickable" onClick={() => setSelected(p.code)}>
                    <td className="id">{p.code}</td>
                    <td>
                      <div style={{fontSize:13, fontWeight:500}}>{p.name}</div>
                      <div className="ink-3" style={{fontSize:11.5, fontStyle:'italic', fontFamily:'var(--display)'}}>{p.scent}</div>
                    </td>
                    <td className="ink-3">{p.fmt}</td>
                    <td className="ink-3" style={{fontSize:11.5}}>{p.cat}</td>
                    <td className="mono tab">{p.vat}%</td>
                    <td className="num">{CRM_FMT_EUR(p.price)}</td>
                    <td className="num">{m.contracts}</td>
                    <td className="num">{m.qty}</td>
                    <td><button className="btn ghost sm" style={{padding:'0 4px'}}><Icon k="more" size={14}/></button></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {/* Selected product slide-over */}
      {selected && <ProductSheet code={selected} onClose={() => setSelected(null)} byProduct={byProduct} />}
    </div>
  );
}

function ProductPlaceholder({kind='bottle'}) {
  const c = 'var(--clay)';
  const shapes = {
    bottle: <g fill="none" stroke={c} strokeWidth="0.8"><path d="M30 8 h20 v12 h-20 z"/><path d="M22 22 h36 v50 a8 8 0 0 1 -8 8 h-20 a8 8 0 0 1 -8 -8 z"/><line x1="28" y1="50" x2="52" y2="50"/></g>,
    tube:   <g fill="none" stroke={c} strokeWidth="0.8"><path d="M30 8 h20 v6 h-20 z"/><path d="M26 14 h28 v60 l-4 6 h-20 l-4 -6 z"/></g>,
    jar:    <g fill="none" stroke={c} strokeWidth="0.8"><ellipse cx="40" cy="22" rx="20" ry="6"/><path d="M20 22 v50 a20 6 0 0 0 40 0 v-50"/><ellipse cx="40" cy="22" rx="20" ry="6"/><line x1="22" y1="50" x2="58" y2="50"/></g>,
    bar:    <g fill="none" stroke={c} strokeWidth="0.8"><rect x="18" y="28" width="44" height="36" rx="2"/></g>,
  };
  return <svg viewBox="0 0 80 100" width={56} height={88}>{shapes[kind] || shapes.bottle}</svg>;
}

function ProductSheet({code, onClose, byProduct}) {
  const p = CRM_PRODUCTS.find(x => x.code === code);
  const m = byProduct[code];
  if (!p) return null;

  // Which contracts include this SKU
  const contracts = CRM_CONTRACTS.filter(c => (c.base || []).some(([k]) => k === code));

  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, zIndex:50,
      background:'rgba(31,24,18,0.4)', backdropFilter:'blur(6px)',
      display:'flex', justifyContent:'flex-end',
    }}>
      <div onClick={e=>e.stopPropagation()} style={{
        width:520, maxWidth:'94vw', background:'var(--bone)',
        borderLeft:'0.5px solid var(--rule)', height:'100vh',
        overflowY:'auto', padding:'24px 28px',
      }}>
        <div className="flex between items-c">
          <span className="mono" style={{fontSize:11, color:'var(--ink-3)'}}>{p.code}</span>
          <button className="btn ghost sm" style={{padding:'0 6px'}} onClick={onClose}><Icon k="x" size={14}/></button>
        </div>

        <div style={{height:200, background:'var(--surface-3)', borderRadius:4, marginTop:14, display:'flex', alignItems:'center', justifyContent:'center'}}>
          <svg viewBox="0 0 80 100" width={100} height={150}>
            <g fill="none" stroke="var(--clay)" strokeWidth="0.6">
              {p.kind === 'bottle' && <><path d="M30 8 h20 v12 h-20 z"/><path d="M22 22 h36 v50 a8 8 0 0 1 -8 8 h-20 a8 8 0 0 1 -8 -8 z"/><line x1="28" y1="50" x2="52" y2="50"/></>}
              {p.kind === 'tube' && <><path d="M30 8 h20 v6 h-20 z"/><path d="M26 14 h28 v60 l-4 6 h-20 l-4 -6 z"/></>}
              {p.kind === 'jar' && <><ellipse cx="40" cy="22" rx="20" ry="6"/><path d="M20 22 v50 a20 6 0 0 0 40 0 v-50"/></>}
              {p.kind === 'bar' && <rect x="18" y="28" width="44" height="36" rx="2"/>}
            </g>
          </svg>
        </div>

        <h2 className="display mt-4" style={{fontSize:30, lineHeight:1.05}}>{p.name}</h2>
        <div className="display ital ink-3 mt-1" style={{fontSize:16}}>{p.scent}</div>

        {/* Form-style fields */}
        <div className="mt-5 stack gap-3">
          <Field label="Categoria" value={p.cat}/>
          <Field label="Formato"    value={p.fmt}/>
          <div className="grid gap-3" style={{gridTemplateColumns:'1fr 1fr'}}>
            <Field label="Preço · sem IVA" value={CRM_FMT_EUR(p.price)} mono/>
            <Field label="IVA"              value={p.vat + '%'} mono/>
          </div>
        </div>

        <hr style={{border:0, borderTop:'0.5px solid var(--rule)', margin:'24px 0'}}/>

        <div>
          <div className="flex between items-c">
            <span className="smallcaps">Em contratos</span>
            <span className="mono ink-3" style={{fontSize:11}}>{m.contracts} contratos · {m.qty} un/trim</span>
          </div>
          <div className="mt-3 stack" style={{gap:0}}>
            {contracts.slice(0, 8).map((c, i) => {
              const cust = CRM_BY_ID[c.id];
              const qty = (c.base || []).find(([k]) => k === code)?.[1] || 0;
              return (
                <div key={c.id} className="flex between items-c" style={{padding:'9px 0', borderBottom: i<Math.min(7,contracts.length-1) ? '0.5px solid var(--rule-2)' : 'none', fontSize:13}}>
                  <div className="row gap-3">
                    <span className="mono ink-3" style={{fontSize:11, width:100}}>{c.id}</span>
                    <span>{cust?.name}</span>
                  </div>
                  <span className="mono tab" style={{fontWeight:600}}>{qty} un</span>
                </div>
              );
            })}
          </div>
        </div>

        <div className="row gap-2 mt-5">
          <button className="btn primary"><Icon k="edit" size={13}/> Editar produto</button>
          <button className="btn outline">Duplicar</button>
          <button className="btn ghost" style={{color:'var(--clay-deep)'}}>Arquivar</button>
        </div>
      </div>
    </div>
  );
}

function Field({label, value, mono}) {
  return (
    <div>
      <div className="smallcaps">{label}</div>
      <div className={'input mt-1 ' + (mono ? 'mono tab' : '')} style={{display:'flex', alignItems:'center', height:34}}>{value}</div>
    </div>
  );
}

Object.assign(window, { ProductsList });
