// hydor-page-intelligence.jsx — Performance Intelligence Engine
// Owner + cofounder only. All 5 modules + employee cost/profit analysis.

/* ============================================================
   INTELLIGENCE ENGINE
   ============================================================ */
function computeIntelligence(s, d, days) {
  const cutoff = new Date(); cutoff.setDate(cutoff.getDate() - days);
  const cutoffStr = cutoff.toISOString().slice(0, 10);
  const prevCutoff = new Date(cutoff); prevCutoff.setDate(prevCutoff.getDate() - days);
  const prevCutoffStr = prevCutoff.toISOString().slice(0, 10);

  const activeTx = (s.transactions || []).filter(t => !t.deleted);
  const periodTx = activeTx.filter(t => (t.date || '') >= cutoffStr);
  const prevTx   = activeTx.filter(t => (t.date||'') >= prevCutoffStr && (t.date||'') < cutoffStr);
  const sales    = periodTx.filter(t => t.type === 'sale');
  const prevSales= prevTx.filter(t => t.type === 'sale');

  // ---- MODULE 1: PRODUCTS ----
  const prodMap = {}; const prevProdMap = {};
  const addToMap = (map, t) => {
    const pid = t.productId; if (!pid) return;
    const txc = d.txc[t.id]; if (!txc) return;
    if (!map[pid]) map[pid] = { revenue: 0, cogs: 0, gp: 0, units: 0, txns: 0, prices: [] };
    map[pid].revenue += txc.subtotal || 0;
    map[pid].cogs    += txc.cogs || 0;
    map[pid].gp      += txc.profit || 0;
    map[pid].units   += Hydor.num(t.qty, 0);
    map[pid].txns++;
    map[pid].prices.push(Hydor.num(t.actualSell, 0));
  };
  sales.forEach(t => addToMap(prodMap, t));
  prevSales.forEach(t => addToMap(prevProdMap, t));

  const products = s.products.map(p => {
    const cur = prodMap[p.id] || { revenue:0,cogs:0,gp:0,units:0,txns:0,prices:[] };
    const prv = prevProdMap[p.id] || { revenue:0, units:0 };
    const margin = cur.revenue > 0 ? cur.gp / cur.revenue : 0;
    const avgPrice = cur.prices.length ? cur.prices.reduce((a,b)=>a+b,0)/cur.prices.length : 0;
    const vg = prv.units > 0 ? (cur.units - prv.units)/prv.units : null;
    const ps = d.productStats[p.id] || {};
    return { ...p, ...cur, margin, avgPrice, recPrice: ps.recPrice||0, velocityGrowth:vg,
      prevRevenue:prv.revenue, prevUnits:prv.units, remaining:ps.remaining||0 };
  }).filter(p => p.revenue > 0 || p.remaining > 0).sort((a,b) => b.revenue - a.revenue);

  // cross-sell
  const crossSell = {};
  const txByCust = {};
  sales.forEach(t => {
    const key = (t.date||'').slice(0,10)+'|'+(t.partyId||t.employee||'');
    if (!txByCust[key]) txByCust[key] = [];
    txByCust[key].push(t.productId);
  });
  Object.values(txByCust).forEach(pids => {
    for(let i=0;i<pids.length;i++) for(let j=i+1;j<pids.length;j++) {
      const pair=[pids[i],pids[j]].sort().join('|');
      crossSell[pair]=(crossSell[pair]||0)+1;
    }
  });
  const topCrossSell = Object.entries(crossSell).sort((a,b)=>b[1]-a[1]).slice(0,3).map(([pair,count])=>{
    const [a,b]=pair.split('|');
    const pa=s.products.find(p=>p.id===a); const pb=s.products.find(p=>p.id===b);
    return { a:pa?pa.name:a, b:pb?pb.name:b, count };
  });

  // ---- MODULE 2: PEOPLE ----
  const empHours={}, empVisits={}, empClosed={}, empDOW={}, empGP={}, empContracts={}, empNewCusts={}, empDealSizes={};
  (s.attendance||[]).filter(a=>a.type==='check_out'&&a.hoursWorked>0)
    .forEach(a=>{ empHours[a.userId]=(empHours[a.userId]||0)+(a.hoursWorked||0); });
  (s.attendance||[]).filter(a=>a.type==='visit_end')
    .forEach(a=>{ empVisits[a.userId]=(empVisits[a.userId]||0)+1; });
  const custFirstEmp={};
  activeTx.filter(t=>t.type==='sale'&&t.partyId&&t.employee).sort((a,b)=>(a.date||'')<(b.date||'')?-1:1)
    .forEach(t=>{ if(!custFirstEmp[t.partyId]) custFirstEmp[t.partyId]=t.employee; });
  sales.forEach(t=>{
    const u=s.users.find(u=>u.code===t.employee); if(!u) return;
    const txc=d.txc[t.id];
    empClosed[u.id]=(empClosed[u.id]||0)+1;
    if(txc){ empGP[u.id]=(empGP[u.id]||0)+(txc.profit||0); if(!empDealSizes[u.id])empDealSizes[u.id]=[]; empDealSizes[u.id].push(txc.subtotal||0); }
    const dow=new Date(t.date||Date.now()).getDay();
    if(!empDOW[u.id]) empDOW[u.id]=Array(7).fill(0);
    empDOW[u.id][dow]++;
    if(custFirstEmp[t.partyId]===t.employee) empNewCusts[u.id]=(empNewCusts[u.id]||0)+1;
  });
  activeTx.filter(t=>t.type==='maintenance_contract'&&t.employee).forEach(t=>{
    const u=s.users.find(u=>u.code===t.employee); if(u) empContracts[u.id]=(empContracts[u.id]||0)+1;
  });
  const DOW=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];

  const people = s.users.filter(u=>u.active&&u.role!=='owner'&&u.role!=='cofounder').map(u=>{
    const up=d.userPerf[u.id]||{};
    const hours=empHours[u.id]||0, visits=empVisits[u.id]||0, closed=empClosed[u.id]||0;
    const gp=empGP[u.id]||0, contracts=empContracts[u.id]||0, newCusts=empNewCusts[u.id]||0;
    const dealSizes=empDealSizes[u.id]||[];
    const avgDealSize=dealSizes.length?dealSizes.reduce((a,b)=>a+b,0)/dealSizes.length:0;
    const convRate=visits>0?closed/visits:null;
    const revPerHour=hours>0?(up.salesAllTime||0)/hours:null;
    const gpPerHour=hours>0?gp/hours:null;
    const monthlySalary=u.salary||0;
    const lb=d.leaveBalances&&d.leaveBalances[u.id];
    const monthsEmp=lb?lb.monthsEmployed:0;
    const totalSalaryCost=monthlySalary*Math.max(1,monthsEmp);
    const revenueROI=totalSalaryCost>0?(up.salesAllTime||0)/totalSalaryCost:null;
    const gpROI=totalSalaryCost>0?gp/totalSalaryCost:null;
    const netContrib=(up.salesAllTime||0)-totalSalaryCost;
    const salaryPct=(up.salesAllTime||0)>0?totalSalaryCost/(up.salesAllTime||1)*100:null;
    const costPerDeal=closed>0&&totalSalaryCost>0?totalSalaryCost/closed:null;
    const revPerVisit=visits>0?(up.salesAllTime||0)/visits:null;
    const bestDow=empDOW[u.id]?empDOW[u.id].indexOf(Math.max(...empDOW[u.id])):-1;
    const prodSales={};
    sales.filter(t=>{const pu=s.users.find(x=>x.code===t.employee);return pu&&pu.id===u.id;})
      .forEach(t=>{prodSales[t.productId]=(prodSales[t.productId]||0)+1;});
    const topProdId=Object.entries(prodSales).sort((a,b)=>b[1]-a[1])[0];
    const topProd=topProdId?s.products.find(p=>p.id===topProdId[0]):null;
    return { ...u, hours, visits, closed, gp, contracts, newCusts, avgDealSize,
      convRate, revPerHour, gpPerHour, monthlySalary, totalSalaryCost,
      revenueROI, gpROI, netContrib, salaryPct, costPerDeal, revPerVisit,
      bestDow:bestDow>=0?DOW[bestDow]:null,
      topProduct:topProd?topProd.name:null,
      monthSales:up.monthSales||0, salesAllTime:up.salesAllTime||0,
      target:u.monthlyTarget||0, attainment:up.attainment };
  }).filter(p=>p.salesAllTime>0||p.visits>0||p.closed>0)
    .sort((a,b)=>b.salesAllTime-a.salesAllTime);

  const avgConv=people.filter(p=>p.convRate!==null).reduce((a,p)=>a+p.convRate,0)/Math.max(1,people.filter(p=>p.convRate!==null).length);

  // ---- MODULE 3: CUSTOMERS ----
  const custMap={};
  activeTx.filter(t=>t.type==='sale'||t.type==='maintenance_contract').forEach(t=>{
    if(!t.partyId) return;
    const txc=d.txc[t.id]; if(!txc) return;
    if(!custMap[t.partyId]) custMap[t.partyId]={revenue:0,txns:0,lastDate:'',products:{},contracts:0};
    custMap[t.partyId].revenue+=txc.total||0;
    custMap[t.partyId].txns++;
    if((t.date||'')>custMap[t.partyId].lastDate) custMap[t.partyId].lastDate=t.date||'';
    if(t.productId) custMap[t.partyId].products[t.productId]=(custMap[t.partyId].products[t.productId]||0)+1;
    if(t.type==='maintenance_contract') custMap[t.partyId].contracts++;
  });
  const customers=s.parties.filter(p=>p.type==='customer'&&custMap[p.id]).map(p=>{
    const c=custMap[p.id];
    const daysSince=c.lastDate?Math.floor((Date.now()-new Date(c.lastDate))/86400000):999;
    const churnRisk=daysSince>180?'high':daysSince>90?'medium':'low';
    const topProdId=Object.entries(c.products).sort((a,b)=>b[1]-a[1])[0];
    const topProd=topProdId?s.products.find(x=>x.id===topProdId[0]):null;
    return {...p,...c,daysSince,churnRisk,topProduct:topProd?topProd.name:null};
  }).sort((a,b)=>b.revenue-a.revenue);
  const highChurn=customers.filter(c=>c.churnRisk==='high').length;
  const avgCLV=customers.length?customers.reduce((a,c)=>a+c.revenue,0)/customers.length:0;
  const top20pct=Math.max(1,Math.ceil(customers.length*0.2));
  const top20rev=customers.slice(0,top20pct).reduce((a,c)=>a+c.revenue,0);
  const totalCustRev=customers.reduce((a,c)=>a+c.revenue,0);
  const top20share=totalCustRev>0?top20rev/totalCustRev:0;

  // ---- MODULE 4: FORECAST ----
  const monthly={};
  activeTx.filter(t=>t.type==='sale'||t.type==='maintenance_contract').forEach(t=>{
    const ym=(t.date||'').slice(0,7); if(!ym) return;
    const txc=d.txc[t.id]; if(!txc) return;
    if(!monthly[ym]) monthly[ym]={revenue:0,gp:0,txns:0};
    monthly[ym].revenue+=txc.subtotal||0;
    monthly[ym].gp+=txc.profit||0;
    monthly[ym].txns++;
  });
  const monthKeys=Object.keys(monthly).sort();
  const last6=monthKeys.slice(-6);
  const monthData=last6.map(ym=>({ym,...monthly[ym]}));
  const growthRates=monthData.slice(1).map((m,i)=>{
    const prev=monthData[i].revenue; return prev>0?(m.revenue-prev)/prev:0;
  });
  const avgGrowth=growthRates.length?growthRates.reduce((a,b)=>a+b,0)/growthRates.length:0;
  const lastMonthRev=monthData.length?monthData[monthData.length-1].revenue:0;
  const nextMonthForecast=lastMonthRev*(1+avgGrowth);
  const quarterForecast=nextMonthForecast*3;
  const confidence=monthData.length>=6?'high':monthData.length>=3?'medium':'low';
  const fixedCosts=d.recurringMonthly||0;
  const avgMargin=d.totals.margin||0;
  const breakeven=avgMargin>0?fixedCosts/avgMargin:null;

  // ---- MODULE 5: OPERATIONS ----
  const totalCosts=d.totals.costs||0;
  const totalSales=d.totals.sales||1;
  const costPerSale=sales.length>0?totalCosts/sales.length:0;
  const revenuePerCostJOD=totalCosts>0?totalSales/totalCosts:0;
  const totalVisits=(s.attendance||[]).filter(a=>a.type==='visit_end').length;
  const totalClosed=activeTx.filter(t=>t.type==='sale').length;
  const overallConv=totalVisits>0?totalClosed/totalVisits:0;
  const periodRevenue=sales.reduce((a,t)=>{const txc=d.txc[t.id];return a+(txc?txc.subtotal:0);},0);

  // ---- AUTO INSIGHTS ----
  const insights=[];
  const topProd=products[0];
  if(topProd) insights.push({ icon:'📦',priority:'high',module:'products',
    title:`${topProd.name} is your top revenue driver`,
    body:`Generated ${Hydor.fmtMoney0(topProd.revenue)} JD with ${(topProd.margin*100).toFixed(1)}% margin.${topProd.velocityGrowth!==null?(topProd.velocityGrowth>0?` Growing ${(topProd.velocityGrowth*100).toFixed(0)}%.`:` Down ${Math.abs(topProd.velocityGrowth*100).toFixed(0)}% — investigate.`):''}`,
    action:`Prioritize ${topProd.name} in sales. Stock: ${Hydor.fmtQty(topProd.remaining)} units.`,
    metric:Hydor.fmtMoney0(topProd.revenue)+' JD' });
  const topMarginProd=[...products].sort((a,b)=>b.margin-a.margin)[0];
  if(topMarginProd&&topMarginProd.id!==topProd?.id) insights.push({ icon:'💰',priority:'high',module:'products',
    title:`${topMarginProd.name} has highest margin`,
    body:`${(topMarginProd.margin*100).toFixed(1)}% gross margin — most profitable per JD sold.`,
    action:`Increase sales focus on ${topMarginProd.name}. Consider bundling with lower-margin products.`,
    metric:(topMarginProd.margin*100).toFixed(1)+'% margin' });
  if(highChurn>0) insights.push({ icon:'⚠️',priority:'high',module:'customers',
    title:`${highChurn} customer${highChurn>1?'s':''} at high churn risk`,
    body:`Haven't purchased in 6+ months. Combined value: ${Hydor.fmtMoney0(customers.filter(c=>c.churnRisk==='high').reduce((a,c)=>a+c.revenue,0))} JD.`,
    action:'Schedule immediate follow-up calls. Offer maintenance contract.',
    metric:highChurn+' at risk' });
  const topEmp=people[0];
  if(topEmp) insights.push({ icon:'🏆',priority:'medium',module:'people',
    title:`${topEmp.name} is your top performer`,
    body:`${Hydor.fmtMoney0(topEmp.salesAllTime)} JD all-time.${topEmp.convRate!==null?` Conversion: ${(topEmp.convRate*100).toFixed(0)}% vs team avg ${(avgConv*100).toFixed(0)}%.`:''}${topEmp.bestDow?` Best day: ${topEmp.bestDow}.`:''}`,
    action:`Share ${topEmp.name}'s approach. Assign premium leads.`,
    metric:Hydor.fmtMoney0(topEmp.salesAllTime)+' JD' });
  if(avgGrowth!==0) insights.push({ icon:'📈',priority:'medium',module:'forecast',
    title:avgGrowth>0?`Revenue growing ${(avgGrowth*100).toFixed(1)}%/month`:`Revenue declining — action needed`,
    body:`Forecast next month: ${Hydor.fmtMoney0(nextMonthForecast)} JD. Confidence: ${confidence}.`,
    action:avgGrowth>0?'Maintain momentum. Reflect growth in targets.':'Review product mix and customer pipeline.',
    metric:Hydor.fmtMoney0(nextMonthForecast)+' JD' });
  if(top20share>0.5) insights.push({ icon:'🎯',priority:'medium',module:'customers',
    title:`Top ${top20pct} clients = ${(top20share*100).toFixed(0)}% of revenue`,
    body:`Classic Pareto concentration.`,
    action:'Protect these relationships. Diversify by finding similar new clients.',
    metric:(top20share*100).toFixed(0)+'% concentration' });
  const lowROI=people.filter(p=>p.revenueROI!==null&&p.revenueROI<1.5);
  lowROI.forEach(p=>insights.push({ icon:'⚠️',priority:'high',module:'people',
    title:`${p.name} salary ROI below target (${p.revenueROI.toFixed(1)}×)`,
    body:`Revenue ${Hydor.fmtMoney0(p.salesAllTime)} JD vs salary cost ${Hydor.fmtMoney0(p.totalSalaryCost)} JD. Target is 3×.`,
    action:'Set performance improvement plan. Pair with top performer for mentoring.',
    metric:p.revenueROI.toFixed(1)+'× ROI' }));

  return { products, people, customers, monthData, topCrossSell, insights,
    avgConv, highChurn, avgCLV, top20share, top20pct,
    avgGrowth, nextMonthForecast, quarterForecast, confidence, lastMonthRev,
    fixedCosts, avgMargin, breakeven,
    costPerSale, revenuePerCostJOD, overallConv,
    totalVisits, totalClosed, periodRevenue };
}

/* ============================================================
   CHART COMPONENTS
   ============================================================ */
function InlineBar({ data, valueKey='revenue', labelKey='name', color='var(--accent)', height=160, fmtFn }) {
  const [hov, setHov] = React.useState(null);
  const max = Math.max(...data.map(d=>d[valueKey]||0), 1);
  const fmt = fmtFn || (v => Hydor.fmtMoney0(v)+' JD');
  return (
    <div style={{ position:'relative', height, display:'flex', alignItems:'flex-end', gap:4, paddingBottom:22 }}>
      {data.map((item,i) => {
        const pct = Math.max(2,((item[valueKey]||0)/max)*85);
        return (
          <div key={i} style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', height:'100%', justifyContent:'flex-end', minWidth:0, position:'relative' }}
            onMouseEnter={()=>setHov(i)} onMouseLeave={()=>setHov(null)}>
            {hov===i && (
              <div style={{ position:'absolute', bottom:'100%', left:'50%', transform:'translateX(-50%)', background:'var(--bg-2)', border:'1px solid var(--border)', borderRadius:8, padding:'4px 10px', fontSize:11, fontWeight:600, whiteSpace:'nowrap', color:'var(--text)', zIndex:10, boxShadow:'0 4px 12px rgba(0,0,0,.4)', marginBottom:4 }}>
                <div style={{ fontSize:10, color:'var(--text-2)' }}>{item[labelKey]}</div>
                <div>{fmt(item[valueKey]||0)}</div>
              </div>
            )}
            <div style={{ width:'70%', background:color, borderRadius:'4px 4px 0 0', height:pct+'%', opacity:hov!==null&&hov!==i?0.4:1, transition:'.15s' }} />
            <div style={{ fontSize:10, color:'var(--text-3)', marginTop:3, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', width:'100%', textAlign:'center' }}>
              {(String(item[labelKey]||'')).slice(0,9)}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function InlineLine({ data, valueKey='revenue', color='var(--accent)', height=120 }) {
  const [hov, setHov] = React.useState(null);
  if(!data.length) return <div style={{ height, display:'grid', placeItems:'center', color:'var(--text-3)', fontSize:12 }}>Not enough data yet</div>;
  const vals=data.map(d=>d[valueKey]||0);
  const min=Math.min(...vals); const max=Math.max(...vals,1);
  const W=400; const H=height-28;
  const pts=data.map((d,i)=>({
    x:data.length>1?(i/(data.length-1))*W:W/2,
    y:H-((d[valueKey]||0)-min)/(max-min||1)*(H-8),
  }));
  const pathD=pts.map((p,i)=>i===0?`M${p.x},${p.y}`:`L${p.x},${p.y}`).join(' ');
  const fillD=`${pathD} L${pts[pts.length-1].x},${H} L${pts[0].x},${H} Z`;
  return (
    <div style={{ position:'relative', height }}>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width:'100%', height:H, overflow:'visible' }}>
        <defs><linearGradient id="lg1" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor={color} stopOpacity="0.25"/><stop offset="1" stopColor={color} stopOpacity="0.02"/></linearGradient></defs>
        <path d={fillD} fill="url(#lg1)"/>
        <path d={pathD} fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
        {pts.map((p,i)=>(
          <circle key={i} cx={p.x} cy={p.y} r={hov===i?6:4} fill={color} stroke="var(--bg)" strokeWidth="2" style={{ cursor:'pointer' }}
            onMouseEnter={()=>setHov(i)} onMouseLeave={()=>setHov(null)}/>
        ))}
        {hov!==null&&pts[hov]&&(
          <foreignObject x={Math.min(pts[hov].x-55,W-120)} y={Math.max(0,pts[hov].y-50)} width="120" height="42">
            <div style={{ background:'var(--bg-2)', border:'1px solid var(--border)', borderRadius:8, padding:'4px 8px', fontSize:11, color:'var(--text)', textAlign:'center' }}>
              <div style={{ color:'var(--text-3)' }}>{data[hov].ym}</div>
              <div style={{ fontWeight:700 }}>{Hydor.fmtMoney0(data[hov][valueKey]||0)} JD</div>
            </div>
          </foreignObject>
        )}
      </svg>
      <div style={{ display:'flex', justifyContent:'space-between', fontSize:10, color:'var(--text-3)', marginTop:2 }}>
        {data.map((d,i)=><span key={i}>{(d.ym||'').slice(5)}</span>)}
      </div>
    </div>
  );
}

function RiskPill({ risk }) {
  const map = { high:['var(--neg)','#ff5b6b18'], medium:['var(--warn)','#ffc24b18'], low:['var(--pos)','#34d3a018'] };
  const [c,bg] = map[risk]||map.low;
  return <span style={{ background:bg, color:c, border:`1px solid ${c}44`, borderRadius:20, padding:'2px 9px', fontSize:11, fontWeight:700 }}>{risk}</span>;
}

function RecCard({ icon, title, body, action, metric, priority }) {
  const border = priority==='high'?'var(--accent)':priority==='medium'?'var(--warn)':'var(--border)';
  return (
    <div style={{ background:'var(--card)', border:`1px solid ${border}33`, borderLeft:`3px solid ${border}`, borderRadius:12, padding:'14px 16px', marginBottom:10 }}>
      <div style={{ display:'flex', alignItems:'flex-start', gap:10 }}>
        <span style={{ fontSize:18, lineHeight:1, flexShrink:0 }}>{icon}</span>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:13.5, fontWeight:700, marginBottom:4 }}>{title}</div>
          <div style={{ fontSize:12.5, color:'var(--text-2)', lineHeight:1.6, marginBottom:6 }}>{body}</div>
          <div style={{ fontSize:12, color:'var(--accent-2)', background:'var(--accent-soft)', borderRadius:7, padding:'4px 10px', display:'inline-block' }}>→ {action}</div>
        </div>
        {metric&&<div style={{ fontSize:13, fontWeight:700, color:'var(--text)', whiteSpace:'nowrap', marginLeft:8 }}>{metric}</div>}
      </div>
    </div>
  );
}

/* ============================================================
   SUB-COMPONENTS (avoid hook-in-IIFE issues)
   ============================================================ */
function PeopleTab({ intel, insights }) {
  const [sub, setSub] = React.useState('performance');
  const { people, avgConv, totalVisits, totalClosed } = intel;
  const subs = [['performance','📊 Performance'],['roi','💰 ROI vs Salary'],['costprofit','📉 Cost vs Profit'],['products','📦 Product Mix']];
  return (
    <div>
      <div className="stat-strip" style={{ gridTemplateColumns:'repeat(4,1fr)', marginBottom:16 }}>
        <div className="mini-stat" style={{ borderLeft:'3px solid var(--accent)' }}><div className="ms-label">Active reps</div><div className="ms-value">{people.length}</div></div>
        <div className="mini-stat" style={{ borderLeft:'3px solid var(--pos)' }}><div className="ms-label">Avg conversion</div><div className="ms-value">{(avgConv*100).toFixed(0)}%</div></div>
        <div className="mini-stat" style={{ borderLeft:'3px solid var(--accent-3)' }}><div className="ms-label">Total visits</div><div className="ms-value">{totalVisits}</div></div>
        <div className="mini-stat" style={{ borderLeft:'3px solid var(--warn)' }}><div className="ms-label">Closed deals</div><div className="ms-value">{totalClosed}</div></div>
      </div>
      {/* sub-tabs */}
      <div style={{ display:'flex', gap:4, marginBottom:14, flexWrap:'wrap' }}>
        {subs.map(([id,lbl])=>(
          <button key={id} onClick={()=>setSub(id)}
            style={{ padding:'6px 14px', borderRadius:8, border:'1px solid var(--border)', fontSize:12.5, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
              background:sub===id?'var(--accent)':'var(--surface)', color:sub===id?'#fff':'var(--text-2)', transition:'.12s' }}>
            {lbl}
          </button>
        ))}
      </div>

      {sub==='performance' && (
        <div className="hx-panel" style={{ overflow:'hidden', marginBottom:16 }}>
          <table className="hx-table">
            <thead><tr><th>Employee</th><th>Dept</th><th className="r">Revenue</th><th className="r">GP</th><th className="r">Visits</th><th className="r">Closed</th><th className="r">Conv%</th><th className="r">Avg deal</th><th className="r">Contracts</th><th className="r">New clients</th><th>Best day</th></tr></thead>
            <tbody>
              {people.map(p=>(
                <tr key={p.id}>
                  <td style={{ fontWeight:500 }}>{p.name}</td>
                  <td style={{ fontSize:12, color:'var(--text-2)' }}>{p.department}</td>
                  <td className="r num">{Hydor.fmtMoney0(p.salesAllTime)} JD</td>
                  <td className="r num" style={{ color:'var(--pos)' }}>{Hydor.fmtMoney0(p.gp)} JD</td>
                  <td className="r num">{p.visits}</td>
                  <td className="r num">{p.closed}</td>
                  <td className="r">{p.convRate!==null?<span style={{ color:p.convRate>avgConv?'var(--pos)':p.convRate<avgConv*0.7?'var(--neg)':'var(--warn)' }}>{(p.convRate*100).toFixed(0)}%</span>:'—'}</td>
                  <td className="r num">{p.avgDealSize>0?Hydor.fmtMoney0(p.avgDealSize)+' JD':'—'}</td>
                  <td className="r num">{p.contracts||'—'}</td>
                  <td className="r num">{p.newCusts||'—'}</td>
                  <td style={{ fontSize:12 }}>{p.bestDow||'—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {sub==='roi' && (
        <div>
          <div className="hx-panel" style={{ overflow:'hidden', marginBottom:12 }}>
            <table className="hx-table">
              <thead><tr><th>Employee</th><th className="r">Monthly salary</th><th className="r">Total salary paid</th><th className="r">Revenue</th><th className="r">Rev / salary</th><th className="r">GP / salary</th><th className="r">Net contribution</th><th className="r">Salary % of rev</th><th className="r">Cost per deal</th><th className="r">Rev per visit</th></tr></thead>
              <tbody>
                {people.map(p=>{
                  const rc=p.revenueROI===null?'var(--text-3)':p.revenueROI>=3?'var(--pos)':p.revenueROI>=1.5?'var(--warn)':'var(--neg)';
                  return (
                    <tr key={p.id}>
                      <td style={{ fontWeight:500 }}>{p.name}</td>
                      <td className="r num">{p.monthlySalary>0?Hydor.fmtMoney0(p.monthlySalary)+' JD':'—'}</td>
                      <td className="r num">{p.totalSalaryCost>0?Hydor.fmtMoney0(p.totalSalaryCost)+' JD':'—'}</td>
                      <td className="r num">{Hydor.fmtMoney0(p.salesAllTime)} JD</td>
                      <td className="r"><span style={{ color:rc, fontWeight:700 }}>{p.revenueROI!==null?p.revenueROI.toFixed(2)+'×':'—'}</span></td>
                      <td className="r"><span style={{ color:rc }}>{p.gpROI!==null?p.gpROI.toFixed(2)+'×':'—'}</span></td>
                      <td className="r"><span style={{ color:p.netContrib>=0?'var(--pos)':'var(--neg)', fontWeight:700 }}>{(p.netContrib>=0?'+':'')+Hydor.fmtMoney0(p.netContrib)+' JD'}</span></td>
                      <td className="r">{p.salaryPct!==null?<span style={{ color:p.salaryPct<30?'var(--pos)':p.salaryPct<60?'var(--warn)':'var(--neg)' }}>{p.salaryPct.toFixed(1)}%</span>:'—'}</td>
                      <td className="r num">{p.costPerDeal!==null?Hydor.fmtMoney0(p.costPerDeal)+' JD':'—'}</td>
                      <td className="r num">{p.revPerVisit!==null?Hydor.fmtMoney0(p.revPerVisit)+' JD':'—'}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          <div style={{ padding:'12px 16px', background:'var(--bg-2)', border:'1px solid var(--border)', borderRadius:10, fontSize:12.5, color:'var(--text-2)', lineHeight:1.7 }}>
            <b style={{ color:'var(--text)' }}>Rev / salary (target: 3×+)</b> — JD revenue per JD salary paid. &nbsp;
            <b style={{ color:'var(--text)' }}>Net contribution</b> — revenue minus salary cost: positive = covers their own cost. &nbsp;
            <b style={{ color:'var(--text)' }}>Salary % of rev</b> — below 30% is healthy; above 60% is a concern.
          </div>
        </div>
      )}

      {sub==='costprofit' && (
        <div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, marginBottom:16 }}>
            <div className="hx-panel hx-panel-pad">
              <div className="hx-h2" style={{ marginBottom:12 }}>Revenue vs salary cost</div>
              <InlineBar data={people.filter(p=>p.totalSalaryCost>0).slice(0,8).map(p=>({ name:p.name.split(' ')[0], value:p.salesAllTime }))}
                valueKey="value" labelKey="name" color="var(--accent)" />
            </div>
            <div className="hx-panel hx-panel-pad">
              <div className="hx-h2" style={{ marginBottom:12 }}>Gross profit generated</div>
              <InlineBar data={people.slice(0,8).map(p=>({ name:p.name.split(' ')[0], value:p.gp }))}
                valueKey="value" labelKey="name" color="var(--pos)" />
            </div>
          </div>
          <div className="hx-panel" style={{ overflow:'hidden', marginBottom:16 }}>
            <div style={{ padding:'14px 20px', borderBottom:'1px solid var(--border)' }}>
              <div className="hx-h2">Employee cost vs profit — full breakdown</div>
            </div>
            <table className="hx-table">
              <thead><tr><th>Employee</th><th>Role</th><th className="r">Monthly cost</th><th className="r">Revenue generated</th><th className="r">Gross profit</th><th className="r">Net contribution</th><th className="r">GP margin</th><th>Status</th></tr></thead>
              <tbody>
                {people.map(p=>{
                  const gpMargin=p.salesAllTime>0?p.gp/p.salesAllTime:0;
                  const status=p.revenueROI===null?'No salary data':p.revenueROI>=3?'✅ High ROI':p.revenueROI>=1.5?'⚠️ Moderate':p.netContrib<0?'❌ Below cost':'⚠️ Low ROI';
                  return (
                    <tr key={p.id}>
                      <td style={{ fontWeight:500 }}>{p.name}</td>
                      <td style={{ fontSize:12, color:'var(--text-2)' }}>{p.role}</td>
                      <td className="r num">{p.monthlySalary>0?Hydor.fmtMoney0(p.monthlySalary)+' JD/mo':'—'}</td>
                      <td className="r num">{Hydor.fmtMoney0(p.salesAllTime)} JD</td>
                      <td className="r num" style={{ color:'var(--pos)' }}>{Hydor.fmtMoney0(p.gp)} JD</td>
                      <td className="r"><span style={{ fontWeight:700, color:p.netContrib>=0?'var(--pos)':'var(--neg)' }}>{(p.netContrib>=0?'+':'')+Hydor.fmtMoney0(p.netContrib)+' JD'}</span></td>
                      <td className="r"><span style={{ color:gpMargin>0.3?'var(--pos)':gpMargin>0.15?'var(--warn)':'var(--neg)' }}>{(gpMargin*100).toFixed(1)}%</span></td>
                      <td style={{ fontSize:12 }}>{status}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12 }}>
            {people.filter(p=>p.monthlySalary>0).map(p=>(
              <div key={p.id} className="hx-panel hx-panel-pad" style={{ borderLeft:`3px solid ${p.netContrib>=0?'var(--pos)':p.revenueROI!==null&&p.revenueROI>=1.5?'var(--warn)':'var(--neg)'}` }}>
                <div style={{ fontSize:13.5, fontWeight:700, marginBottom:6 }}>{p.name}</div>
                <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
                  <div style={{ display:'flex', justifyContent:'space-between', fontSize:12 }}><span style={{ color:'var(--text-2)' }}>Monthly cost</span><span>{Hydor.fmtMoney0(p.monthlySalary)} JD</span></div>
                  <div style={{ display:'flex', justifyContent:'space-between', fontSize:12 }}><span style={{ color:'var(--text-2)' }}>Revenue</span><span style={{ color:'var(--accent-2)', fontWeight:600 }}>{Hydor.fmtMoney0(p.salesAllTime)} JD</span></div>
                  <div style={{ display:'flex', justifyContent:'space-between', fontSize:12 }}><span style={{ color:'var(--text-2)' }}>GP</span><span style={{ color:'var(--pos)', fontWeight:600 }}>{Hydor.fmtMoney0(p.gp)} JD</span></div>
                  <div style={{ marginTop:4, paddingTop:4, borderTop:'1px solid var(--border-2)', display:'flex', justifyContent:'space-between', fontSize:13, fontWeight:700 }}>
                    <span>Net</span>
                    <span style={{ color:p.netContrib>=0?'var(--pos)':'var(--neg)' }}>{(p.netContrib>=0?'+':'')+Hydor.fmtMoney0(p.netContrib)} JD</span>
                  </div>
                  <div style={{ height:6, background:'var(--grid)', borderRadius:4, marginTop:4, overflow:'hidden' }}>
                    <div style={{ height:'100%', borderRadius:4, width:Math.min(100,p.revenueROI!==null?p.revenueROI/5*100:0)+'%', background:p.netContrib>=0?'var(--pos)':'var(--neg)', transition:'.3s' }} />
                  </div>
                  <div style={{ fontSize:10, color:'var(--text-3)', textAlign:'right' }}>{p.revenueROI!==null?p.revenueROI.toFixed(1)+'× ROI':'No salary data'}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {sub==='products' && (
        <div className="hx-panel" style={{ overflow:'hidden', marginBottom:16 }}>
          <table className="hx-table">
            <thead><tr><th>Employee</th><th>Top product</th><th className="r">Contracts</th><th className="r">Avg deal size</th><th className="r">Rev/hour</th><th className="r">GP/hour</th><th className="r">Rev/visit</th></tr></thead>
            <tbody>
              {people.map(p=>(
                <tr key={p.id}>
                  <td style={{ fontWeight:500 }}>{p.name}</td>
                  <td style={{ color:'var(--accent-2)' }}>{p.topProduct||'—'}</td>
                  <td className="r num">{p.contracts||'—'}</td>
                  <td className="r num">{p.avgDealSize>0?Hydor.fmtMoney0(p.avgDealSize)+' JD':'—'}</td>
                  <td className="r num" style={{ color:'var(--pos)' }}>{p.revPerHour?Hydor.fmtMoney0(p.revPerHour)+' JD':'—'}</td>
                  <td className="r num" style={{ color:'var(--accent-2)' }}>{p.gpPerHour?Hydor.fmtMoney0(p.gpPerHour)+' JD':'—'}</td>
                  <td className="r num">{p.revPerVisit?Hydor.fmtMoney0(p.revPerVisit)+' JD':'—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <div className="hx-h2" style={{ marginBottom:10, marginTop:8 }}>Recommendations</div>
      {insights.filter(i=>i.module==='people').map((ins,i)=><RecCard key={i} {...ins} />)}
      {insights.filter(i=>i.module==='people').length===0&&(
        <p style={{ color:'var(--text-3)', fontSize:13 }}>Add attendance records and completed visits to unlock deeper insights.</p>
      )}
    </div>
  );
}

/* ============================================================
   MAIN PAGE
   ============================================================ */
function IntelligencePage() {
  const s = useHydor();
  const d = useDerive();
  const [days, setDays] = React.useState(90);
  const [tab, setTab] = React.useState('products');

  const intel = React.useMemo(() => {
    try { return computeIntelligence(s, d, days); }
    catch(e) { console.error('[Intelligence]', e); return null; }
  }, [s, d, days]);

  if (!intel) return (
    <div className="hx-panel hx-panel-pad" style={{ textAlign:'center', padding:40 }}>
      <div style={{ fontSize:28, marginBottom:8 }}>⚙️</div>
      <p style={{ color:'var(--text-2)', fontSize:14 }}>Not enough data yet. Add transactions and the engine will activate.</p>
    </div>
  );

  const { products, customers, monthData, topCrossSell, insights,
    highChurn, avgCLV, top20share, top20pct,
    avgGrowth, nextMonthForecast, quarterForecast, confidence, lastMonthRev,
    fixedCosts, avgMargin, breakeven,
    costPerSale, revenuePerCostJOD, overallConv,
    totalVisits, totalClosed, periodRevenue } = intel;

  const TABS = [
    { id:'products', label:'📦 Products' },
    { id:'people',   label:'👤 People' },
    { id:'customers',label:'🤝 Customers' },
    { id:'forecast', label:'📈 Forecast' },
    { id:'operations',label:'⚙️ Operations' },
  ];

  return (
    <div className="content-narrow">
      {/* Header */}
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:20, flexWrap:'wrap', gap:12 }}>
        <div>
          <h2 style={{ fontSize:22, fontWeight:800, margin:0 }}>Performance Intelligence</h2>
          <div style={{ fontSize:12.5, color:'var(--text-3)', marginTop:3 }}>Formula-driven analysis of all company data · Owner access only</div>
        </div>
        <div style={{ display:'flex', gap:6 }}>
          {[30,90,180,365].map(d=>(
            <button key={d} onClick={()=>setDays(d)}
              style={{ padding:'6px 14px', borderRadius:8, border:'1px solid var(--border)', fontSize:12.5, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
                background:days===d?'var(--accent)':'var(--surface)', color:days===d?'#fff':'var(--text-2)', transition:'.12s' }}>
              {d}d
            </button>
          ))}
        </div>
      </div>

      {/* Top 3 insights */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(240px,1fr))', gap:12, marginBottom:24 }}>
        {insights.slice(0,3).map((ins,i)=>(
          <div key={i} onClick={()=>setTab(ins.module)} style={{ background:'var(--card)', border:'1px solid var(--border)', borderRadius:14, padding:'16px 18px', cursor:'pointer' }}
            onMouseEnter={e=>e.currentTarget.style.borderColor='var(--accent)'}
            onMouseLeave={e=>e.currentTarget.style.borderColor='var(--border)'}>
            <div style={{ fontSize:22, marginBottom:8 }}>{ins.icon}</div>
            <div style={{ fontSize:14, fontWeight:700, marginBottom:5, lineHeight:1.35 }}>{ins.title}</div>
            <div style={{ fontSize:12, color:'var(--text-2)', lineHeight:1.55 }}>{ins.body.slice(0,110)}{ins.body.length>110?'…':''}</div>
            <div style={{ marginTop:8, fontSize:18, fontWeight:800, color:'var(--accent-2)' }}>{ins.metric}</div>
          </div>
        ))}
      </div>

      {/* Module tabs */}
      <div style={{ display:'flex', gap:4, background:'var(--bg-2)', borderRadius:12, padding:4, marginBottom:20, border:'1px solid var(--border)', overflowX:'auto' }}>
        {TABS.map(t=>(
          <button key={t.id} onClick={()=>setTab(t.id)}
            style={{ flex:1, padding:'9px 12px', borderRadius:9, border:'none', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit', whiteSpace:'nowrap', transition:'.12s',
              background:tab===t.id?'var(--card)':'transparent', color:tab===t.id?'var(--text)':'var(--text-2)',
              boxShadow:tab===t.id?'0 2px 8px rgba(0,0,0,.25)':'none' }}>
            {t.label}
          </button>
        ))}
      </div>

      {/* Products */}
      {tab==='products' && (
        <div>
          <div className="stat-strip" style={{ gridTemplateColumns:'repeat(4,1fr)', marginBottom:16 }}>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--accent)' }}><div className="ms-label">Products tracked</div><div className="ms-value">{products.length}</div></div>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--pos)' }}><div className="ms-label">Period revenue</div><div className="ms-value">{Hydor.fmtMoney0(periodRevenue)}</div></div>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--accent-3)' }}><div className="ms-label">Avg margin</div><div className="ms-value">{(avgMargin*100).toFixed(1)}%</div></div>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--warn)' }}><div className="ms-label">Top product</div><div className="ms-value" style={{ fontSize:13 }}>{products[0]?products[0].name.slice(0,14):'—'}</div></div>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, marginBottom:16 }}>
            <div className="hx-panel hx-panel-pad"><div className="hx-h2" style={{ marginBottom:12 }}>Revenue by product</div>
              <InlineBar data={products.slice(0,8)} valueKey="revenue" labelKey="name" color="var(--accent)" /></div>
            <div className="hx-panel hx-panel-pad"><div className="hx-h2" style={{ marginBottom:12 }}>Margin by product</div>
              <InlineBar data={products.slice(0,8)} valueKey="margin" labelKey="name" color="var(--pos)" fmtFn={v=>(v*100).toFixed(1)+'%'} /></div>
          </div>
          <div className="hx-panel" style={{ overflow:'hidden', marginBottom:16 }}>
            <table className="hx-table">
              <thead><tr><th>Product</th><th className="r">Revenue</th><th className="r">Units</th><th className="r">Margin</th><th className="r">Avg price</th><th className="r">Trend</th><th className="r">Stock</th></tr></thead>
              <tbody>
                {products.map(p=>(
                  <tr key={p.id}>
                    <td style={{ fontWeight:500 }}>{p.name}</td>
                    <td className="r num">{Hydor.fmtMoney0(p.revenue)} JD</td>
                    <td className="r num">{Hydor.fmtQty(p.units)}</td>
                    <td className="r"><span style={{ color:p.margin>0.3?'var(--pos)':p.margin>0.15?'var(--warn)':'var(--neg)' }}>{(p.margin*100).toFixed(1)}%</span></td>
                    <td className="r num">{Hydor.fmtMoney(p.avgPrice)}</td>
                    <td className="r">{p.velocityGrowth!==null?<span style={{ color:p.velocityGrowth>0?'var(--pos)':'var(--neg)' }}>{p.velocityGrowth>0?'▲':'▼'} {Math.abs(p.velocityGrowth*100).toFixed(0)}%</span>:'—'}</td>
                    <td className="r num" style={{ color:p.remaining<=2?'var(--neg)':'var(--text-2)' }}>{Hydor.fmtQty(p.remaining)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {topCrossSell.length>0&&(
            <div className="hx-panel hx-panel-pad" style={{ marginBottom:16 }}>
              <div className="hx-h2" style={{ marginBottom:10 }}>Cross-sell patterns (frequently bought together)</div>
              {topCrossSell.map((cs,i)=>(
                <div key={i} style={{ display:'flex', gap:10, alignItems:'center', padding:'8px 0', borderBottom:'1px solid var(--border-2)' }}>
                  <Badge color="blue">{cs.count}×</Badge>
                  <span style={{ fontWeight:500 }}>{cs.a}</span>
                  <span style={{ color:'var(--text-3)' }}>+</span>
                  <span style={{ fontWeight:500 }}>{cs.b}</span>
                </div>
              ))}
            </div>
          )}
          <div className="hx-h2" style={{ marginBottom:10 }}>Recommendations</div>
          {insights.filter(i=>i.module==='products').map((ins,i)=><RecCard key={i} {...ins} />)}
        </div>
      )}

      {/* People */}
      {tab==='people' && <PeopleTab intel={intel} insights={insights} />}

      {/* Customers */}
      {tab==='customers' && (
        <div>
          <div className="stat-strip" style={{ gridTemplateColumns:'repeat(4,1fr)', marginBottom:16 }}>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--accent)' }}><div className="ms-label">Active customers</div><div className="ms-value">{customers.length}</div></div>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--pos)' }}><div className="ms-label">Avg CLV</div><div className="ms-value">{Hydor.fmtMoney0(avgCLV)} JD</div></div>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--neg)' }}><div className="ms-label">High churn risk</div><div className="ms-value" style={{ color:highChurn>0?'var(--neg)':'var(--pos)' }}>{highChurn}</div></div>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--warn)' }}><div className="ms-label">Top 20% share</div><div className="ms-value">{(top20share*100).toFixed(0)}%</div></div>
          </div>
          <div className="hx-panel" style={{ overflow:'hidden', marginBottom:16 }}>
            <table className="hx-table">
              <thead><tr><th>Customer</th><th className="r">Total revenue</th><th className="r">Transactions</th><th className="r">Last purchase</th><th>Churn risk</th><th>Top product</th></tr></thead>
              <tbody>
                {customers.map(c=>(
                  <tr key={c.id}>
                    <td style={{ fontWeight:500 }}>{c.name}</td>
                    <td className="r num">{Hydor.fmtMoney0(c.revenue)} JD</td>
                    <td className="r num">{c.txns}</td>
                    <td className="r" style={{ fontSize:12 }}>{c.lastDate?Hydor.fmtDate(c.lastDate):'—'} <span style={{ color:'var(--text-3)' }}>({c.daysSince}d)</span></td>
                    <td><RiskPill risk={c.churnRisk} /></td>
                    <td style={{ fontSize:12, color:'var(--text-2)' }}>{c.topProduct||'—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="hx-h2" style={{ marginBottom:10 }}>Recommendations</div>
          {insights.filter(i=>i.module==='customers').map((ins,i)=><RecCard key={i} {...ins} />)}
        </div>
      )}

      {/* Forecast */}
      {tab==='forecast' && (
        <div>
          <div className="stat-strip" style={{ gridTemplateColumns:'repeat(4,1fr)', marginBottom:16 }}>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--accent)' }}><div className="ms-label">Monthly growth</div><div className="ms-value" style={{ color:avgGrowth>=0?'var(--pos)':'var(--neg)' }}>{avgGrowth>=0?'+':''}{(avgGrowth*100).toFixed(1)}%</div></div>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--pos)' }}><div className="ms-label">Next month forecast</div><div className="ms-value">{Hydor.fmtMoney0(nextMonthForecast)} JD</div></div>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--accent-3)' }}><div className="ms-label">Quarter forecast</div><div className="ms-value">{Hydor.fmtMoney0(quarterForecast)} JD</div></div>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--warn)' }}><div className="ms-label">Confidence</div><div className="ms-value" style={{ fontSize:14, textTransform:'capitalize' }}>{confidence}</div></div>
          </div>
          <div className="hx-panel hx-panel-pad" style={{ marginBottom:16 }}>
            <div className="hx-h2" style={{ marginBottom:16 }}>Monthly revenue trend</div>
            <InlineLine data={monthData} valueKey="revenue" color="var(--accent)" height={160} />
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, marginBottom:16 }}>
            <div className="hx-panel hx-panel-pad">
              <div className="hx-h2" style={{ marginBottom:8 }}>Break-even analysis</div>
              <div style={{ fontSize:28, fontWeight:800, color:'var(--accent-2)', marginBottom:4 }}>{breakeven?Hydor.fmtMoney0(breakeven)+' JD':'—'}</div>
              <div style={{ fontSize:12.5, color:'var(--text-2)', lineHeight:1.55 }}>Monthly revenue needed to cover fixed costs of {Hydor.fmtMoney0(fixedCosts)} JD at {(avgMargin*100).toFixed(1)}% avg margin.</div>
            </div>
            <div className="hx-panel hx-panel-pad">
              <div className="hx-h2" style={{ marginBottom:8 }}>Confidence: {confidence}</div>
              <div style={{ fontSize:13.5, color:confidence==='high'?'var(--pos)':confidence==='medium'?'var(--warn)':'var(--neg)', marginBottom:6 }}>{monthData.length} months of data</div>
              <div style={{ fontSize:12.5, color:'var(--text-2)', lineHeight:1.55 }}>{confidence==='low'?'Accumulate 6+ months for stronger forecasts.':confidence==='medium'?'Improving. More data will increase accuracy.':'Strong dataset. Forecasts are reliable.'}</div>
            </div>
          </div>
          <div className="hx-h2" style={{ marginBottom:10 }}>Recommendations</div>
          {insights.filter(i=>i.module==='forecast').map((ins,i)=><RecCard key={i} {...ins} />)}
        </div>
      )}

      {/* Operations */}
      {tab==='operations' && (
        <div>
          <div className="stat-strip" style={{ gridTemplateColumns:'repeat(4,1fr)', marginBottom:16 }}>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--accent)' }}><div className="ms-label">Cost per sale</div><div className="ms-value">{Hydor.fmtMoney0(costPerSale)} JD</div></div>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--pos)' }}><div className="ms-label">Revenue per cost JD</div><div className="ms-value">{revenuePerCostJOD.toFixed(2)}×</div></div>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--accent-3)' }}><div className="ms-label">Visit → close rate</div><div className="ms-value">{(overallConv*100).toFixed(0)}%</div></div>
            <div className="mini-stat" style={{ borderLeft:'3px solid var(--warn)' }}><div className="ms-label">Total visits</div><div className="ms-value">{totalVisits}</div></div>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, marginBottom:16 }}>
            <div className="hx-panel hx-panel-pad">
              <div className="hx-h2" style={{ marginBottom:12 }}>Monthly GP trend</div>
              <InlineLine data={monthData} valueKey="gp" color="var(--pos)" height={140} />
            </div>
            <div className="hx-panel hx-panel-pad">
              <div className="hx-h2" style={{ marginBottom:8 }}>Efficiency metrics</div>
              {[
                { label:'Revenue per cost JD', value:revenuePerCostJOD.toFixed(2)+'×', good:revenuePerCostJOD>2 },
                { label:'Visit → close rate', value:(overallConv*100).toFixed(0)+'%', good:overallConv>0.3 },
                { label:'Fixed cost coverage', value:lastMonthRev>0&&fixedCosts>0?((lastMonthRev/fixedCosts)*100).toFixed(0)+'%':'—', good:lastMonthRev>fixedCosts },
                { label:'Cost per sale', value:Hydor.fmtMoney0(costPerSale)+' JD', good:costPerSale<300 },
              ].map((m,i)=>(
                <div key={i} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'8px 0', borderBottom:'1px solid var(--border-2)' }}>
                  <span style={{ fontSize:13, color:'var(--text-2)' }}>{m.label}</span>
                  <span style={{ fontWeight:700, color:m.good?'var(--pos)':'var(--warn)' }}>{m.value}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="hx-panel hx-panel-pad" style={{ marginBottom:16 }}>
            <div className="hx-h2" style={{ marginBottom:10 }}>What these metrics mean</div>
            <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
              <div style={{ fontSize:13, color:'var(--text-2)', lineHeight:1.7 }}><b style={{ color:'var(--text)' }}>Cost per sale ({Hydor.fmtMoney0(costPerSale)} JD):</b> Total operating costs divided by number of sales closed. Industry target: below 20% of average sale value.</div>
              <div style={{ fontSize:13, color:'var(--text-2)', lineHeight:1.7 }}><b style={{ color:'var(--text)' }}>Revenue per cost JD ({revenuePerCostJOD.toFixed(2)}×):</b> For every 1 JD spent, you generate {revenuePerCostJOD.toFixed(2)} JD in revenue. Target: above 3×.</div>
              <div style={{ fontSize:13, color:'var(--text-2)', lineHeight:1.7 }}><b style={{ color:'var(--text)' }}>Visit-to-close ({(overallConv*100).toFixed(0)}%):</b> Of all client visits, {(overallConv*100).toFixed(0)}% resulted in a sale. Water treatment industry target: 30–50%.</div>
            </div>
          </div>
          <div className="hx-h2" style={{ marginBottom:10 }}>Recommendations</div>
          <RecCard icon="⚙️" priority="medium" title="Optimize visit-to-close pipeline"
            body={`Current conversion: ${(overallConv*100).toFixed(0)}%. Each 5% improvement adds significant revenue without new leads.`}
            action="Identify lowest-conversion employees and coach on objection handling and product demonstration."
            metric={(overallConv*100).toFixed(0)+'% conv.'} />
          {insights.filter(i=>!['products','people','customers','forecast'].includes(i.module)).map((ins,i)=><RecCard key={i} {...ins} />)}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { IntelligencePage, computeIntelligence });
