/* ============ InsightsTab — terminal reskin of InsightsPanel ============
   Source: profit-calc-clean-source.html lines 2733-3019. Insight rules + math identical. */

function InsightsTab({products,distroState}){
  const distroMargin=distroState.distroMarginShared||10;
  const salesPct=distroState.salesPctShared||5;
  const sampleRate=distroState.sampleRateShared||3;
  const testingAnnual=distroState.testingAnnualShared||24000;

  const insights=useMemo(()=>{
    const list=[];
    if(products.length===0){
      list.push({type:'info',tag:'START',title:'no data yet',
        body:'add products across the flower, prerolls, vapes, and extracts tabs to unlock ai-powered profit analysis. the more product configurations you add, the more detailed the insights become.'});
      return list;
    }
    const cats={};
    products.forEach(p=>{if(!cats[p.category])cats[p.category]=[];cats[p.category].push(p);});
    const totalWsRev=products.reduce((s,p)=>s+p.wsList*p.units,0);
    const totalProfit=products.reduce((s,p)=>s+(p.wsList-p.totalCOGS)*p.units,0);
    const totalUnits=products.reduce((s,p)=>s+p.units,0);
    const totalCOGS=products.reduce((s,p)=>s+p.totalCOGS*p.units,0);
    const blendedCOGSPct=totalWsRev>0?totalCOGS/totalWsRev:0.40;

    const sorted=[...products].sort((a,b)=>(b.listMarginPct||0)-(a.listMarginPct||0));
    const best=sorted[0];const worst=sorted[sorted.length-1];
    const bestName=best.skuName||`${best.grade||best.tier||best.prType||best.oilType||''} ${best.size||best.weight||''}`.trim();
    const worstName=worst.skuName||`${worst.grade||worst.tier||worst.prType||worst.oilType||''} ${worst.size||worst.weight||''}`.trim();

    list.push({type:'profit',tag:'MARGIN',title:'highest wholesale margin',
      body:`your highest-margin sku is ${bestName} at ${(best.listMarginPct||0).toFixed(1)}% ws margin (${fmt(best.wsList-best.totalCOGS)} profit per unit on list of ${fmt(best.wsList)}). scale up. at ${(best.units*1.5).toLocaleString()} units (+50%), you'd generate an additional ${fmtK((best.wsList-best.totalCOGS)*best.units*0.5)} in gross profit.`});

    if((worst.listMarginPct||0)<30){
      list.push({type:'warning',tag:'ALERT',title:'low margin sku',
        body:`${worstName} has only a ${(worst.listMarginPct||0).toFixed(1)}% margin at ${fmt(worst.wsList)}. to hit 40%, raise list to ${fmt(worst.totalCOGS/0.6)} or reduce cogs below ${fmt(worst.wsList*0.6)}. options: (1) switch to cheaper packaging, (2) use a less expensive grade, (3) negotiate volume pricing on raw materials.`});
    }

    const lowRetMu=products.filter(p=>p.consumerRetail&&p.wsList&&((p.consumerRetail-p.wsList)/p.consumerRetail)<0.35);
    if(lowRetMu.length>0){
      list.push({type:'strategy',tag:'RETAIL',title:'retailer markup opportunity',
        body:`${lowRetMu.length} product(s) give retailers below 35% margin. stores resist stocking products that don't pay. consider: (1) lower your ws list to widen retailer margin, (2) emphasize turn rate — velocity beats margin, (3) offer intro pricing to prove sell-through before asking full price.`});
    }

    const catRevs=Object.entries(cats).map(([cat,prods])=>({cat,rev:prods.reduce((s,p)=>s+p.wsList*p.units,0),profit:prods.reduce((s,p)=>s+(p.wsList-p.totalCOGS)*p.units,0)}));
    const topCat=catRevs.sort((a,b)=>b.profit-a.profit)[0];
    list.push({type:'strategy',tag:'MIX',title:'product mix strategy',
      body:`${topCat.cat} is your strongest category at ${fmtK(topCat.profit)} gross ws profit (${(topCat.profit/Math.max(totalProfit,1)*100).toFixed(0)}% of total). ${catRevs.length<3?'diversify — more skus per shelf = more reorders and sales-team leverage.':`solid diversification across ${catRevs.length} categories.`}`});

    const glassProducts=products.filter(p=>p.pkgType&&String(p.pkgType).toLowerCase().includes('glass'));
    if(glassProducts.length>0){
      const savingsPerUnit=0.65;
      const totalSavings=glassProducts.reduce((s,p)=>s+savingsPerUnit*p.units,0);
      list.push({type:'savings',tag:'PKG',title:'packaging cost opt',
        body:`switching ${glassProducts.length} glass sku(s) to mylar saves ~${fmt(savingsPerUnit)}/unit (${fmtK(totalSavings)} total). mylar reduces breakage ~90%. strategy: miron/glass for premium indoor (justifies higher ws), mylar for deps/outdoor/smalls.`});
    }

    if(totalUnits<5000){
      list.push({type:'growth',tag:'SCALE',title:'scale for better unit economics',
        body:`at ${totalUnits.toLocaleString()} total units, you're paying premium on packaging and hardware. scale to 5k+ to unlock 15-25% material savings. tip: use ws floor strategically — larger initial orders at floor to prove sell-through, list price on reorders.`});
    }

    if(cats.prerolls){
      const handRolled=cats.prerolls.filter(p=>p.method==='Hand Roll');
      const machine=cats.prerolls.filter(p=>p.method==='Machine');
      if(handRolled.length>0&&machine.length>0){
        const handAvg=handRolled.reduce((s,p)=>s+p.totalCOGS,0)/handRolled.length;
        const machAvg=machine.reduce((s,p)=>s+p.totalCOGS,0)/machine.length;
        list.push({type:'manufacturing',tag:'MFG',title:'preroll production opt',
          body:`hand-rolled avg ${fmt(handAvg)} cogs vs ${fmt(machAvg)} machine (${fmt(handAvg-machAvg)} delta). for volume skus (1k+/mo), machine rolling saves ${fmtK((handAvg-machAvg)*1000)}/month. reserve hand for premium/limited drops.`});
      }
    }

    if(cats.prerolls?.some(p=>p.prType==='Hash Hole')){
      list.push({type:'marketing',tag:'MKT',title:'hash hole playbook',
        body:'hash holes command the highest ws in preroll. playbook: (1) film cross-section cuts for social — goes viral, drives retailer demand, (2) limit batch size to create scarcity, (3) branded papers visible in cross-section, (4) collab drops with known hash makers. premium ws makes these a margin powerhouse even at $5 labor.'});
    }

    if(cats.vapes){
      list.push({type:'strategy',tag:'VAPE',title:'vape portfolio strategy',
        body:'multi-tier: (1) distillate at aggressive ws to win doors — high margin, low cogs, (2) live resin premium ws for 2-3x margin, (3) cbn sleep blends = fastest-growing segment, (4) hemp: thca+thcv blends command premium. pro tip: exclusive strains per retailer prevent price shopping.'});
    }

    list.push({type:'sales',tag:'SALES',title:'sales + distribution playbook',
      body:`based on ${fmtK(totalWsRev)} ws revenue: (1) target 10-15 stores initially — prove sell-through before scaling, (2) first orders at floor price to win doors, list on reorders, (3) 2-3% cod discount improves cash flow, (4) 7-8% comm for new doors vs 5% reorders incentivizes growth, (5) track velocity per sku per store — cut slow movers. your list-vs-floor spread gives reps negotiating room without killing margins.`});

    list.push({type:'savings',tag:'TEST',title:'testing cost strategy',
      body:'minimize testing: (1) maximize batch sizes — double batch, halve per-unit cost, (2) fewer strains with higher volume (5 × big > 15 × small), (3) group testing orders to negotiate lab volume discounts, (4) hemp annual testing saves tens of thousands vs licensed batch-by-batch.'});

    const totalExpPct=blendedCOGSPct*100+distroMargin+salesPct+sampleRate*blendedCOGSPct;
    const fixedNote=`testing alone = ${fmtK(testingAnnual/12)}/mo. combined with distro (${distroMargin}%), sales (${salesPct}%), samples (${sampleRate}%), variable costs eat ${totalExpPct.toFixed(0)}% of every revenue dollar before rent/payroll.`;

    if(blendedCOGSPct>0.50){
      list.push({type:'warning',tag:'COGS',title:'forecast alert: cogs too high',
        body:`blended cogs is ${(blendedCOGSPct*100).toFixed(0)}% of ws revenue — more than half of every dollar. ${fixedNote} fix: (1) shift mix toward higher-margin skus (extracts/vapes typically 50-65% gm), (2) negotiate volume pricing on packaging/raws, (3) swap your lowest-margin sku for a better alternative — one swap can move the needle.`});
    }else if(blendedCOGSPct>0.40){
      list.push({type:'strategy',tag:'COGS',title:'forecast opt: blended margins',
        body:`${(blendedCOGSPct*100).toFixed(0)}% blended cogs is typical. ${fixedNote} push below 40%: (1) add more extract/vape skus (lower cogs ratio), (2) mylar on non-premium flower saves $0.50-1.00/unit, (3) bigger batches = lower per-unit testing, (4) machine-roll volume skus saves $2-3/joint.`});
    }else{
      list.push({type:'profit',tag:'COGS',title:'forecast: strong blended cogs',
        body:`excellent — ${(blendedCOGSPct*100).toFixed(0)}% blended cogs gives a healthy gm foundation. max profit: (1) scale volume (more stores, higher cadence) — unit economics are strong, (2) your margins can absorb aggressive floor pricing to win doors, (3) invest saved margin into marketing or better packaging to command higher ws.`});
    }

    if(distroMargin>12){
      list.push({type:'warning',tag:'DISTRO',title:'high distribution cost',
        body:`${distroMargin}% distro margin — above the ca standard of 10%. every 1% reduction saves ${fmtK(totalWsRev*0.01)}/month (${fmtK(totalWsRev*0.01*12)}/year). options: (1) negotiate — at your volume you have leverage, (2) flat-rate model (fixed discount vs % of gross), (3) self-distribution for 20+ stores in a metro.`});
    }

    if(salesPct>6){
      list.push({type:'strategy',tag:'COMM',title:'optimize commission structure',
        body:`${salesPct}% comm is above avg. tiered: (1) 5% base on reorders (low-effort repeats), (2) 7-8% on new doors (incentivizes growth), (3) quarterly volume bonuses beat higher per-order comm — aligns with profitability, (4) cap on large orders — a $5k order shouldn't pay 3x a $1.5k for the same stop.`});
    }

    list.push({type:'growth',tag:'PATH',title:'path to profitability',
      body:`current cost stack keeps ~${(100-totalExpPct).toFixed(0)}¢ of every revenue dollar before fixed. grow: (1) more doors — each new store adds incremental margin, (2) push reorder cadence from 1-2x/mo to 2-3x with budtender education + in-store promos, (3) raise avg order with multi-sku deals ("order 3+ and get floor pricing"), (4) review fixed costs quarterly — the #1 profitability killer is overhead outpacing revenue.`});

    return list;
  },[products,distroMargin,salesPct,sampleRate,testingAnnual]);

  /* Charts */
  const catData=useMemo(()=>{
    if(products.length===0)return[];
    const cats={};
    products.forEach(p=>{
      if(!cats[p.category])cats[p.category]={rev:0,profit:0,units:0,cogs:0};
      cats[p.category].rev+=p.wsList*p.units;
      cats[p.category].profit+=(p.wsList-p.totalCOGS)*p.units;
      cats[p.category].units+=p.units;
      cats[p.category].cogs+=p.totalCOGS*p.units;
    });
    return Object.entries(cats).map(([cat,d])=>({cat,rev:d.rev,profit:d.profit,units:d.units,cogs:d.cogs,margin:d.rev>0?((d.rev-d.cogs)/d.rev*100):0}));
  },[products]);

  const topProducts=useMemo(()=>
    [...products].sort((a,b)=>(b.wsList-b.totalCOGS)*b.units-(a.wsList-a.totalCOGS)*a.units).slice(0,8),
  [products]);

  const marginDist=useMemo(()=>{
    const buckets=[{label:'<20%',count:0},{label:'20-40%',count:0},{label:'40-60%',count:0},{label:'60-80%',count:0},{label:'80%+',count:0}];
    products.forEach(p=>{
      const m=p.listMarginPct||0;
      if(m<20)buckets[0].count++;else if(m<40)buckets[1].count++;else if(m<60)buckets[2].count++;else if(m<80)buckets[3].count++;else buckets[4].count++;
    });
    return buckets;
  },[products]);

  const maxCatProfit=catData.length?Math.max(...catData.map(c=>c.profit)):0;
  const maxTopProf=topProducts.length?Math.max(...topProducts.map(p=>(p.wsList-p.totalCOGS)*p.units)):0;
  const maxBucket=Math.max(1,...marginDist.map(b=>b.count));
  const hasProducts=products.length>0;

  return(<div className="calc-page">
    <div className="readme">
      <p><strong style={{color:'var(--text)'}}>ai_analyst.run</strong> — rule-based insights mined from your current product mix, distro settings, and forecast variables. each card is a surfaced recommendation with concrete numbers. {hasProducts?`analyzing ${products.length} sku${products.length>1?'s':''} across ${catData.length} categor${catData.length>1?'ies':'y'}.`:'add products to unlock the full analysis.'}</p>
    </div>

    {hasProducts&&<Section idx={1} title="at a glance" active>
      <p className="section-desc">the top-line shape of your business — mix, margins, and where the profit actually comes from.</p>
      <div className="g4">
        <Stat label="total_skus" value={String(products.length)} sub={`across ${catData.length} categor${catData.length>1?'ies':'y'}`}/>
        <Stat label="total_units" value={products.reduce((s,p)=>s+p.units,0).toLocaleString()}/>
        <Stat label="ws_revenue" value={fmtK(products.reduce((s,p)=>s+p.wsList*p.units,0))} tone="pos"/>
        <Stat label="gross_profit" value={fmtK(products.reduce((s,p)=>s+(p.wsList-p.totalCOGS)*p.units,0))} sub={`${(products.reduce((s,p)=>s+(p.wsList-p.totalCOGS)*p.units,0)/Math.max(products.reduce((s,p)=>s+p.wsList*p.units,0),1)*100).toFixed(1)}% blended gm`} tone="pos"/>
      </div>
    </Section>}

    {hasProducts&&<Section idx={2} title="category contribution" active>
      <p className="section-desc">which categories are pulling their weight. bars show gross profit contribution; margin % is the gm on each category's revenue.</p>
      <div className="cat-bars">
        {catData.sort((a,b)=>b.profit-a.profit).map(c=>{
          const band=bandForMargin(c.margin);
          return(<div key={c.cat} className="cat-row">
            <div className="cat-label">{c.cat}</div>
            <div className="cat-bar-track">
              <div className="cat-bar-fill" style={{width:`${maxCatProfit>0?(c.profit/maxCatProfit)*100:0}%`}}></div>
            </div>
            <div className="cat-val">{fmtK(c.profit)}</div>
            <div className="cat-margin"><span className={`band-tag band-${band.cls}`}>{c.margin.toFixed(1)}%</span></div>
            <div className="cat-units">{c.units.toLocaleString()}u</div>
          </div>);
        })}
      </div>
    </Section>}

    {hasProducts&&<Section idx={3} title="top profit generators" active>
      <p className="section-desc">the skus generating the most gross profit. these are your winners — protect volume, consider scaling.</p>
      <div className="top-list">
        {topProducts.map((p,i)=>{
          const profit=(p.wsList-p.totalCOGS)*p.units;
          const name=p.skuName||`${p.grade||p.tier||p.prType||p.oilType||''} ${p.size||p.weight||''}`.trim();
          return(<div key={p.id} className="top-row">
            <span className="top-rank">#{String(i+1).padStart(2,'0')}</span>
            <span className="top-name">{name}</span>
            <span className="cat-tag">{p.category}</span>
            <div className="top-bar-track">
              <div className="top-bar-fill" style={{width:`${maxTopProf>0?(profit/maxTopProf)*100:0}%`}}></div>
            </div>
            <span className="top-units">{p.units.toLocaleString()}u</span>
            <span className="top-profit pos">{fmtK(profit)}</span>
          </div>);
        })}
      </div>
    </Section>}

    {hasProducts&&<Section idx={4} title="margin distribution" active>
      <p className="section-desc">histogram of your skus by margin band. a healthy mix clusters in the 40-60% zone; heavy weight below 20% signals a pricing or cost problem.</p>
      <div className="hist">
        {marginDist.map((b,i)=>(
          <div key={i} className="hist-col">
            <div className="hist-val">{b.count}</div>
            <div className="hist-bar-outer">
              <div className="hist-bar-inner" style={{height:`${(b.count/maxBucket)*100}%`}}></div>
            </div>
            <div className="hist-label">{b.label}</div>
          </div>
        ))}
      </div>
    </Section>}

    <Section idx={hasProducts?5:1} title="ai recommendations" active>
      <p className="section-desc">rule-based analysis of your mix, distro settings, and forecast variables. each card surfaces a concrete number and a playbook.</p>
      <div className="insight-grid">
        {insights.map((ins,i)=>(
          <div key={i} className={`insight-card ins-${ins.type}`}>
            <div className="insight-head">
              <span className="insight-tag">[{ins.tag}]</span>
              <span className="insight-title">{ins.title}</span>
            </div>
            <p className="insight-body">{ins.body}</p>
          </div>
        ))}
      </div>
    </Section>
  </div>);
}

Object.assign(window,{InsightsTab});
