/* ============ ExtractsTab — terminal reskin of HashCalc ============
   Source: profit-calc-clean-source.html lines 785-904. Math identical. */

const exportExtractsCSV=(products)=>{
  const filtered=products.filter(p=>p.category==='hash');
  if(filtered.length===0)return alert('No extract products yet.');
  const cols=['SKU','Type','Size','Input','COGS/Unit','WS List','WS Floor','Retail','List Margin %','Units','Revenue','Gross Profit'];
  const rows=filtered.map(p=>[p.skuName,p.tier,p.size,p.inputMaterial,
    '$'+p.totalCOGS.toFixed(2),'$'+p.wsList.toFixed(2),'$'+p.wsFloor.toFixed(2),'$'+p.consumerRetail.toFixed(2),
    p.listMarginPct.toFixed(1)+'%',p.units,'$'+p.totalRevenue.toFixed(2),'$'+p.totalProfit.toFixed(2)]);
  const csv=[cols.join(','),...rows.map(r=>r.map(c=>'"'+String(c).replace(/"/g,'""')+'"').join(','))].join('\n');
  const blob=new Blob([csv],{type:'text/csv'});
  const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download='cannabiz-extracts.csv';a.click();URL.revokeObjectURL(url);
};

function ExtractsTab({products,setProducts,distroState,setProgress}){
  const [extractCat,setExtractCat]=useState('solventless');
  const [solventlessType,setSolventlessType]=useState('rosin');
  const [solventType,setSolventType]=useState('liveresin');
  const [tier,setTier]=useState('tier1');
  const [inputCost,setInputCost]=useState(15);
  const [jarSize,setJarSize]=useState(1);
  const [jarCost,setJarCost]=useState(0.75);
  const [boxCost,setBoxCost]=useState(0.50);
  const [stickerCost,setStickerCost]=useState(0.15);
  const [skuName,setSkuName]=useState('');
  const [inputGrams,setInputGrams]=useState(100);
  const [lossPct,setLossPct]=useState(2);
  const [consumerRetail,setConsumerRetail]=useState(60);
  const [wsList,setWsList]=useState(32);
  const [wsFloor,setWsFloor]=useState(26);
  const [markupX,setMarkupX]=useState(2.0);
  const [testCostBatch,setTestCostBatch]=useState(400);
  const [fillLaborCost,setFillLaborCost]=useState(1.00);
  const [pkgLaborCost,setPkgLaborCost]=useState(0.50);

  const typeList=extractCat==='solventless'?EXTRACT_TYPES.solventless:EXTRACT_TYPES.solvent;
  const activeTypeId=extractCat==='solventless'?solventlessType:solventType;
  const stObj=typeList.find(t=>t.id===activeTypeId)||typeList[0];

  useEffect(()=>{
    const c=tier==='tier1'?stObj.defCostT1:stObj.defCostT2;
    const w=tier==='tier1'?stObj.defWsT1:stObj.defWsT2;
    const f=tier==='tier1'?stObj.defFloorT1:stObj.defFloorT2;
    setInputCost(c);setWsList(w);setWsFloor(f);
    setConsumerRetail(+(w*markupX).toFixed(2));
  },[tier,solventlessType,solventType,extractCat]);

  const safeInputGrams=nonNegative(inputGrams);
  const safeLossPct=clamp(lossPct,0,100);
  const safeJarSize=positiveOr(jarSize);
  const safeInputCost=nonNegative(inputCost);
  const safeWsList=nonNegative(wsList);
  const safeWsFloor=nonNegative(wsFloor);
  const usableGrams=safeInputGrams*(1-safeLossPct/100);
  const units=Math.max(0,Math.floor(usableGrams/safeJarSize));
  const materialCost=safeInputGrams*safeInputCost;
  const materialPerUnit=units>0?materialCost/units:0;
  const testCostPerUnit=units>0?nonNegative(testCostBatch)/units:0;
  const laborTotal=nonNegative(fillLaborCost)+nonNegative(pkgLaborCost);
  const totalCOGS=units>0?(materialPerUnit+nonNegative(jarCost)+nonNegative(boxCost)+nonNegative(stickerCost)+laborTotal+COA_LABEL+testCostPerUnit):0;
  const listMargin=safeWsList-totalCOGS;
  const listMarginPct=safeWsList>0?(listMargin/safeWsList)*100:0;
  const floorMargin=safeWsFloor-totalCOGS;
  const floorMarginPct=safeWsFloor>0?(floorMargin/safeWsFloor)*100:0;

  /* shared distro */
  const distroModel=distroState.distroModelShared;
  const distroMargin=distroState.distroMarginShared;
  const setDistroModel=distroState.setDistroModelShared;
  const setDistroMargin=distroState.setDistroMarginShared;
  const pricingMode=distroState.distroPricingModeShared;
  const setPricingMode=distroState.setDistroPricingModeShared;
  const salesComm=distroState.salesPctShared;
  const setSalesComm=distroState.setSalesPctShared;
  const samplePct=distroState.sampleRateShared;
  const setSamplePct=distroState.setSampleRateShared;
  const [overheadPerUnit,setOverheadPerUnit]=useState(0);
  const safeDistroMargin=pct(distroMargin);
  const safeSalesComm=pct(salesComm);
  const safeSamplePct=pct(samplePct);

  const isFlat=distroModel==='wholesale'&&pricingMode==='flat';
  const isPct=distroModel==='percentage';
  const distroPerUnit=isPct?safeWsList*(safeDistroMargin/100):0;
  const effectiveRevPerUnit=isPct?safeWsList:(isFlat?safeWsList:safeWsList*(1-safeDistroMargin/100));
  const salesPerUnit=effectiveRevPerUnit*(safeSalesComm/100);
  const sampleUnits=Math.ceil(units*(safeSamplePct/100));
  const samplePerUnit=units>0?(sampleUnits*totalCOGS)/units:0;
  const netPerUnit=effectiveRevPerUnit-totalCOGS-distroPerUnit-salesPerUnit-samplePerUnit-nonNegative(overheadPerUnit);
  const netTotal=netPerUnit*units;
  const netMarginPct=effectiveRevPerUnit>0?(netPerUnit/effectiveRevPerUnit)*100:0;
  const revenueAfterDistro=effectiveRevPerUnit-distroPerUnit;
  const netAfterRepsSamples=effectiveRevPerUnit-distroPerUnit-salesPerUnit-samplePerUnit;

  const sku_done=!!skuName;
  const yield_done=inputGrams>0&&units>0;
  const pricing_done=wsList>0;
  const takehome_done=netPerUnit>0;
  const extractsProducts=products.filter(p=>p.category==='hash');
  const mix_done=extractsProducts.length>0;

  useEffect(()=>{
    setProgress({raw:true,sku:sku_done,yield:yield_done,pricing:pricing_done,takehome:takehome_done,addmix:mix_done});
  },[sku_done,yield_done,pricing_done,takehome_done,mix_done]);

  const canAdd=units>0&&wsList>0;
  const addProduct=()=>{
    const typeLabel=stObj.label;
    const catLabel=extractCat==='solventless'?'Solventless':'Solvent';
    setProducts(p=>[...p,{
      id:uid(),category:'hash',skuName:skuName||`${tier==='tier1'?'T1':'T2'} ${typeLabel} ${jarSize}g`,
      tier:`${tier==='tier1'?'T1':'T2'} ${typeLabel}`,grade:`${catLabel} · ${typeLabel}`,inputMaterial:`${inputGrams}g`,
      size:`${jarSize}g`,gramsPerUnit:jarSize,pkgType:'Jar + Box + Sticker',
      rosinCost:materialPerUnit,jarCost,boxCost,stickerCost,coaCost:COA_LABEL,testCostPerUnit,totalCOGS,
      consumerRetail:nonNegative(consumerRetail),wsList:safeWsList,wsFloor:safeWsFloor,listMarginPct,floorMarginPct,units,
      totalRevenue:safeWsList*units,totalCOGSAll:totalCOGS*units,totalProfit:listMargin*units
    }]);
  };

  const railBand=bandForMargin(netMarginPct);

  return(<div className="shell">
    <div className="col-main">
      <div className="readme">
        <p><strong style={{color:'var(--text)'}}>extract math.</strong> buy <code>input</code> by the gram, jar it at a <code>jar_size</code>. <code>solventless</code> (rosin · bubble · dry sift) and <code>solvent</code> (live resin · bho · distillate · diamonds) share the same cogs shape — input × grams + jar + box + sticker + labor + COA + testing. <strong style={{color:'var(--accent)'}}>take-home</strong> = ws_list − cogs − distro − reps − samples.</p>
        <div className="bands">
          <span className="band premium"><b>45%+</b> excellent</span>
          <span className="band strong"><b>30–45%</b> strong</span>
          <span className="band average"><b>20–30%</b> average</span>
          <span className="band thin"><b>10–20%</b> thin</span>
          <span className="band low"><b>&lt;10%</b> unviable</span>
        </div>
      </div>

      <Section stepId="sku" idx={1} title="configure extract" done={sku_done} active={!sku_done}>
        <div className="g-sku">
          <Field highlight label="sku_name" type="text" value={skuName} onChange={setSkuName} hint="strain or product name" tip="The name you'll sell this under. Example: 'Papaya Live Rosin 1g'."/>
          <Field highlight label="category" value={extractCat} onChange={setExtractCat} options={[{value:'solventless',label:'Solventless'},{value:'solvent',label:'Solvent-Based'}]} tip="Solventless = rosin, bubble, dry sift — no chemical solvents, commands premium. Solvent = live resin, BHO, distillate — higher yields, lower cost."/>
          <Field highlight label="extract_type" value={activeTypeId} onChange={v=>extractCat==='solventless'?setSolventlessType(v):setSolventType(v)} options={typeList.map(t=>({value:t.id,label:t.label}))} tip={stObj.desc}/>
          <Field highlight label="quality_tier" value={tier} onChange={setTier} options={[{value:'tier1',label:`Tier 1 — Premium (${fmt(stObj.defCostT1)}/g)`},{value:'tier2',label:`Tier 2 — Standard (${fmt(stObj.defCostT2)}/g)`}]} tip="Tier 1 = fire, top-shelf. Tier 2 = solid mids. Changes input cost and suggested pricing."/>
        </div>
        <div style={{marginTop:10,padding:10,background:'var(--surface-2)',border:'1px solid var(--border)',borderRadius:4,fontFamily:'var(--mono)',fontSize:11,color:'var(--muted)',lineHeight:1.6}}>
          <span style={{color:'var(--accent)'}}>{stObj.label.toLowerCase()}</span> — {stObj.desc}
        </div>
      </Section>

      <Section stepId="sku" idx={2} title="inputs · jar · packaging · labor" done={true}>
        <div className="g3">
          <Field label="input_cost / g" prefix="$" value={inputCost} onChange={setInputCost} hint={`tier ${tier==='tier1'?'1':'2'} default ${fmt(tier==='tier1'?stObj.defCostT1:stObj.defCostT2)}/g`}/>
          <Field label="jar_size" value={jarSize} onChange={setJarSize} suffix="g" step={0.5} min={0.5}/>
          <Stat label="material_cost_total" value={fmtK(materialCost)} sub={`${inputGrams}g × ${fmt(inputCost)}/g`} tone="warn"/>
        </div>
        <SubHead title="packaging"/>
        <div className="g3">
          <Field label="jar_cost" prefix="$" value={jarCost} onChange={setJarCost} step={0.05}/>
          <Field label="box_cost" prefix="$" value={boxCost} onChange={setBoxCost} step={0.05}/>
          <Field label="sticker_cost" prefix="$" value={stickerCost} onChange={setStickerCost} step={0.05}/>
        </div>
        <SubHead title="labor"/>
        <div className="g2">
          <Field label="fill_labor" prefix="$" value={fillLaborCost} onChange={setFillLaborCost} step={0.1} hint="weigh · fill · cap · label"/>
          <Field label="pkg_labor" prefix="$" value={pkgLaborCost} onChange={setPkgLaborCost} step={0.1} hint="box · insert · qc"/>
        </div>
      </Section>

      <Section stepId="yield" idx={3} title="input quantity · yield · testing" done={yield_done} active={sku_done&&!yield_done}>
        <div className="g3">
          <Field highlight label="input_grams" value={inputGrams} onChange={setInputGrams} suffix="g" step={10} tip="How many grams of raw extract you purchased or produced."/>
          <Field label="loss_factor" value={lossPct} onChange={setLossPct} suffix="%" step={0.5} hint="residual · tools"/>
          <Field label="testing_batch" prefix="$" value={testCostBatch} onChange={setTestCostBatch}/>
        </div>
        <div className="g4" style={{marginTop:12}}>
          <Stat label="theoretical_max" value={Math.floor(inputGrams/jarSize).toLocaleString()} sub={`${inputGrams}g / ${jarSize}g jars`} tone="dim"/>
          <Stat label="loss" value={`${(inputGrams*(lossPct/100)).toFixed(1)}g`} sub={`${lossPct}% waste`} tone="neg"/>
          <Stat label="usable" value={`${usableGrams.toFixed(1)}g`} sub={`after loss`} tone="warn"/>
          <Stat label="finished_jars" value={units.toLocaleString()} sub={`${usableGrams.toFixed(1)}g ÷ ${jarSize}g`} tone="pos"/>
        </div>

        <SubHead title="per-jar cogs breakdown"/>
        <Waterfall caption={`every line going into one ${jarSize}g jar.`}
          lines={[
            {label:`${stObj.label.toLowerCase()}_material  (${fmtK(materialCost)} / ${units||0} jars)`,value:fmt(materialPerUnit)},
            {label:'glass_jar',value:fmt(jarCost)},
            {label:'box',value:fmt(boxCost)},
            {label:'sticker',value:fmt(stickerCost)},
            {label:'fill_labor',value:fmt(fillLaborCost)},
            {label:'pkg_labor',value:fmt(pkgLaborCost)},
            {label:'coa_label',value:fmt(COA_LABEL)},
            {label:`testing  (${fmt(testCostBatch)} / ${units})`,value:fmt(testCostPerUnit)}
          ]}
          total={fmt(totalCOGS)} totalLabel="cogs / jar"/>
      </Section>

      <Section stepId="pricing" idx={4} title="pricing · margin bands" done={pricing_done} active={yield_done&&!pricing_done}>
        {!isFlat&&<div className="g4">
          <Field highlight label="ws_list" prefix="$" value={wsList} onChange={v=>{setWsList(v);setConsumerRetail(+(v*markupX).toFixed(2));}} hint="what you charge the store"/>
          <Field highlight label="ws_floor" prefix="$" value={wsFloor} onChange={setWsFloor} hint="lowest you'd accept"/>
          <Field label="markup" value={markupX} onChange={v=>{setMarkupX(v);setConsumerRetail(+(wsList*v).toFixed(2));}} suffix="×" step={0.1}/>
          <Field label="retail" prefix="$" value={consumerRetail} onChange={v=>{setConsumerRetail(v);if(wsList>0)setMarkupX(+(v/wsList).toFixed(2));}}/>
        </div>}
        {isFlat&&<div className="g2">
          <Field label="flat_price_to_distro" prefix="$" value={wsList} onChange={v=>{setWsList(v);setConsumerRetail(+(v*markupX).toFixed(2));}}/>
          <div style={{alignSelf:'center',color:'var(--muted)',fontSize:12,lineHeight:1.6}}>flat to distro — they handle retail.</div>
        </div>}

        <SubHead title="benchmarks"/>
        {!isFlat?<div className="g2">
          <BenchBar name="gm @ list" pct={listMarginPct}/>
          <BenchBar name="gm @ floor" pct={floorMarginPct}/>
        </div>:<BenchBar name="gm @ flat" pct={listMarginPct}/>}

        <SubHead title="deductions waterfall" note="revenue → take-home"/>
        <Waterfall caption="every deduction from revenue down to what you pocket per jar."
          lines={[
            {label:isFlat?'flat_price_to_distro':'ws_list',value:fmt(effectiveRevPerUnit),sign:'+ '},
            {label:'cogs',value:fmt(totalCOGS),sign:'− ',tone:'neg'},
            ...(isPct?[{label:`distro_fee  (${safeDistroMargin}% of invoice)`,value:fmt(distroPerUnit),sign:'− ',tone:'warn'}]:[]),
            {label:`sales_reps  (${safeSalesComm}%)`,value:fmt(salesPerUnit),sign:'− ',tone:'warn'},
            {label:`samples  (${safeSamplePct}% at cogs)`,value:fmt(samplePerUnit),sign:'− ',tone:'warn'},
            ...(overheadPerUnit>0?[{label:'overhead',value:fmt(overheadPerUnit),sign:'− ',tone:'neg'}]:[])
          ]}
          total={fmt(netPerUnit)} totalLabel="take-home / jar"/>
      </Section>

      <Section stepId="takehome" idx={5} title="distribution & sales" done={takehome_done} active={pricing_done&&!takehome_done} note="syncs across all tabs">
        <Seg options={[{value:'pct',label:'distro_takes_fee'},{value:'flat',label:'sell_at_flat_price'},{value:'discount',label:'sell_at_discount'}]} value={distroModel==='percentage'?'pct':(pricingMode==='flat'?'flat':'discount')}
        onChange={v=>{
          if(v==='pct'){setDistroModel('percentage');setPricingMode('pct');setDistroMargin(10);}
          else if(v==='flat'){setDistroModel('wholesale');setPricingMode('flat');}
          else {setDistroModel('wholesale');setPricingMode('pct');setDistroMargin(20);}
        }}/>
        <div className="g4" style={{marginTop:12}}>
          {distroModel==='percentage'&&<Field highlight label="distro_pct" value={distroMargin} onChange={setDistroMargin} suffix="%"/>}
          {distroModel==='wholesale'&&pricingMode==='pct'&&<Field highlight label="discount_pct" value={distroMargin} onChange={setDistroMargin} suffix="%"/>}
          {isFlat&&<Field highlight label="flat_price" prefix="$" value={wsList} onChange={v=>setWsList(v)}/>}
          <Field highlight label="sales_rep_commission" value={salesComm} onChange={setSalesComm} suffix="%"/>
          <Field label="samples_pct" value={samplePct} onChange={setSamplePct} suffix="%"/>
          <Field label="overhead / unit" prefix="$" value={overheadPerUnit} onChange={setOverheadPerUnit} step={0.05}/>
        </div>
        <div className="g3" style={{marginTop:14}}>
          <Stat label="revenue_after_distro" value={fmt(revenueAfterDistro)} sub={isPct?`${fmt(effectiveRevPerUnit)} − ${fmt(distroPerUnit)}`:'distro pays direct'}/>
          <Stat label="net_after_reps_samples" value={fmt(netAfterRepsSamples)} sub={`− ${fmt(salesPerUnit)} reps − ${fmt(samplePerUnit)} samples`} tone="warn"/>
          <Stat label="take_home / jar" value={fmt(netPerUnit)} sub={`${netMarginPct.toFixed(1)}% net`} tone={netPerUnit>0?'pos':'neg'}/>
        </div>
      </Section>

      <Section stepId="takehome" idx={6} title="batch totals · full run" done={units>0}>
        <div className="g3">
          <Stat label="capital_required" value={fmtK(totalCOGS*units)} sub={`${fmt(totalCOGS)}/u × ${units.toLocaleString()}`} tone="neg"/>
          <Stat label="revenue_at_list" value={fmtK(effectiveRevPerUnit*units)} sub={`${fmt(effectiveRevPerUnit)}/u × ${units.toLocaleString()}`}/>
          <Stat label="gross_profit" value={fmtK(listMargin*units)} sub="before distro/reps/samples" tone={listMargin>0?'pos':'neg'}/>
        </div>
        <div className="g3" style={{marginTop:12}}>
          <Stat label="take_home_batch" value={fmtK(netTotal)} sub={`${units.toLocaleString()} × ${fmt(netPerUnit)}`} tone={netTotal>0?'pos':'neg'}/>
          <Stat label="return_on_capital" value={totalCOGS*units>0?`${(netTotal/(totalCOGS*units)*100).toFixed(1)}%`:'—'} sub="take-home / capital" tone={netTotal>0?'pos':'neg'}/>
          <Stat label="net_margin" value={`${netMarginPct.toFixed(1)}%`} sub={bandForMargin(netMarginPct).label} tone={bandForMargin(netMarginPct).idx>=3?'pos':bandForMargin(netMarginPct).idx>=2?'warn':'neg'}/>
        </div>
      </Section>

      <Section stepId="addmix" idx={7} title="add to product mix" done={mix_done} active={takehome_done&&!mix_done}>
        <p className="section-desc">save this extract SKU. build your concentrate lineup across types and tiers.</p>
        <div style={{display:'flex',gap:8,flexWrap:'wrap'}}>
          <button className="btn primary" onClick={addProduct} disabled={!canAdd}>[+] add_to_mix</button>
          {extractsProducts.length>0&&<button className="btn outline" onClick={()=>exportExtractsCSV(products)}>export extracts csv</button>}
        </div>
        {extractsProducts.length>0&&<div style={{marginTop:16}}>
          <SubHead title="extracts product mix"/>
          <div className="tbl-wrap"><table className="tbl">
            <thead><tr>
              <th>sku</th><th>type</th><th>size</th><th>input</th><th>cogs/u</th><th>ws_list</th><th>ws_floor</th><th>retail</th><th>margin</th>
              <th>units</th><th>revenue</th><th>gross</th><th></th>
            </tr></thead>
            <tbody>{extractsProducts.map(p=><tr key={p.id}>
              <td className="sku">{p.skuName}</td>
              <td className="dim" style={{fontSize:10}}>{p.tier}</td>
              <td className="dim">{p.size}</td>
              <td className="dim">{p.inputMaterial}</td>
              <td>{fmt(p.totalCOGS)}</td>
              <td className="pos">{fmt(p.wsList)}</td>
              <td className="warn">{fmt(p.wsFloor)}</td>
              <td className="dim">{fmt(p.consumerRetail)}</td>
              <td style={{color:bandForMargin(p.listMarginPct).color}}>{p.listMarginPct.toFixed(1)}%</td>
              <td>{p.units.toLocaleString()}</td>
              <td>{fmtK(p.totalRevenue)}</td>
              <td className="pos">{fmtK(p.totalProfit)}</td>
              <td><button className="btn danger sm" onClick={()=>setProducts(ps=>ps.filter(x=>x.id!==p.id))}>×</button></td>
            </tr>)}</tbody>
          </table></div>
        </div>}
      </Section>
    </div>

    <aside className="rail">
      <div className="rail-card">
        <div className="rail-panel head">
          <div className="rail-eyebrow">live jar</div>
          <div className="rail-title">{skuName||'untitled extract'}</div>
          <div className="rail-meta">{extractCat==='solventless'?'solventless':'solvent'} · {stObj.label.toLowerCase()} · {jarSize}g</div>
        </div>
        <div className="rail-panel">
          <div className="rail-hero-label">take-home / jar</div>
          <div className={`rail-hero-val ${netPerUnit<0?'neg':''}`}>{fmt(netPerUnit)}</div>
          <div className="rail-hero-sub">{netMarginPct.toFixed(1)}% of {isFlat?'flat_price':'ws_list'}</div>
        </div>
        <div className="rail-panel">
          <div className="rail-ledger">
            <div className="r"><span className="lbl">{isFlat?'flat':'ws_list'}</span><span className="val">+ {fmt(effectiveRevPerUnit)}</span></div>
            <div className="r neg"><span className="lbl">cogs</span><span className="val">− {fmt(totalCOGS)}</span></div>
            {isPct&&<div className="r warn"><span className="lbl">distro</span><span className="val">− {fmt(distroPerUnit)}</span></div>}
            <div className="r warn"><span className="lbl">reps</span><span className="val">− {fmt(salesPerUnit)}</span></div>
            <div className="r warn"><span className="lbl">samples</span><span className="val">− {fmt(samplePerUnit)}</span></div>
            <div className="rule"></div>
            <div className="r total"><span className="lbl">net</span><span className="val">{fmt(netPerUnit)}</span></div>
          </div>
        </div>
        <div className="rail-panel">
          <div className="rail-grid">
            <div className="rail-stat"><span className="lbl">jars</span><span className="val">{units.toLocaleString()}</span></div>
            <div className="rail-stat"><span className="lbl">input/g</span><span className="val">{fmt(inputCost)}</span></div>
            <div className="rail-stat"><span className="lbl">revenue</span><span className="val">{fmtK(effectiveRevPerUnit*units)}</span></div>
            <div className="rail-stat"><span className="lbl">take-home</span><span className="val pos">{fmtK(netTotal)}</span></div>
          </div>
        </div>
        <div className="rail-panel">
          <button className="btn primary" style={{width:'100%',justifyContent:'center'}} onClick={addProduct} disabled={!canAdd}>[+] add_to_mix</button>
        </div>
      </div>
      <div className="bench-callout">
        <span className="pct" style={{color:railBand.color}}>{netMarginPct.toFixed(1)}%</span> — <b style={{color:railBand.color}}>{railBand.label}</b> band for {stObj.label.toLowerCase()}.
      </div>

      {extractsProducts.length>0&&<div className="mix-mini">
        <div className="mix-mini-head">
          <span className="mix-eyebrow">extracts_mix</span>
          <span className="mix-count">{extractsProducts.length} sku{extractsProducts.length>1?'s':''}</span>
        </div>
        <div className="mix-list">
          {extractsProducts.map(p=>{
            const b=bandForMargin(p.listMarginPct);
            return(<div key={p.id} className="mix-item">
              <div className="mix-row-top">
                <span className="mix-sku" title={p.skuName}>{p.skuName}</span>
                <button className="mix-x" onClick={()=>setProducts(ps=>ps.filter(x=>x.id!==p.id))} title="remove">×</button>
              </div>
              <div className="mix-row-mid">
                <span className="mix-meta">{p.tier.toLowerCase()} · {p.size}</span>
                <span className="mix-pct" style={{color:b.color}}>{p.listMarginPct.toFixed(0)}%</span>
              </div>
              <div className="mix-row-bot">
                <span className="mix-price">{fmt(p.wsList)} <span className="dim">/u</span></span>
                <span className="mix-profit">{fmtK(p.totalProfit)}</span>
              </div>
            </div>);
          })}
        </div>
      </div>}
    </aside>
  </div>);
}

Object.assign(window,{ExtractsTab,exportExtractsCSV});
