/* ============ DistroTab — terminal reskin of DistroCalc ============
   Source: profit-calc-clean-source.html lines 2211-2395 + TestingSamples 2400-2500. Math identical. */

function DistroTab({products,distroState,setProgress}){
  const [market,setMarket]=useState('california');
  const [salesLow,setSalesLow]=useState(5);
  const [salesHigh,setSalesHigh]=useState(8);

  const distroModel=distroState.distroModelShared;
  const setDistroModel=distroState.setDistroModelShared;
  const distroMargin=distroState.distroMarginShared;
  const setDistroMargin=distroState.setDistroMarginShared;
  const pricingMode=distroState.distroPricingModeShared;
  const setPricingMode=distroState.setDistroPricingModeShared;
  const salesPct=distroState.salesPctShared;
  const setSalesPct=distroState.setSalesPctShared;
  const sampleRate=distroState.sampleRateShared;
  const setSampleRate=distroState.setSampleRateShared;
  const setTestingAnnual=distroState.setTestingAnnualShared;
  const safeDistroMargin=pct(distroMargin);
  const safeSalesPct=pct(salesPct);
  const safeSampleRate=pct(sampleRate);

  const totalWsListRev=products.reduce((s,p)=>s+p.wsList*p.units,0);
  const totalConsumerRev=products.reduce((s,p)=>s+(p.consumerRetail||0)*p.units,0);
  const totalCOGS=products.reduce((s,p)=>s+p.totalCOGS*p.units,0);
  const totalUnits=products.reduce((s,p)=>s+p.units,0);

  const isPct=distroModel==='percentage';
  const isFlatMode=!isPct&&pricingMode==='flat';
  const wholesaleDiscount=!isPct&&!isFlatMode?totalWsListRev*(safeDistroMargin/100):0;
  const distroCost=isPct?totalWsListRev*(safeDistroMargin/100):0;
  const effectiveRev=isPct?totalWsListRev:totalWsListRev-wholesaleDiscount;
  const salesCost=effectiveRev*(safeSalesPct/100);
  const netRevAfterDistro=effectiveRev-distroCost-salesCost;

  /* Testing + samples */
  const [marketType,setMarketType]=useState('licensed');
  const [testCost,setTestCost]=useState(400);
  const [numStrains,setNumStrains]=useState(5);
  const [batchesPerYear,setBatchesPerYear]=useState(12);
  const [hempProductTypes,setHempProductTypes]=useState(8);
  const avgCOGS=totalUnits>0?totalCOGS/totalUnits:0;
  const testingCostAnnual=marketType==='licensed'?nonNegative(testCost)*nonNegative(numStrains)*nonNegative(batchesPerYear):nonNegative(testCost)*nonNegative(hempProductTypes);
  useEffect(()=>{if(setTestingAnnual)setTestingAnnual(testingCostAnnual);},[testingCostAnnual]);
  const sampleUnits=Math.ceil(totalUnits*(safeSampleRate/100));
  const sampleCost=sampleUnits*avgCOGS;
  const totalOverhead=testingCostAnnual+sampleCost;
  const netProfit=netRevAfterDistro-totalCOGS-sampleCost;
  const netMargin=effectiveRev>0?(netProfit/effectiveRev)*100:0;
  const netAfterAnnualTesting=netProfit-testingCostAnnual;

  const hasProducts=products.length>0;

  return(<div className="calc-page">
    <div className="readme">
      <p><strong style={{color:'var(--text)'}}>distribution layer.</strong> this is where your wholesale revenue gets sliced. three models — <code>%_fee</code> (distro invoices on your behalf), <code>flat_price</code> (distro pays you a fixed $), <code>discount</code> (distro buys at a % off list). the settings here apply globally — every product tab reads from this state.</p>
      <p>california standard: <code>10%</code> of gross invoice for distro, <code>5-8%</code> sales comm. hemp markets vary wildly.</p>
    </div>

    <Section idx={1} title="market + model" active>
      <p className="section-desc">pick your market and how you work with distributors. the model changes which math applies.</p>
      <div style={{marginBottom:12}}>
        <div className="sub-head"><span className="mark">//</span><span className="title">market</span></div>
        <Seg options={[
          {value:'california',label:'california'},
          {value:'newyork',label:'new_york'},
          {value:'hemp',label:'hemp_national'}
        ]} value={market} onChange={setMarket}/>
      </div>
      <div>
        <div className="sub-head"><span className="mark">//</span><span className="title">distro_model</span></div>
        <Seg options={[
          {value:'pct',label:'%_of_invoice'},
          {value:'flat',label:'flat_price'},
          {value:'discount',label:'%_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>
      <div className="g3" style={{marginTop:12}}>
        {isPct&&<Field highlight label="distro_pct" value={distroMargin} onChange={setDistroMargin} suffix="%" hint="% of gross invoice"/>}
        {!isPct&&pricingMode==='pct'&&<Field highlight label="discount_pct" value={distroMargin} onChange={setDistroMargin} suffix="%" hint="% off ws_list"/>}
        {isFlatMode&&<Stat label="flat_price" value="set per product" sub="on each calc tab"/>}
        <Field highlight label="sales_commission" value={salesPct} onChange={setSalesPct} suffix="%" min={salesLow} max={salesHigh}/>
        <div className="field">
          <label>comm_range</label>
          <div style={{display:'flex',gap:6}}>
            <Field label="low" value={salesLow} onChange={setSalesLow} suffix="%"/>
            <Field label="high" value={salesHigh} onChange={setSalesHigh} suffix="%"/>
          </div>
        </div>
      </div>
    </Section>

    <Section idx={2} title="revenue waterfall" active={hasProducts}>
      {!hasProducts?<div className="empty-state">
        <h3>no products in the mix</h3>
        <p>add products from flower, prerolls, vapes, or extracts to see distribution analysis.</p>
      </div>:<>
        <p className="section-desc">how the total wholesale revenue gets sliced — distro cut, sales reps, cogs — to net profit across your entire mix.</p>
        <div className="g4">
          <Stat label="gross_ws_rev" value={fmtK(totalWsListRev)} sub={`${totalUnits.toLocaleString()} units · list prices`}/>
          {isPct?<Stat label="distro_fee" value={fmtK(distroCost)} sub={`${safeDistroMargin}% of invoice`} tone="warn"/>
            :<Stat label="effective_rev" value={fmtK(effectiveRev)} sub={isFlatMode?'flat price × units':`list − ${safeDistroMargin}% discount`} tone="pos"/>}
          <Stat label="sales_cost" value={fmtK(salesCost)} sub={`${safeSalesPct}% of ${isPct?'gross':'effective'}`} tone="warn"/>
          <Stat label="consumer_retail" value={fmtK(totalConsumerRev)} sub="what stores charge"/>
        </div>
        <div style={{marginTop:16}}>
          <Waterfall caption="every deduction from gross invoice down to net profit."
            lines={[
              {label:'gross_ws_revenue',value:fmtK(totalWsListRev),sign:'+ '},
              ...(!isPct&&!isFlatMode?[{label:`distro_discount  (${safeDistroMargin.toFixed(1)}% off list)`,value:fmtK(wholesaleDiscount),sign:'− ',tone:'neg'}]:[]),
              ...(isPct?[{label:`distro_fee  (${safeDistroMargin}% of invoice)`,value:fmtK(distroCost),sign:'− ',tone:'warn'}]:[]),
              {label:`sales_commission  (${safeSalesPct}% of ${isPct?'gross':'effective'})`,value:fmtK(salesCost),sign:'− ',tone:'warn'},
              {label:'total_cogs',value:fmtK(totalCOGS),sign:'− ',tone:'neg'},
              {label:`samples  (${safeSampleRate}% at avg cogs)`,value:fmtK(sampleCost),sign:'− ',tone:'warn'}
            ]}
            total={fmtK(netProfit)}
            totalLabel={`net_profit  (${netMargin.toFixed(1)}% margin)`}/>
        </div>
      </>}
    </Section>

    {hasProducts&&<Section idx={3} title="product-level breakdown" active>
      <p className="section-desc">per-sku distro math. <code>to_distro</code> = what they pay you, <code>net/u</code> = what you keep after cogs, distro, and reps.</p>
      <div className="sku-table">
        <table>
          <thead><tr>
            <th>sku</th><th>category</th><th>units</th><th>cogs</th><th>ws_list</th>
            {!isPct&&<th>to_distro</th>}<th>retail</th><th>{isPct?'distro_fee':'discount'}</th>
            <th>sales</th><th>net/u</th><th>margin</th>
          </tr></thead>
          <tbody>
            {products.map(p=>{
              const pEff=isPct?p.wsList:(isFlatMode?p.wsList:p.wsList*(1-safeDistroMargin/100));
              const pDistro=isPct?p.wsList*(safeDistroMargin/100):(isFlatMode?0:p.wsList*(safeDistroMargin/100));
              const pSales=pEff*(safeSalesPct/100);
              const pSampleUnits=Math.ceil(p.units*(safeSampleRate/100));
              const pSample=p.units>0?(pSampleUnits*p.totalCOGS)/p.units:0;
              const pNet=pEff-(isPct?pDistro:0)-pSales-p.totalCOGS-pSample;
              const pNetPct=pEff>0?(pNet/pEff*100):0;
              const band=bandForMargin(pNetPct);
              return(<tr key={p.id}>
                <td className="sku-name">{p.skuName||`${p.grade||p.tier||p.prType||p.oilType||''} ${p.size||p.weight||''}`}</td>
                <td><span className="cat-tag">{p.category}</span></td>
                <td>{p.units.toLocaleString()}</td>
                <td>{fmt(p.totalCOGS)}</td>
                <td className="pos">{fmt(p.wsList)}</td>
                {!isPct&&<td className="warn">{fmt(pEff)}</td>}
                <td>{fmt(p.consumerRetail||0)}</td>
                <td className="warn">{fmt(pDistro)}</td>
                <td className="warn">{fmt(pSales)}</td>
                <td className={pNet>0?'pos bold':'neg bold'}>{fmt(pNet)}</td>
                <td><span className={`band-tag band-${band.cls}`}>{pNetPct.toFixed(1)}% {band.label}</span></td>
              </tr>);
            })}
          </tbody>
        </table>
      </div>
    </Section>}

    <Section idx={4} title="samples + compliance testing" active={hasProducts}>
      <p className="section-desc">samples and compliance testing are overhead. sample cost = sample_pct × total_units × avg_cogs. testing cost is annual — cost × strains × batches/yr (licensed) or cost × product_types (hemp).</p>
      <div className="g3">
        <Field label="sample_rate" value={sampleRate} onChange={setSampleRate} suffix="%" hint="% of production given away"/>
        <Stat label="sample_units" value={sampleUnits.toLocaleString()} sub={`${safeSampleRate}% of ${totalUnits.toLocaleString()}`}/>
        <Stat label="sample_cost" value={fmtK(sampleCost)} sub={`at ${fmt(avgCOGS)}/u avg cogs`} tone="warn"/>
      </div>
      <div style={{marginTop:14}}>
        <div className="sub-head"><span className="mark">//</span><span className="title">compliance_testing</span><span className="note">— market toggle changes math</span></div>
        <Seg options={[
          {value:'licensed',label:'licensed  (ca / ny)'},
          {value:'hemp',label:'hemp'}
        ]} value={marketType} onChange={setMarketType}/>
        {marketType==='licensed'?<div className="g3" style={{marginTop:10}}>
          <Field label="cost_per_test" prefix="$" value={testCost} onChange={setTestCost} hint="per strain / batch"/>
          <Field label="num_strains" value={numStrains} onChange={setNumStrains}/>
          <Field label="batches_per_year" value={batchesPerYear} onChange={setBatchesPerYear} hint="per strain"/>
        </div>:<div className="g2" style={{marginTop:10}}>
          <Field label="cost_per_product_type" prefix="$" value={testCost} onChange={setTestCost} hint="annual"/>
          <Field label="num_product_types" value={hempProductTypes} onChange={setHempProductTypes}/>
        </div>}
        <div className="g4" style={{marginTop:14}}>
          <Stat label="annual_testing" value={fmtK(testingCostAnnual)} sub={marketType==='licensed'?`${numStrains} × ${batchesPerYear} × ${fmt(testCost)}`:`${hempProductTypes} × ${fmt(testCost)}`} tone="warn"/>
          <Stat label="monthly_testing" value={fmtK(testingCostAnnual/12)}/>
          <Stat label="total_overhead" value={fmtK(totalOverhead)} sub="testing + samples" tone="neg"/>
          <Stat label="overhead / unit" value={totalUnits>0?fmt(totalOverhead/totalUnits):'$0.00'} sub="added to effective cogs"/>
          <Stat label="net_after_annual_testing" value={fmtK(netAfterAnnualTesting)} sub="distro net − annual testing" tone={netAfterAnnualTesting>=0?'pos':'neg'}/>
        </div>
      </div>
    </Section>
  </div>);
}

Object.assign(window,{DistroTab});
