// Stockyard Drill-Down Engine — shared components for all Stockyard sections
// All components exported to window.* for cross-file use.
const { useState: sddSt, useMemo: sddMemo } = React;
const SDD_IN = new Set(['Opening','Purchase','Transfer In','Adjustment In','Stock Transfer In','Customer Return']);

// ── Internal helpers ───────────────────────────────────────────────────────
function sddDaysSince(dateStr) {
  if (!dateStr) return 9999;
  return Math.floor((Date.now() - new Date(dateStr).getTime()) / 86400000);
}
function sddGetMatPos(movements, syId, matId) {
  const rel = (movements||[]).filter(m => m.stockyardId === syId && m.materialId === matId);
  const inc = rel.filter(m => SDD_IN.has(m.type)).reduce((s,m) => s+(parseFloat(m.quantity)||0), 0);
  const out = rel.filter(m => !SDD_IN.has(m.type)).reduce((s,m) => s+(parseFloat(m.quantity)||0), 0);
  const wtE = rel.filter(m => SDD_IN.has(m.type) && parseFloat(m.rate)>0);
  const wtQ = wtE.reduce((s,m) => s+(parseFloat(m.quantity)||0), 0);
  const wtV = wtE.reduce((s,m) => s+(parseFloat(m.quantity)||0)*(parseFloat(m.rate)||0), 0);
  const avg = wtQ>0 ? Math.round(wtV/wtQ) : 0;
  const byType = {};
  rel.forEach(m => { byType[m.type] = (byType[m.type]||0)+1; });
  return { inc, out, cur: inc-out, avg, value: Math.round((inc-out)*avg), byType, count: rel.length };
}

// ── SYDrillSection — titled card panel inside drill-down ──────────────────
function SYDrillSection({ title, color, children }) {
  return (
    <div style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 12px',marginBottom:0}}>
      <div style={{fontWeight:700,fontSize:10.5,color:color||'var(--or)',marginBottom:8,paddingBottom:5,borderBottom:'2px solid '+(color||'var(--or)'),opacity:1,textTransform:'uppercase',letterSpacing:'.5px'}}>{title}</div>
      {children}
    </div>
  );
}
window.SYDrillSection = SYDrillSection;

// ── SYDrillKV — key-value detail row ──────────────────────────────────────
function SYDrillKV({ label, value, mono, bold, color }) {
  return (
    <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:4,paddingBottom:4,borderBottom:'1px dashed var(--bdr)',fontSize:11.5,gap:8}}>
      <span style={{color:'var(--txt2)',flexShrink:0}}>{label}</span>
      <span style={{fontWeight:bold?700:500,fontFamily:'var(--font)',color:color||'var(--txt)',textAlign:'right',wordBreak:'break-all'}}>{value}</span>
    </div>
  );
}
window.SYDrillKV = SYDrillKV;

// ── SYMovementHistory — reusable movement history table ───────────────────
function SYMovementHistory({ movements, stockyards, materials, stockyardId, materialId, limit }) {
  const allRel = sddMemo(() => {
    let r = (movements||[]);
    if (stockyardId) r = r.filter(m => m.stockyardId === stockyardId);
    if (materialId)  r = r.filter(m => m.materialId  === materialId);
    return [...r].sort((a,b) => (a.date||'').localeCompare(b.date||''));
  }, [movements, stockyardId, materialId]);

  const balMap = sddMemo(() => {
    let bal = 0; const map = {};
    allRel.forEach(mv => {
      const q = parseFloat(mv.quantity)||0;
      if (SDD_IN.has(mv.type)) bal += q; else bal -= q;
      map[mv.id] = Math.max(0, bal);
    });
    return map;
  }, [allRel]);

  const rows = sddMemo(() => [...allRel].reverse().slice(0, limit||50), [allRel, limit]);

  if (!rows.length) return <div style={{fontSize:11.5,color:'var(--txt3)',fontStyle:'italic',padding:'8px 0'}}>No movement history.</div>;

  return (
    <div style={{overflowX:'auto'}}>
      <table style={{width:'100%',borderCollapse:'collapse',fontSize:11.5,minWidth:500}}>
        <thead><tr style={{background:'#F9FAFB'}}>
          {(stockyardId && materialId
            ? ['Date','Type','Qty','Rate','Value','Balance After','Challan No.','By']
            : ['Date',!stockyardId?'Stockyard':'',!materialId?'Material':'','Type','Qty','Rate','Value','Balance After','Challan No.'].filter(Boolean)
          ).map(h => <th key={h} style={{padding:'5px 8px',textAlign:'left',fontWeight:700,fontSize:10.5,color:'var(--txt2)',borderBottom:'1px solid var(--bdr)',whiteSpace:'nowrap'}}>{h}</th>)}
        </tr></thead>
        <tbody>
          {rows.map(m => {
            const isIn = SDD_IN.has(m.type);
            return (
              <tr key={m.id} style={{borderBottom:'1px solid #F3F4F6'}}>
                <td style={{padding:'4px 8px',whiteSpace:'nowrap'}}>{window.fmtDate(m.date)}</td>
                {!stockyardId && <td style={{padding:'4px 8px',fontSize:11}}>{Store.name('stockyards',m.stockyardId)||'—'}</td>}
                {!materialId  && <td style={{padding:'4px 8px',fontWeight:500}}>{Store.name('materials',m.materialId)||'—'}</td>}
                <td style={{padding:'4px 8px'}}><span style={{fontSize:10,fontWeight:700,padding:'1px 5px',borderRadius:3,background:isIn?'#DCFCE7':'#FEE2E2',color:isIn?'#166534':'#991B1B'}}>{m.type}</span></td>
                <td style={{padding:'4px 8px',fontWeight:600,color:isIn?'var(--ok)':'var(--err)',fontFamily:'var(--font)'}}>{isIn?'+':'-'}{Number(m.quantity||0).toFixed(3)}</td>
                <td style={{padding:'4px 8px',color:'var(--txt2)'}}>{m.rate ? window.fmtCur(m.rate) : '—'}</td>
                <td style={{padding:'4px 8px'}}>{m.value ? window.fmtCur(m.value) : '—'}</td>
                <td style={{padding:'4px 8px',fontWeight:700,color:'var(--or)',fontFamily:'var(--font)'}}>{balMap[m.id]!=null ? Number(balMap[m.id]).toFixed(3) : '—'}</td>
                <td style={{padding:'4px 8px',fontFamily:'var(--font)',fontSize:11,color:'var(--txt2)'}}>{m.reference||m.challanNumber||'—'}</td>
                {stockyardId && materialId && <td style={{padding:'4px 8px',fontSize:11,color:'var(--txt2)'}}>{m.createdBy||'—'}</td>}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
window.SYMovementHistory = SYMovementHistory;

// ── SYPositionDrill — material stock position detail ──────────────────────
function SYPositionDrill({ row, movements, materials }) {
  const mat = sddMemo(() => (materials||[]).find(m=>m.id===row.materialId)||{}, [materials, row.materialId]);
  const pos = sddMemo(() => sddGetMatPos(movements, row.syId||row.stockyardId||row.syName, row.materialId), [movements, row]);
  const syId = row.syId || row.stockyardId;
  // Resolve syId from name if needed
  const resolvedSyId = sddMemo(() => {
    if (syId) return syId;
    const found = (Store.all('stockyards')||[]).find(s=>s.name===row.syName);
    return found ? found.id : null;
  }, [syId, row.syName]);

  return (
    <div style={{padding:'14px 16px 18px',background:'#FFF9F5',borderBottom:'2px solid var(--or-bdr)'}}>
      <div className="rg-3" style={{gap:10,marginBottom:12}}>
        <SYDrillSection title="Material Information" color="var(--or)">
          <SYDrillKV label="Material" value={row.name||mat.name||'—'} bold/>
          <SYDrillKV label="Unit of Measure" value={row.unit||mat.unit||'MT'}/>
          <SYDrillKV label="Conversion Factor" value={mat.conversionFactor!=null?mat.conversionFactor:'—'}/>
          <SYDrillKV label="Stockyard" value={row.syName||'—'}/>
          <SYDrillKV label="Last Movement" value={row.lastDate ? window.fmtDate(row.lastDate) : '—'}/>
        </SYDrillSection>
        <SYDrillSection title="Stock Position" color="#1D4ED8">
          <SYDrillKV label="Total Received" value={pos.inc.toFixed(3)+' '+(row.unit||'MT')} color="var(--ok)" bold/>
          <SYDrillKV label="Total Dispatched" value={pos.out.toFixed(3)+' '+(row.unit||'MT')} color="var(--err)"/>
          <SYDrillKV label="Current Stock" value={pos.cur.toFixed(3)+' '+(row.unit||'MT')} color="var(--or)" bold/>
          <SYDrillKV label="Average Rate" value={window.fmtCur(pos.avg)}/>
          <SYDrillKV label="Stock Value" value={window.fmtCur(pos.value)} color="var(--or)" bold/>
        </SYDrillSection>
        <SYDrillSection title="Activity by Type" color="#6D28D9">
          {Object.entries(pos.byType).map(([t,c]) => (
            <SYDrillKV key={t} label={t} value={c+' transactions'} color={SDD_IN.has(t)?'var(--ok)':'var(--err)'}/>
          ))}
          {!Object.keys(pos.byType).length && <div style={{fontSize:11.5,color:'var(--txt3)',fontStyle:'italic'}}>No transactions.</div>}
          <div style={{marginTop:6,paddingTop:6,borderTop:'1px solid var(--bdr)',fontWeight:600,fontSize:11.5,color:'var(--txt2)'}}>Total: {pos.count} transactions</div>
        </SYDrillSection>
      </div>
      {/* ── Opening Stock by Vendor — only shown when vendor-wise entries exist ── */}
      {(()=>{
        const openingMovs = (movements||[]).filter(m =>
          (m.stockyardId===resolvedSyId||m.stockyardId===syId) &&
          m.materialId===row.materialId &&
          m.type==='Opening' &&
          m.vendorId
        );
        if (!openingMovs.length) return null;
        const byVendor = {};
        openingMovs.forEach(m => {
          const v = m.vendorId;
          if (!byVendor[v]) byVendor[v] = { name: (Store.byId('vendors',v)||{}).name||v, qty: 0 };
          byVendor[v].qty += parseFloat(m.quantity)||0;
        });
        const vRows = Object.values(byVendor).sort((a,b)=>b.qty-a.qty);
        const totQ  = vRows.reduce((s,r)=>s+r.qty,0);
        return (
          <div style={{marginBottom:12}}>
            <SYDrillSection title="Opening Stock by Vendor" color="var(--info)">
              {vRows.map((v,i)=>(
                <SYDrillKV key={i} label={v.name}
                  value={v.qty.toFixed(3)+' '+(row.unit||mat.unit||'MT')}
                  color="var(--info)"
                  bold={false}/>
              ))}
              <div style={{marginTop:6,paddingTop:6,borderTop:'1px solid var(--bdr)',fontWeight:700,fontSize:11.5,display:'flex',justifyContent:'space-between'}}>
                <span style={{color:'var(--txt2)'}}>Total Opening</span>
                <span style={{color:'var(--info)'}}>{totQ.toFixed(3)} {row.unit||mat.unit||'MT'}</span>
              </div>
            </SYDrillSection>
          </div>
        );
      })()}
      <SYDrillSection title={'Movement History (Last 50) — ' + (row.name||mat.name||'')} color="#374151">
        <SYMovementHistory movements={movements} stockyardId={resolvedSyId} materialId={row.materialId} limit={50}/>
      </SYDrillSection>
    </div>
  );
}
window.SYPositionDrill = SYPositionDrill;

// ── SYRegisterDrill — single stock movement transaction detail ────────────
function SYRegisterDrill({ m, movements, materials }) {
  const mat = sddMemo(() => (materials||[]).find(x=>x.id===m.materialId)||{}, [materials, m.materialId]);
  const isIn = SDD_IN.has(m.type);

  const allInYard = sddMemo(() =>
    [...((movements||[]).filter(mv=>mv.stockyardId===m.stockyardId&&mv.materialId===m.materialId))]
      .sort((a,b) => (a.date||'').localeCompare(b.date||'')),
    [movements, m.stockyardId, m.materialId]
  );

  const balAfter = sddMemo(() => {
    let bal = 0;
    for (const mv of allInYard) {
      if (SDD_IN.has(mv.type)) bal += parseFloat(mv.quantity)||0;
      else bal -= parseFloat(mv.quantity)||0;
      if (mv.id === m.id) return Math.max(0, bal);
    }
    return null;
  }, [allInYard, m.id]);

  const trFreight = sddMemo(()=>{
    // Transport cost always uses net quantity (customer weighbridge / challan qty),
    // never the inventory deducted quantity. Use stored transportCost if present
    // (records saved after the fix), otherwise recompute from netQuantity × rate.
    if (m.transportCost != null && parseFloat(m.transportCost) > 0) return parseFloat(m.transportCost);
    const nq = parseFloat(m.netQuantity ?? m.quantity)||0;
    const tr = parseFloat(m.transportRate)||0;
    return nq * tr;
  },[m.transportCost, m.netQuantity, m.quantity, m.transportRate]);
  const hasTransport   = !!(m.transporterName||m.vehicleFull||m.transporterMasterId);
  const hasDestination = !!(m.destinationName||m.destinationType);

  return (
    <div style={{padding:'14px 18px 16px',background:'#FAFAF8',borderTop:'2px solid var(--or-bdr)'}}>

      {/* Row 1: 3-column — General · Source · Quantity & Financials */}
      <div className="dd-3col" style={{marginBottom:(hasTransport||hasDestination)?10:0}}>

        <SYDrillSection title="General Information" color="var(--or)">
          <SYDrillKV label="Transaction ID"  value={m.id?m.id.slice(0,8).toUpperCase():'—'} mono bold/>
          <SYDrillKV label="Date"            value={window.fmtDate(m.date)}/>
          <SYDrillKV label="Type"            value={m.type} color={isIn?'var(--ok)':'var(--err)'} bold/>
          <SYDrillKV label="Direction"       value={isIn?'Inward ↓':'Outward ↑'} color={isIn?'var(--ok)':'var(--err)'}/>
          <SYDrillKV label="Stockyard"       value={Store.name('stockyards',m.stockyardId)||'—'} bold/>
          <SYDrillKV label="Company"         value={Store.name('companies',m.companyId)||'—'}/>
          {m.reference    && <SYDrillKV label="Challan No."     value={m.reference}  mono/>}
          {m.poNumber     && <SYDrillKV label="Price Order"    value={m.poNumber}   mono/>}
          {m.notes        && <SYDrillKV label="Notes"          value={m.notes}/>}
          <SYDrillKV label="Created By"      value={m.createdBy||'—'}/>
        </SYDrillSection>

        <SYDrillSection title="Source Information" color="#1D4ED8">
          <SYDrillKV label="Movement Source Type" value={m.movementSourceType||'—'} bold/>
          {m.entityName
            ? <SYDrillKV label={m.movementSourceType||'Entity'} value={m.entityName} bold/>
            : m.movementSourceType && <SYDrillKV label="Source" value={m.movementSourceType||'—'}/>
          }
          {m.transferId && <SYDrillKV label="Transfer Ref" value={('SYT-'+m.transferId.slice(-6)).toUpperCase()} mono/>}
          {m.transferId && <SYDrillKV label="Source Type"  value="Yard Transfer" color="#1D4ED8"/>}
          <SYDrillKV label="Material" value={mat.name||Store.name('materials',m.materialId)||'—'} bold/>
          <SYDrillKV label="Unit"     value={mat.unit||'MT'}/>
        </SYDrillSection>

        <SYDrillSection title="Quantity & Financials" color="#B45309">
          {m.adjustmentEnabled ? (
            <>
              <SYDrillKV label="Net Quantity (Customer)"  value={Number(m.netQuantity||m.quantity||0).toFixed(3)+' '+(mat.unit||'MT')} bold color="var(--info)"/>
              <SYDrillKV label="Inv. Adjustment"          value="Enabled" bold color="var(--ok)"/>
              <SYDrillKV label="Adjustment Type"          value={m.adjustmentType||'—'} color="#166534"/>
              <SYDrillKV label="Adjustment %"             value={(m.adjustmentPct||0)+'%'} color="#166534"/>
              <SYDrillKV label="Gross Quantity"           value={Number(m.grossQuantity||m.quantity||0).toFixed(3)+' '+(mat.unit||'MT')} bold color="var(--ok)"/>
              <SYDrillKV label="Inventory Deducted"       value={Number(m.inventoryDeduction||m.quantity||0).toFixed(3)+' '+(mat.unit||'MT')} bold color={isIn?'var(--ok)':'var(--err)'}/>
            </>
          ) : (
            <SYDrillKV label="Quantity (Inventory)"      value={Number(m.quantity||0).toFixed(3)+' '+(mat.unit||'MT')} bold color={isIn?'var(--ok)':'var(--err)'}/>
          )}
          <SYDrillKV label="Material Rate"   value={m.rate?window.fmtCur(m.rate)+'/Ton':'—'}/>
          <SYDrillKV label="Material Value"  value={m.value?window.fmtCur(m.value):'—'} bold color="var(--or)"/>
          {parseFloat(m.transportRate)>0 && <>
            <SYDrillKV label="Transport Rate" value={window.fmtCur(m.transportRate)+'/Ton'} color="#6B7280"/>
            <SYDrillKV label="Freight Cost"   value={window.fmtCur(trFreight)}              color="#6B7280"/>
            <SYDrillKV label="Total Cost"     value={window.fmtCur((parseFloat(m.value)||0)+trFreight)} bold color="var(--or)"/>
          </>}
          <SYDrillKV label="Balance After"   value={balAfter!=null?Number(balAfter).toFixed(3)+' '+(mat.unit||'MT'):'—'} bold color="var(--or)"/>
        </SYDrillSection>

      </div>

      {/* Row 2: Transport + Destination — only when present */}
      {(hasTransport||hasDestination) && (
        <div style={{display:'grid',gridTemplateColumns:hasTransport&&hasDestination?'1fr 1fr':'1fr',gap:10}}>

          {hasTransport && (
            <SYDrillSection title="Transport Information" color="#15803D">
              {m.transporterName
                ? <SYDrillKV label="Transporter"     value={m.transporterName}    bold/>
                : <SYDrillKV label="Transporter"     value="Not assigned"         color="var(--txt3)"/>
              }
              {m.vehicleFull        && <SYDrillKV label="Vehicle Number"  value={m.vehicleFull}                           mono bold/>}
              {m.transportRate>0    && <SYDrillKV label="Transport Rate"  value={window.fmtCur(m.transportRate)+' /Ton'}  bold/>}
              {m.transportRate>0    && <SYDrillKV label="Freight Amount"  value={window.fmtCur(trFreight)}                bold color="var(--ok)"/>}
            </SYDrillSection>
          )}

          {hasDestination && (
            <SYDrillSection title="Destination Information" color="#6D28D9">
              <SYDrillKV label="Destination Type" value={m.destinationType||'—'} bold/>
              <SYDrillKV label="Destination"      value={m.destinationName||'—'} bold/>
              {m.destinationId && m.destinationType==='Customer' && (
                <SYDrillKV label="Delivery Address" value={(Store.byId('customers',m.destinationId)||{}).address||'—'}/>
              )}
              {m.destinationId && m.destinationType==='Stockyard' && (
                <SYDrillKV label="Yard Location"   value={(Store.byId('stockyards',m.destinationId)||{}).location||'—'}/>
              )}
              {m.destinationId && m.destinationType==='Vendor' && (
                <SYDrillKV label="Vendor Address"  value={(Store.byId('vendors',m.destinationId)||{}).address||'—'}/>
              )}
              {m.entityName && m.destinationName && (
                <div style={{marginTop:6,padding:'5px 9px',background:'#EDE9FE',borderRadius:4,fontSize:11,color:'#6D28D9',fontWeight:600,display:'flex',alignItems:'center',gap:6}}>
                  <span>{m.entityName}</span>
                  <span style={{opacity:.5}}>→</span>
                  <span>{m.destinationName}</span>
                </div>
              )}
            </SYDrillSection>
          )}

        </div>
      )}

    </div>
  );
}
window.SYRegisterDrill = SYRegisterDrill;

// ── SYTransferDrill — yard transfer detail panel ──────────────────────────
function SYTransferDrill({ t, materials }) {
  const mat = sddMemo(() => (materials||[]).find(m=>m.id===t.materialId)||{}, [materials, t.materialId]);
  return (
    <div style={{padding:'12px 16px 16px',background:'#EFF6FF',borderTop:'2px solid #BFDBFE'}}>
      <div className="rg-4" style={{gap:10}}>
        <SYDrillSection title="Transfer Information" color="#1D4ED8">
          <SYDrillKV label="Transfer ID" value={t.id?t.id.slice(0,8).toUpperCase():'—'} mono bold/>
          <SYDrillKV label="Date" value={window.fmtDate(t.date)}/>
          <SYDrillKV label="Status" value={t.status||'Completed'} color={t.status==='Completed'?'var(--ok)':t.status==='In Transit'?'var(--info)':'var(--warn)'} bold/>
          <SYDrillKV label="Reference" value={('SYT-'+(t.id||'').slice(-6)).toUpperCase()} mono/>
        </SYDrillSection>
        <SYDrillSection title="Route" color="var(--or)">
          <SYDrillKV label="From Stockyard" value={Store.name('stockyards',t.fromStockyardId)||'—'} bold/>
          <SYDrillKV label="To Stockyard" value={Store.name('stockyards',t.toStockyardId)||'—'} bold/>
          <SYDrillKV label="Material" value={mat.name||Store.name('materials',t.materialId)||'—'}/>
          <SYDrillKV label="Unit" value={mat.unit||'MT'}/>
        </SYDrillSection>
        <SYDrillSection title="Quantity & Valuation" color="#B45309">
          <SYDrillKV label="Quantity" value={Number(t.quantity||0).toFixed(3)+' '+(mat.unit||'MT')} bold color="var(--or)"/>
          <SYDrillKV label="Rate" value={t.rate?window.fmtCur(t.rate)+'/Ton':'—'}/>
          <SYDrillKV label="Transfer Value" value={t.value?window.fmtCur(t.value):'—'} bold color="var(--or)"/>
        </SYDrillSection>
        <SYDrillSection title="Logistics & Audit" color="#6B7280">
          <SYDrillKV label="Vehicle" value={t.vehicleNum||'—'} mono/>
          <SYDrillKV label="Challan" value={t.challan||'—'} mono/>
          <SYDrillKV label="Created By" value={t.createdBy||'—'}/>
          {t.notes && <SYDrillKV label="Remarks" value={t.notes}/>}
        </SYDrillSection>
      </div>
    </div>
  );
}
window.SYTransferDrill = SYTransferDrill;

// ── SYOverviewDrill — stockyard overview card drill-down ──────────────────
function SYOverviewDrill({ sy, movements, materials }) {
  const pos = sddMemo(() => {
    const matIds = [...new Set((movements||[]).filter(m=>m.stockyardId===sy.id).map(m=>m.materialId))];
    return matIds.map(mid => {
      const mat = (materials||[]).find(x=>x.id===mid)||{name:mid,unit:'MT'};
      const p = sddGetMatPos(movements, sy.id, mid);
      if (p.cur <= 0) return null;
      const sorted = [...(movements||[]).filter(m=>m.stockyardId===sy.id&&m.materialId===mid)].sort((a,b)=>(b.date||'').localeCompare(a.date||''));
      return { materialId:mid, name:mat.name, unit:mat.unit||'MT', ...p, lastDate:sorted[0]?.date||'' };
    }).filter(Boolean);
  }, [sy.id, movements, materials]);

  const totalMvts = (movements||[]).filter(m=>m.stockyardId===sy.id).length;
  const lastActivity = [...(movements||[]).filter(m=>m.stockyardId===sy.id)]
    .sort((a,b)=>(b.date||'').localeCompare(a.date||''))[0]?.date||'';
  const totalVal = pos.reduce((s,p)=>s+p.value,0);
  const totalQty = pos.reduce((s,p)=>s+p.cur,0);

  return (
    <div style={{padding:'12px 16px 16px',background:'#FFF9F5',borderTop:'2px solid var(--or-bdr)'}}>
      <div className="rg-2" style={{gap:10,marginBottom:12}}>
        <SYDrillSection title="Stockyard Details" color="var(--or)">
          <SYDrillKV label="Name" value={sy.name||'—'} bold/>
          <SYDrillKV label="Location" value={sy.location||'—'}/>
          <SYDrillKV label="Company" value={Store.name('companies',sy.companyId)||'—'}/>
          <SYDrillKV label="Address" value={sy.address||'—'}/>
          <SYDrillKV label="Status" value={sy.status||'Active'} color={sy.status==='Active'?'var(--ok)':'var(--err)'}/>
        </SYDrillSection>
        <SYDrillSection title="Inventory Summary" color="#1D4ED8">
          <SYDrillKV label="Material Types" value={pos.length} bold/>
          <SYDrillKV label="Total Quantity" value={window.formatQuantity(totalQty)+' Ton'} bold color="var(--or)"/>
          <SYDrillKV label="Total Value" value={window.fmtCur(totalVal)} bold color="var(--or)"/>
          <SYDrillKV label="Total Movements" value={totalMvts}/>
          <SYDrillKV label="Last Activity" value={lastActivity?window.fmtDate(lastActivity):'—'}/>
        </SYDrillSection>
      </div>
      {pos.length > 0 && (
        <SYDrillSection title="Material Breakdown" color="#B45309">
          <div style={{overflowX:'auto'}}>
            <table style={{width:'100%',borderCollapse:'collapse',fontSize:11.5}}>
              <thead><tr style={{background:'#F9FAFB'}}>
                {['Material','Unit','Current Stock','Avg Rate','Value','Last Movement'].map(h=>(
                  <th key={h} style={{padding:'5px 8px',textAlign:h==='Material'?'left':'right',fontWeight:700,fontSize:10.5,color:'var(--txt2)',borderBottom:'1px solid var(--bdr)'}}>{h}</th>
                ))}
              </tr></thead>
              <tbody>
                {pos.map(p=>(
                  <tr key={p.materialId} style={{borderBottom:'1px solid #F3F4F6'}}>
                    <td style={{padding:'4px 8px',fontWeight:600}}>{p.name}</td>
                    <td style={{padding:'4px 8px',textAlign:'right',color:'var(--txt2)'}}>{p.unit}</td>
                    <td style={{padding:'4px 8px',textAlign:'right',fontWeight:700,color:'var(--or)'}}>{p.cur.toFixed(3)}</td>
                    <td style={{padding:'4px 8px',textAlign:'right'}}>{window.fmtCur(p.avg)}</td>
                    <td style={{padding:'4px 8px',textAlign:'right',fontWeight:600,color:'var(--or)'}}>{window.fmtCur(p.value)}</td>
                    <td style={{padding:'4px 8px',textAlign:'right',color:'var(--txt2)',fontSize:11}}>{p.lastDate?window.fmtDate(p.lastDate):'—'}</td>
                  </tr>
                ))}
              </tbody>
              <tfoot><tr style={{background:'#FFF7ED'}}>
                <td colSpan={2} style={{padding:'5px 8px',fontWeight:700,fontSize:11,color:'var(--txt2)'}}>TOTALS</td>
                <td style={{padding:'5px 8px',textAlign:'right',fontWeight:700,color:'var(--or)'}}>{window.formatQuantity(totalQty)} T</td>
                <td style={{padding:'5px 8px'}}></td>
                <td style={{padding:'5px 8px',textAlign:'right',fontWeight:700,color:'var(--or)'}}>{window.fmtCur(totalVal)}</td>
                <td style={{padding:'5px 8px'}}></td>
              </tr></tfoot>
            </table>
          </div>
        </SYDrillSection>
      )}
    </div>
  );
}
window.SYOverviewDrill = SYOverviewDrill;

// ── SYIntelDrill — intelligence row drill-down ────────────────────────────
function SYIntelDrill({ item, movements, materials }) {
  const days = sddDaysSince(item.lastMovementDate);
  const col  = days>=90?'var(--err)':days>=30?'var(--warn)':'var(--ok)';
  return (
    <div style={{padding:'12px 16px 16px',background:'#FAFAFA',borderTop:'2px solid var(--bdr)'}}>
      <div className="rg-3" style={{gap:10,marginBottom:10}}>
        <SYDrillSection title="Material Status" color="var(--or)">
          <SYDrillKV label="Material" value={item.matName||'—'} bold/>
          <SYDrillKV label="Stockyard" value={item.syName||'—'}/>
          <SYDrillKV label="Current Stock" value={Number(item.current||0).toFixed(3)+' '+(item.unit||'MT')} bold color="var(--or)"/>
          <SYDrillKV label="Stock Value" value={window.fmtCur(item.value||0)} bold color="var(--or)"/>
        </SYDrillSection>
        <SYDrillSection title="Aging Analysis" color={col}>
          <SYDrillKV label="Last Movement" value={item.lastMovementDate?window.fmtDate(item.lastMovementDate):'—'}/>
          <SYDrillKV label="Days Since Last Move" value={days===9999?'Unknown':days+' days'} bold color={col}/>
          <SYDrillKV label="First Entry" value={item.firstInDate?window.fmtDate(item.firstInDate):'—'}/>
          <SYDrillKV label="Out Transactions" value={item.outMovesCount||0}/>
        </SYDrillSection>
        <SYDrillSection title="Movement Summary" color="#6D28D9">
          <SYDrillKV label="Total Inward" value={Number(item.totalIn||0).toFixed(3)+' '+(item.unit||'MT')} color="var(--ok)"/>
          <SYDrillKV label="Total Outward" value={Number(item.totalOut||0).toFixed(3)+' '+(item.unit||'MT')} color="var(--err)"/>
          <SYDrillKV label="Net Position" value={Number(item.current||0).toFixed(3)+' '+(item.unit||'MT')} bold color="var(--or)"/>
        </SYDrillSection>
      </div>
      <SYDrillSection title="Movement History (Last 20)" color="#374151">
        <SYMovementHistory movements={movements} stockyardId={item.syId} materialId={item.materialId} limit={20}/>
      </SYDrillSection>
    </div>
  );
}
window.SYIntelDrill = SYIntelDrill;

// ── SYValueDrillModal — total value breakdown modal ───────────────────────
function SYValueDrillModal({ rows, materials, stockyards, onClose }) {
  const matBreak = sddMemo(() => {
    const map = {};
    (rows||[]).forEach(mv => {
      const mid = mv.materialId;
      if (!map[mid]) map[mid] = { name:Store.name('materials',mid)||mid, inQty:0, outQty:0, inVal:0, outVal:0 };
      const q=parseFloat(mv.quantity)||0, v=parseFloat(mv.value)||0;
      if (SDD_IN.has(mv.type)) { map[mid].inQty+=q; map[mid].inVal+=v; }
      else { map[mid].outQty+=q; map[mid].outVal+=v; }
    });
    return Object.values(map).sort((a,b)=>Math.abs(b.inVal-b.outVal)-Math.abs(a.inVal-a.outVal));
  }, [rows]);

  const yardBreak = sddMemo(() => {
    const map = {};
    (rows||[]).forEach(mv => {
      const sid = mv.stockyardId;
      if (!map[sid]) map[sid] = { name:Store.name('stockyards',sid)||'—', inVal:0, outVal:0 };
      const v=parseFloat(mv.value)||0;
      if (SDD_IN.has(mv.type)) map[sid].inVal+=v; else map[sid].outVal+=v;
    });
    return Object.values(map);
  }, [rows]);

  const totIn  = (rows||[]).filter(m=>SDD_IN.has(m.type)).reduce((s,m)=>s+(parseFloat(m.value)||0),0);
  const totOut = (rows||[]).filter(m=>!SDD_IN.has(m.type)).reduce((s,m)=>s+(parseFloat(m.value)||0),0);

  return ReactDOM.createPortal(
    <div className="mbg">
      <div className="mod mod-xl">
        <div className="mod-hd"><h2>Value Breakdown — Current Filters</h2><button className="mod-x" onClick={onClose}>×</button></div>
        <div className="mod-bd">
          <div className="rg-3kpi" style={{marginBottom:14}}>
            {[['Inward Value',window.fmtCur(totIn),'var(--ok)'],['Outward Value',window.fmtCur(totOut),'var(--err)'],['Net Value',window.fmtCur(Math.abs(totIn-totOut)),'var(--or)']].map(([l,v,c])=>(
              <div key={l} style={{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:6,padding:'10px 14px'}}>
                <div className="kpi-val" style={{fontSize:17,fontWeight:700,color:c}}>{v}</div>
                <div style={{fontSize:11,color:'var(--txt2)',marginTop:3}}>{l}</div>
              </div>
            ))}
          </div>
          <div style={{fontWeight:700,fontSize:12.5,marginBottom:8}}>Material-wise Breakdown</div>
          <div style={{overflowX:'auto',marginBottom:14}}>
            <table style={{width:'100%',borderCollapse:'collapse',fontSize:12}}>
              <thead><tr style={{background:'#F9FAFB'}}>
                {['Material','Inward Qty','Outward Qty','Inward Value','Outward Value','Net Value'].map(h=>(
                  <th key={h} style={{padding:'6px 8px',textAlign:h==='Material'?'left':'right',fontWeight:700,fontSize:10.5,color:'var(--txt2)',borderBottom:'1px solid var(--bdr)'}}>{h}</th>
                ))}
              </tr></thead>
              <tbody>
                {matBreak.map((r,i)=>(
                  <tr key={i} style={{borderBottom:'1px solid #F3F4F6'}}>
                    <td style={{padding:'5px 8px',fontWeight:600}}>{r.name}</td>
                    <td style={{padding:'5px 8px',textAlign:'right',color:'var(--ok)',fontFamily:'var(--font)'}}>{r.inQty.toFixed(3)}</td>
                    <td style={{padding:'5px 8px',textAlign:'right',color:'var(--err)',fontFamily:'var(--font)'}}>{r.outQty.toFixed(3)}</td>
                    <td style={{padding:'5px 8px',textAlign:'right',color:'var(--ok)'}}>{window.fmtCur(r.inVal)}</td>
                    <td style={{padding:'5px 8px',textAlign:'right',color:'var(--err)'}}>{window.fmtCur(r.outVal)}</td>
                    <td style={{padding:'5px 8px',textAlign:'right',fontWeight:700,color:'var(--or)'}}>{window.fmtCur(Math.abs(r.inVal-r.outVal))}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div style={{fontWeight:700,fontSize:12.5,marginBottom:8}}>Stockyard-wise Breakdown</div>
          <div style={{overflowX:'auto'}}>
            <table style={{width:'100%',borderCollapse:'collapse',fontSize:12}}>
              <thead><tr style={{background:'#F9FAFB'}}>
                {['Stockyard','Inward Value','Outward Value','Net Value'].map(h=>(
                  <th key={h} style={{padding:'6px 8px',textAlign:h==='Stockyard'?'left':'right',fontWeight:700,fontSize:10.5,color:'var(--txt2)',borderBottom:'1px solid var(--bdr)'}}>{h}</th>
                ))}
              </tr></thead>
              <tbody>
                {yardBreak.map((r,i)=>(
                  <tr key={i} style={{borderBottom:'1px solid #F3F4F6'}}>
                    <td style={{padding:'5px 8px',fontWeight:600}}>{r.name}</td>
                    <td style={{padding:'5px 8px',textAlign:'right',color:'var(--ok)'}}>{window.fmtCur(r.inVal)}</td>
                    <td style={{padding:'5px 8px',textAlign:'right',color:'var(--err)'}}>{window.fmtCur(r.outVal)}</td>
                    <td style={{padding:'5px 8px',textAlign:'right',fontWeight:700,color:'var(--or)'}}>{window.fmtCur(Math.abs(r.inVal-r.outVal))}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
        <div className="mod-ft"><button className="btn btn-wh" onClick={onClose}>Close</button></div>
      </div>
    </div>,
    document.body
  );
}
window.SYValueDrillModal = SYValueDrillModal;

// Chevron icon helper — shared expand indicator
window.SYChevron = function({ open, color }) {
  return (
    <svg width="9" height="9" viewBox="0 0 10 10" fill="none"
      style={{transform:open?'rotate(90deg)':'none',transition:'transform .15s',color:color||'var(--or)',display:'block',margin:'0 auto'}}>
      <path d="M3 1.5L7 5L3 8.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
};

// ── SYDrillModal — generic reusable drill-down modal wrapper ──────────────
function SYDrillModal({ title, subtitle, onClose, children, width, color }) {
  return ReactDOM.createPortal(
    <div className="mbg">
      <div className="mod mod-xl" style={{maxWidth:width||780,width:'94vw'}}>
        <div className="mod-hd">
          <div>
            <h2 style={{color:color||'var(--or)'}}>{title}</h2>
            {subtitle&&<div style={{fontSize:11,color:'var(--txt2)',marginTop:2,fontWeight:400}}>{subtitle}</div>}
          </div>
          <button className="mod-x" onClick={onClose}>×</button>
        </div>
        <div className="mod-bd" style={{maxHeight:'70vh',overflowY:'auto'}}>{children}</div>
        <div className="mod-ft"><button className="btn btn-wh" onClick={onClose}>Close</button></div>
      </div>
    </div>,
    document.body
  );
}
window.SYDrillModal = SYDrillModal;

// ── SYIntelListDrill — reusable modal for Intel KPI lists ─────────────────
function SYIntelListDrill({ title, color, items, movements, materials, colExtra, onClose }) {
  const { useState: ld1St, useMemo: ld1Me } = React;
  const [expKey, setExpKey] = ld1St(null);
  return (
    <window.SYDrillModal title={title} subtitle={items.length+' items'} color={color} onClose={onClose}>
      <div className="dd-3col" style={{marginBottom:12}}>
        {[['Items',items.length],['Total Stock',items.reduce((s,p)=>s+p.current,0).toFixed(1)+' T'],['Total Value',window.fmtCur(items.reduce((s,p)=>s+p.value,0))]].map(([l,v])=>(
          <div key={l} style={{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:6,padding:'8px 12px'}}>
            <div className="kpi-val" style={{fontSize:16,fontWeight:700,color}}>{v}</div>
            <div style={{fontSize:11,color:'var(--txt2)',marginTop:2}}>{l}</div>
          </div>
        ))}
      </div>
      <div className="tbl-w" style={{maxHeight:400,overflowY:'auto'}}>
        <table className="tbl">
          <thead><tr>
            <th style={{width:28}}></th>
            <th>STOCKYARD</th><th>MATERIAL</th><th>QTY</th><th>UNIT</th>
            {colExtra&&<th>{colExtra.header}</th>}
            <th>VALUE</th><th>LAST MOVEMENT</th>
          </tr></thead>
          <tbody>
            {items.length===0
              ? <tr className="empty"><td colSpan={colExtra?8:7} style={{textAlign:'center',padding:24,color:'var(--txt2)'}}>No items</td></tr>
              : items.map(p=>{
                const key=`${p.syId}:${p.materialId}`; const isExp=expKey===key;
                return (
                  <React.Fragment key={key}>
                    <tr onClick={()=>setExpKey(k=>k===key?null:key)} style={{cursor:'pointer',background:isExp?'#FAFAFA':''}}>
                      <td style={{textAlign:'center'}}><window.SYChevron open={isExp} color={color}/></td>
                      <td style={{fontWeight:500}}>{p.syName}</td>
                      <td><strong>{p.matName}</strong></td>
                      <td style={{fontWeight:600,color}}>{p.current.toFixed(3)}</td>
                      <td style={{color:'var(--txt2)'}}>{p.unit}</td>
                      {colExtra&&<td>{colExtra.render(p)}</td>}
                      <td style={{fontWeight:600,color:'var(--or)'}}>{window.fmtCur(p.value)}</td>
                      <td style={{fontSize:11.5,color:'var(--txt2)'}}>{p.lastMovementDate?window.fmtDate(p.lastMovementDate):'—'}</td>
                    </tr>
                    {isExp&&<tr><td colSpan={colExtra?8:7} style={{padding:0}}><window.SYIntelDrill item={p} movements={movements} materials={materials}/></td></tr>}
                  </React.Fragment>
                );
              })}
          </tbody>
        </table>
      </div>
    </window.SYDrillModal>
  );
}
window.SYIntelListDrill = SYIntelListDrill;
