// Executive Interactive Analytics — OM Group ERP
// Auto-works for every company. Data-driven. No hardcoding.
const { useState: eaSt, useEffect: eaEf, useMemo: eaMemo, useRef: eaRef, useCallback: eaCb } = React;

// ── Palette ─────────────────────────────────────────────────────────────────
const EA_PALETTE = [
  '#F97316','#3B82F6','#22C55E','#A855F7','#EF4444',
  '#F59E0B','#06B6D4','#EC4899','#10B981','#6366F1',
  '#84CC16','#F43F5E','#0EA5E9','#8B5CF6','#14B8A6',
];

// ── Donut Chart (pure SVG) ───────────────────────────────────────────────────
function ExecDonut({ slices, size = 220, thickness = 46, label, sublabel, onSliceClick }) {
  const [hovered, setHovered] = eaSt(null);
  const [tooltip, setTooltip] = eaSt({ vis: false, x: 0, y: 0, slice: null });
  const svgRef = eaRef(null);

  const cx = size / 2, cy = size / 2, r = (size - thickness) / 2 - 4;
  const circ = 2 * Math.PI * r;
  const total = slices.reduce((s, sl) => s + Math.max(0, sl.value), 0);

  const computedSlices = eaMemo(() => {
    if (total <= 0) return [];
    let offset = 0;
    const sliceGap = slices.length > 1 ? 3 : 0;
    return slices.map((sl, i) => {
      const pct = Math.max(0, sl.value) / total;
      const dash = Math.max(0, pct * circ - sliceGap);
      const gap = circ - dash;
      const slice = { ...sl, pct, dash, gap, offset, color: sl.color || EA_PALETTE[i % EA_PALETTE.length] };
      offset += pct;
      return slice;
    });
  }, [slices, total, circ]);

  const handleMouseMove = eaCb((e, sl) => {
    var vw = window.innerWidth, vh = window.innerHeight;
    var TW = 210, TH = 110, gap = 14, margin = 10;
    var left = e.clientX + gap;
    if (left + TW > vw - margin) left = e.clientX - TW - gap;
    var top = e.clientY - TH / 2;
    top = Math.max(margin, Math.min(top, vh - TH - margin));
    setTooltip({ vis: true, x: left, y: top, slice: sl });
  }, []);

  const handleMouseLeave = eaCb(() => {
    setHovered(null);
    setTooltip(t => ({ ...t, vis: false }));
  }, []);

  const ROTATE = -90; // start from top

  return (
    <div className="ea-donut-wrap" style={{ position: 'relative', display: 'inline-block', width: size, height: size, flexShrink: 0 }}>
      <svg ref={svgRef} width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: 'block', overflow: 'visible' }}>
        {/* Track */}
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="#EDECEA" strokeWidth={thickness} />
        {/* Slices */}
        {total <= 0 ? (
          <circle cx={cx} cy={cy} r={r} fill="none" stroke="#E5E7EB" strokeWidth={thickness}
            strokeDasharray={`${circ} ${circ}`} strokeDashoffset={0} strokeLinecap="butt"
            transform={`rotate(${ROTATE} ${cx} ${cy})`} />
        ) : computedSlices.map((sl, i) => {
          const isHov = hovered === i;
          return (
            <circle key={i} cx={cx} cy={cy} r={r} fill="none"
              stroke={sl.color} strokeWidth={isHov ? thickness + 6 : thickness}
              strokeDasharray={`${sl.dash} ${sl.gap}`}
              strokeDashoffset={-(sl.offset * circ)}
              strokeLinecap="butt"
              transform={`rotate(${ROTATE} ${cx} ${cy})`}
              style={{
                cursor: onSliceClick ? 'pointer' : 'default',
                transition: 'stroke-width .18s, opacity .18s',
                opacity: hovered !== null && hovered !== i ? 0.55 : 1,
              }}
              onMouseEnter={() => setHovered(i)}
              onMouseMove={e => handleMouseMove(e, sl)}
              onMouseLeave={handleMouseLeave}
              onClick={() => onSliceClick && onSliceClick(sl)}
            />
          );
        })}
        {/* Center text */}
        <text x={cx} y={cy - 8} textAnchor="middle" fontSize="13" fontWeight="700" fill="#374151">{label}</text>
        <text x={cx} y={cy + 10} textAnchor="middle" fontSize="9.5" fill="#9CA3AF">{sublabel}</text>
      </svg>
      {/* Tooltip — OM Group white hover card */}
      {tooltip.vis && tooltip.slice && (
        <div className="om-tip" style={{
          position: 'fixed',
          top: tooltip.y, left: tooltip.x,
          width: 210, padding: '10px 12px',
        }}>
          <div style={{ fontWeight: 700, fontSize: 12.5, color: 'var(--txt)', marginBottom: 4 }}>{tooltip.slice.label}</div>
          <div style={{ color: tooltip.slice.color || 'var(--or)', fontWeight: 700, fontSize: 14 }}>{tooltip.slice.formatted}</div>
          <div style={{ color: 'var(--txt3)', fontSize: 10.5, marginTop: 3 }}>{(tooltip.slice.pct * 100).toFixed(1)}% of total</div>
          {onSliceClick && <div style={{ color: 'var(--info)', fontSize: 10.5, marginTop: 5, fontWeight: 500 }}>Click to drill down →</div>}
        </div>
      )}
    </div>
  );
}

// ── Legend ───────────────────────────────────────────────────────────────────
function ExecLegend({ slices, total, onSliceClick }) {
  const C = window.fmtCur;
  return (
    <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 5, justifyContent: 'center' }}>
      {slices.map((sl, i) => {
        const pct = total > 0 ? (Math.max(0, sl.value) / total * 100).toFixed(1) : '0.0';
        return (
          <div key={i}
            style={{ display: 'flex', alignItems: 'center', gap: 7, cursor: onSliceClick ? 'pointer' : 'default', padding: '3px 6px', borderRadius: 5, transition: 'background .12s' }}
            onClick={() => onSliceClick && onSliceClick(sl)}
            onMouseEnter={e => onSliceClick && (e.currentTarget.style.background = '#F9FAFB')}
            onMouseLeave={e => (e.currentTarget.style.background = '')}>
            <div style={{ width: 10, height: 10, borderRadius: '50%', background: sl.color || EA_PALETTE[i % EA_PALETTE.length], flexShrink: 0 }}></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="ea-legend-label" style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 160 }}>{sl.label}</div>
              <div style={{ fontSize: 10, color: '#6B7280' }}>{sl.formatted} · {pct}%</div>
            </div>
            {onSliceClick && <span style={{ fontSize: 9, color: '#D1D5DB', fontWeight: 700 }}>▶</span>}
          </div>
        );
      })}
    </div>
  );
}

// ── Mini Donut Card (for material/customer/vendor panels) ────────────────────
function MiniDonutCard({ title, slices, emptyMsg, onSliceClick, color }) {
  const total = slices.reduce((s, sl) => s + Math.max(0, sl.value), 0);
  return (
    <div className="card" style={{ padding: '12px 14px' }}>
      <div style={{ fontWeight: 700, fontSize: 12, color: color || 'var(--txt)', marginBottom: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        {title}
        {onSliceClick && <span style={{ fontSize: 9.5, color: '#9CA3AF', fontWeight: 500 }}>click to drill</span>}
      </div>
      {slices.length === 0 || total === 0 ? (
        <div style={{ fontSize: 11, color: 'var(--txt3)', textAlign: 'center', padding: '18px 0' }}>{emptyMsg || 'No data'}</div>
      ) : (
        <div className="ea-mini-flex" style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
          <ExecDonut slices={slices} size={130} thickness={32} label={slices.length} sublabel="items" onSliceClick={onSliceClick} />
          <ExecLegend slices={slices} total={total} onSliceClick={onSliceClick} />
        </div>
      )}
    </div>
  );
}

// ── Main Executive Analytics Section ────────────────────────────────────────
function ExecutiveAnalyticsSection({ purchases, sales, allMaterials, companyId, range }) {
  const [mode, setMode] = eaSt('financial'); // 'financial' | 'operational'
  const [drill, setDrill] = eaSt(null);
  const C = window.fmtCur;
  const fmt3 = n => Number(n || 0).toFixed(3);
  const fmtT = n => Number(n || 0).toFixed(1) + ' T';

  // ── Derived KPIs ──────────────────────────────────────────────────────────
  const { totalRev, totalCost, grossProfit, margin, totalPQty, totalSQty, totalTrips, purchaseTrips, salesTrips } = eaMemo(() => {
    const rev  = sales.reduce((s, o) => s + window.gAmt(o), 0);
    const cost = purchases.reduce((s, p) => s + window.gAmt(p), 0);
    const pQty = purchases.reduce((s, p) => s + (p.items || []).reduce((a, i) => a + (parseFloat(i.quantity) || 0), 0), 0);
    const sQty = sales.reduce((s, o) => s + (parseFloat(o.quantity) || 0), 0);
    return {
      totalRev: rev, totalCost: cost, grossProfit: rev - cost,
      margin: rev > 0 ? ((rev - cost) / rev * 100) : 0,
      totalPQty: pQty, totalSQty: sQty,
      totalTrips: purchases.length + sales.length,
      purchaseTrips: purchases.length,
      salesTrips: sales.length,
    };
  }, [purchases, sales]);

  // ── Diesel KPI ────────────────────────────────────────────────────────────
  const dieselCost = eaMemo(() => {
    const recs = Store.all('dieselRecords', companyId);
    const inR = (d) => {
      if (!d) return false;
      if (range.from && d < range.from) return false;
      if (range.to && d > range.to) return false;
      return true;
    };
    return recs.filter(r => inR(r.date)).reduce((s, r) => s + (parseFloat(r.amount) || 0), 0);
  }, [companyId, range]);

  // ── Financial Slices ──────────────────────────────────────────────────────
  const financialSlices = eaMemo(() => {
    const items = [
      { key: 'revenue',      label: 'Revenue',       value: Math.max(0, totalRev),    color: '#22C55E', formatted: C(totalRev) },
      { key: 'cost',         label: 'Purchase Cost',  value: Math.max(0, totalCost),   color: '#F97316', formatted: C(totalCost) },
      { key: 'grossProfit',  label: 'Gross Profit',   value: Math.max(0, grossProfit), color: '#3B82F6', formatted: C(grossProfit) },
    ];
    if (dieselCost > 0) items.push({ key: 'diesel', label: 'Diesel Cost', value: dieselCost, color: '#F59E0B', formatted: C(dieselCost) });
    return items.filter(s => s.value > 0);
  }, [totalRev, totalCost, grossProfit, dieselCost]);

  // ── Operational Slices ────────────────────────────────────────────────────
  const operationalSlices = eaMemo(() => {
    const items = [
      { key: 'tonsPurchased', label: 'Tons Purchased', value: Math.max(0, totalPQty), color: '#F97316', formatted: fmtT(totalPQty) },
      { key: 'tonsSold',      label: 'Tons Sold',      value: Math.max(0, totalSQty), color: '#3B82F6', formatted: fmtT(totalSQty) },
      { key: 'purchaseTrips', label: 'Purchase Trips', value: purchaseTrips,          color: '#A855F7', formatted: purchaseTrips + ' trips' },
      { key: 'salesTrips',    label: 'Sales Trips',    value: salesTrips,             color: '#22C55E', formatted: salesTrips + ' trips' },
    ];
    return items.filter(s => s.value > 0);
  }, [totalPQty, totalSQty, purchaseTrips, salesTrips]);

  // ── Material Slices ───────────────────────────────────────────────────────
  const materialSlices = eaMemo(() => {
    const m = {};
    sales.forEach(s => {
      if (!s.materialId) return;
      if (!m[s.materialId]) m[s.materialId] = { key: 'mat_' + s.materialId, label: Store.name('materials', s.materialId) || s.materialId, value: 0 };
      m[s.materialId].value += window.gAmt(s);
    });
    return Object.values(m)
      .sort((a, b) => b.value - a.value)
      .slice(0, 8)
      .map((sl, i) => ({ ...sl, color: EA_PALETTE[i % EA_PALETTE.length], formatted: C(sl.value) }));
  }, [sales]);

  // ── Customer Slices ───────────────────────────────────────────────────────
  const customerSlices = eaMemo(() => {
    const m = {};
    sales.forEach(s => {
      if (!s.customerId) return;
      const k = s.customerId;
      if (!m[k]) m[k] = { key: 'cust_' + k, label: Store.name('customers', k) || k, value: 0, id: k };
      m[k].value += window.gAmt(s);
    });
    return Object.values(m)
      .sort((a, b) => b.value - a.value)
      .slice(0, 8)
      .map((sl, i) => ({ ...sl, color: EA_PALETTE[(i + 3) % EA_PALETTE.length], formatted: C(sl.value) }));
  }, [sales]);

  // ── Vendor Slices ─────────────────────────────────────────────────────────
  const vendorSlices = eaMemo(() => {
    const m = {};
    purchases.forEach(p => {
      if (!p.vendorId) return;
      const k = p.vendorId;
      if (!m[k]) m[k] = { key: 'vend_' + k, label: Store.name('vendors', k) || k, value: 0, id: k };
      m[k].value += (p.items || []).reduce((s, i) => s + (parseFloat(i.quantity) || 0), 0);
    });
    return Object.values(m)
      .sort((a, b) => b.value - a.value)
      .slice(0, 8)
      .map((sl, i) => ({ ...sl, color: EA_PALETTE[(i + 6) % EA_PALETTE.length], formatted: fmt3(sl.value) + ' T' }));
  }, [purchases]);

  // ── Current mode slices ───────────────────────────────────────────────────
  const activeSlices = mode === 'financial' ? financialSlices : operationalSlices;
  const total = activeSlices.reduce((s, sl) => s + sl.value, 0);

  // ── Main center label ─────────────────────────────────────────────────────
  const centerLabel = mode === 'financial' ? C(totalRev) : totalTrips + ' trips';
  const centerSub   = mode === 'financial' ? 'Total Revenue' : 'Total Trips';

  // ── Drill handler ─────────────────────────────────────────────────────────
  const openDrill = sl => setDrill(sl);
  const closeDrill = () => setDrill(null);

  return (
    <div style={{ marginBottom: 16 }}>
      {/* Section Header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10, flexWrap: 'wrap', gap: 8 }}>
        <div>
          <div style={{ fontWeight: 700, fontSize: 13, color: 'var(--txt)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 18, height: 18, borderRadius: '50%', background: 'linear-gradient(135deg,#F97316,#3B82F6)', display: 'inline-block', flexShrink: 0 }}></span>
            Executive Analytics
          </div>
          <div style={{ fontSize: 11, color: 'var(--txt2)', marginTop: 2 }}>Interactive charts · Click any slice or label to drill down</div>
        </div>
        <div style={{ display: 'flex', gap: 5 }}>
          <button className={`btn btn-sm ${mode === 'financial' ? 'btn-or' : 'btn-wh'}`} onClick={() => setMode('financial')}>Financial</button>
          <button className={`btn btn-sm ${mode === 'operational' ? 'btn-or' : 'btn-wh'}`} onClick={() => setMode('operational')}>Operational</button>
        </div>
      </div>

      {/* Main Donut + Legend */}
      <div className="card" style={{ padding: '18px 20px', marginBottom: 10 }}>
        <div className="ea-main-flex" style={{ display: 'flex', alignItems: 'flex-start', gap: 24, flexWrap: 'wrap' }}>
          {/* Donut */}
          <div className="ea-donut-col" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, flexShrink: 0 }}>
            <ExecDonut slices={activeSlices} size={220} thickness={46} label={centerLabel} sublabel={centerSub} onSliceClick={openDrill} />
            <div style={{ fontSize: 10, color: 'var(--txt3)' }}>Hover to inspect · Click to drill down</div>
          </div>

          {/* Legend + KPI strip */}
          <div className="ea-legend-col" style={{ flex: 1, minWidth: 220 }}>
            <ExecLegend slices={activeSlices} total={total} onSliceClick={openDrill} />

            {/* Margin badge */}
            {mode === 'financial' && (
              <div style={{ marginTop: 14, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                <div style={{ background: grossProfit >= 0 ? '#F0FDF4' : '#FEF2F2', border: `1px solid ${grossProfit >= 0 ? '#BBF7D0' : '#FECACA'}`, borderRadius: 6, padding: '7px 13px' }}>
                  <div style={{ fontSize: 16, fontWeight: 700, color: grossProfit >= 0 ? '#16A34A' : '#DC2626' }}>{margin.toFixed(1)}%</div>
                  <div style={{ fontSize: 10, color: '#6B7280' }}>Gross Margin</div>
                </div>
                <div style={{ background: '#EFF6FF', border: '1px solid #BFDBFE', borderRadius: 6, padding: '7px 13px', cursor: 'pointer' }}
                  onClick={() => openDrill({ key: 'profitPerTon' })}>
                  <div style={{ fontSize: 16, fontWeight: 700, color: '#1D4ED8' }}>{C(totalSQty > 0 ? Math.round(grossProfit / totalSQty) : 0)}</div>
                  <div style={{ fontSize: 10, color: '#6B7280' }}>Profit / Ton</div>
                </div>
                {dieselCost > 0 && (
                  <div style={{ background: '#FFFBEB', border: '1px solid #FDE68A', borderRadius: 6, padding: '7px 13px', cursor: 'pointer' }}
                    onClick={() => openDrill({ key: 'diesel' })}>
                    <div style={{ fontSize: 16, fontWeight: 700, color: '#B45309' }}>{C(dieselCost)}</div>
                    <div style={{ fontSize: 10, color: '#6B7280' }}>Diesel Cost</div>
                  </div>
                )}
              </div>
            )}
            {mode === 'operational' && (
              <div style={{ marginTop: 14, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                <div style={{ background: '#FFF7ED', border: '1px solid var(--or-bdr)', borderRadius: 6, padding: '7px 13px' }}>
                  <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--or)' }}>{fmt3(totalPQty - totalSQty)} T</div>
                  <div style={{ fontSize: 10, color: '#6B7280' }}>Stock Balance</div>
                </div>
                <div style={{ background: '#F0FDF4', border: '1px solid #BBF7D0', borderRadius: 6, padding: '7px 13px' }}>
                  <div style={{ fontSize: 16, fontWeight: 700, color: '#16A34A' }}>{totalSQty > 0 && totalPQty > 0 ? (totalSQty / totalPQty * 100).toFixed(1) + '%' : '—'}</div>
                  <div style={{ fontSize: 10, color: '#6B7280' }}>Sell-Through</div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Mini Donut Trio */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8 }} className="ea-mini-grid">
        <MiniDonutCard
          title="Material Distribution"
          slices={materialSlices}
          color="#F97316"
          emptyMsg="No sales data in period"
          onSliceClick={sl => setDrill({ key: 'mat_' + sl.label, label: sl.label, matId: sl.key?.replace('mat_', '') })}
        />
        <MiniDonutCard
          title="Customer Contribution"
          slices={customerSlices}
          color="#7C3AED"
          emptyMsg="No customer sales in period"
          onSliceClick={sl => setDrill({ key: 'customer', customerId: sl.id, label: sl.label })}
        />
        <MiniDonutCard
          title="Vendor Supply Share"
          slices={vendorSlices}
          color="#B45309"
          emptyMsg="No purchase data in period"
          onSliceClick={sl => setDrill({ key: 'vendor', vendorId: sl.id, label: sl.label })}
        />
      </div>

      {/* Drill-Down Modals */}
      {drill && (
        <window.ExecDrillRouter
          drill={drill}
          purchases={purchases}
          sales={sales}
          allMaterials={allMaterials}
          totalRev={totalRev}
          totalCost={totalCost}
          grossProfit={grossProfit}
          margin={margin}
          totalSQty={totalSQty}
          onClose={closeDrill}
        />
      )}

      <style>{`
        @media (max-width: 1024px) {
          .ea-mini-grid { grid-template-columns: repeat(2, 1fr) !important; }
        }
        @media (max-width: 768px) {
          .ea-mini-grid { grid-template-columns: 1fr !important; }
          .ea-main-flex { flex-direction: column !important; align-items: stretch !important; }
          .ea-donut-col { align-items: center !important; }
          .ea-legend-col { min-width: 0 !important; width: 100% !important; }
          .ea-mini-flex { flex-direction: column !important; align-items: center !important; }
          .ea-mini-flex > div:last-child { width: 100% !important; min-width: 0 !important; }
        }
      `}</style>
    </div>
  );
}

window.ExecutiveAnalyticsSection = ExecutiveAnalyticsSection;
