/* ============================================================
   P&L App (Lite) · Charts (from the US demo) (SVG / div based, responsive)
   ============================================================ */

/* ---------- Grouped vertical bars: income vs cost per month ---------- */
function GroupedBars({ data, height = 240, onPick }) {
  const [hover, setHover] = useState(null);
  const max = Math.max(1, ...data.map(d => Math.max(d.income, d.cost)));
  const ticks = 4;
  return (
    <div>
      <div className="flex items-stretch" style={{ height }}>
        {/* y axis */}
        <div className="relative w-12 shrink-0 mr-1">
          {Array.from({ length: ticks + 1 }).map((_, i) => {
            const v = max * (1 - i / ticks);
            return (
              <div key={i} className="absolute right-1 -translate-y-1/2 text-[10.5px] text-muted num" style={{ top: `${(i / ticks) * 100}%` }}>
                ${money0(v / 1000)}k
              </div>
            );
          })}
        </div>
        {/* plot */}
        <div className="relative flex-1">
          {Array.from({ length: ticks + 1 }).map((_, i) => (
            <div key={i} className="absolute left-0 right-0 border-t border-dashed" style={{ top: `${(i / ticks) * 100}%`, borderColor: '#EEF1EA' }} />
          ))}
          <div className="absolute inset-0 flex items-end justify-between gap-2 px-1">
            {data.map((d, i) => (
              <div key={i} className={'flex-1 h-full flex items-end justify-center gap-[5px] relative' + (onPick ? ' cursor-pointer' : '')}
                onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)} onClick={() => onPick && onPick(i)}>
                {hover === i && (
                  <div className="absolute -top-1 left-1/2 -translate-x-1/2 -translate-y-full z-10 bg-ink text-white rounded-lg px-2.5 py-2 text-[11px] whitespace-nowrap shadow-pop pointer-events-none">
                    <div className="font-600 mb-0.5">{d.label}</div>
                    <div className="flex items-center gap-1.5"><span className="w-2 h-2 rounded-full" style={{ background: 'var(--pos)' }} />Income <span className="num ml-auto pl-2">{money0USD(d.income)}</span></div>
                    <div className="flex items-center gap-1.5"><span className="w-2 h-2 rounded-full" style={{ background: 'var(--primary)' }} />Costs <span className="num ml-auto pl-2">{money0USD(d.cost)}</span></div>
                  </div>
                )}
                <div className="w-full max-w-[18px] rounded-t-[4px] transition-all" style={{ height: `${(d.income / max) * 100}%`, background: 'var(--pos)', opacity: hover === null || hover === i ? 1 : 0.45 }} />
                <div className="w-full max-w-[18px] rounded-t-[4px] transition-all" style={{ height: `${(d.cost / max) * 100}%`, background: 'var(--primary)', opacity: hover === null || hover === i ? 1 : 0.45 }} />
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="flex items-stretch mt-2">
        <div className="w-12 shrink-0 mr-1" />
        <div className="flex-1 flex justify-between px-1">
          {data.map((d, i) => <div key={i} className="flex-1 text-center text-[11px] text-muted num">{d.label}</div>)}
        </div>
      </div>
    </div>
  );
}

/* ---------- Donut ---------- */
function Donut({ data, size = 184, thickness = 26, centerLabel, centerValue }) {
  const [hover, setHover] = useState(null);
  const total = data.reduce((a, d) => a + d.value, 0) || 1;
  const r = (size - thickness) / 2;
  const c = 2 * Math.PI * r;
  let offset = 0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="shrink-0">
      <g transform={`rotate(-90 ${size / 2} ${size / 2})`}>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="#F1FBD4" strokeWidth={thickness} />
        {data.map((d, i) => {
          const frac = d.value / total;
          const len = frac * c;
          const el = (
            <circle key={i} cx={size / 2} cy={size / 2} r={r} fill="none"
              stroke={d.color} strokeWidth={hover === i ? thickness + 3 : thickness}
              strokeDasharray={`${len} ${c - len}`} strokeDashoffset={-offset}
              style={{ transition: 'stroke-width 0.15s', cursor: 'pointer' }}
              onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)} />
          );
          offset += len;
          return el;
        })}
      </g>
      <text x="50%" y="46%" textAnchor="middle" className="font-display num" style={{ fontSize: 22, fontWeight: 700, fill: 'var(--ink)' }}>
        {hover !== null ? '$' + money0(data[hover].value / 1000) + 'k' : centerValue}
      </text>
      <text x="50%" y="58%" textAnchor="middle" style={{ fontSize: 11, fill: 'var(--muted)' }}>
        {hover !== null ? data[hover].label.slice(0, 16) : centerLabel}
      </text>
    </svg>
  );
}

/* ---------- Horizontal bars ---------- */
function HBars({ data, format = money0 }) {
  const max = Math.max(1, ...data.map(d => d.value));
  return (
    <div className="flex flex-col gap-3.5">
      {data.map((d, i) => (
        <div key={i}>
          <div className="flex items-center justify-between mb-1.5">
            <span className="text-[12.5px] text-ink font-medium truncate pr-2">{d.label}</span>
            <span className="text-[12.5px] text-muted num shrink-0">{format(d.value)}</span>
          </div>
          <div className="h-2.5 rounded-full bg-[#F1FBD4] overflow-hidden">
            <div className="h-full rounded-full transition-all" style={{ width: `${(d.value / max) * 100}%`, background: d.color || 'var(--primary)' }} />
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---------- Mini compare (two bars: income vs cost) ---------- */
function MiniCompare({ income, cost, max }) {
  const m = max || Math.max(income, cost, 1);
  return (
    <div className="flex flex-col gap-1 w-[90px]">
      <div className="h-1.5 rounded-full bg-[#F1FBD4] overflow-hidden">
        <div className="h-full rounded-full" style={{ width: `${(income / m) * 100}%`, background: 'var(--pos)' }} />
      </div>
      <div className="h-1.5 rounded-full bg-[#F1FBD4] overflow-hidden">
        <div className="h-full rounded-full" style={{ width: `${(cost / m) * 100}%`, background: 'var(--primary)' }} />
      </div>
    </div>
  );
}

/* ---------- Chart legend item ---------- */
function LegendRow({ color, label, value, percent }) {
  return (
    <div className="flex items-center gap-2.5 py-1.5">
      <span className="w-2.5 h-2.5 rounded-[3px] shrink-0" style={{ background: color }} />
      <span className="text-[12.5px] text-ink truncate flex-1">{label}</span>
      <span className="text-[12px] text-muted num tabular-nums w-10 text-right">{percent}</span>
      <span className="text-[12.5px] text-ink num font-medium w-20 text-right">{value}</span>
    </div>
  );
}

/* ---------- Up / down bars (brief 28): income above the line (deep green), costs below (lime) ----------
   Like the reference's Cashflow chart. Drawn in SVG at the size of its box; a click on a month calls onPick(i). */
/* The size of a box, kept up to date when the window changes (the charts draw to fit it). */
function useBoxSize(initial) {
  const box = useRef(null);
  const [size, setSize] = useState(initial);
  useEffect(() => {
    const el = box.current; if (!el) return;
    const measure = () => setSize({ w: el.clientWidth, h: el.clientHeight });
    measure();
    const ro = new ResizeObserver(measure); ro.observe(el);
    return () => ro.disconnect();
  }, []);
  return [box, size];
}
const _k = v => '$' + (Math.abs(v) >= 1000 ? Math.round(v / 1000) + 'k' : Math.round(v));

/* Income vs costs (brief 29, Ana: the up / down bars were hard to read). Two rounded bars per period,
   side by side and overlapping by a third, both from zero: income deep green in front, costs lime
   behind. data: [{ label, income, cost }]. Click a bar pair to open its rows. */
function PairBars({ data, onPick }) {
  const [box, { w: W, h: H }] = useBoxSize({ w: 600, h: 220 });
  const [hover, setHover] = useState(null);
  const L = 48, B = 22, T = 8;
  const max = Math.max(1, ...data.map(d => Math.max(d.income, d.cost))) * 1.1;
  const sc = v => Math.max(0, v) / max * (H - B - T);
  const step = (W - L) / Math.max(1, data.length), bw = Math.max(6, Math.min(26, step * 0.32)), ov = bw / 3;
  return (
    <div ref={box} className="relative w-full h-full">
      <svg width={W} height={H} className="block">
        {[0, 0.25, 0.5, 0.75, 1].map(t => { const y = H - B - t * (H - B - T); return (
          <g key={t}>
            <line x1={L} x2={W} y1={y} y2={y} stroke={t === 0 ? '#D9DED5' : '#EEF1EA'} strokeDasharray={t === 0 ? undefined : '3 4'} />
            <text x={L - 8} y={y + 4} textAnchor="end" fontSize="11" fill="#9AA298" fontWeight="600">{_k(t * max)}</text>
          </g>); })}
        {data.map((d, i) => { const cx = L + step * i + step / 2, dim = hover !== null && hover !== i ? 0.45 : 1; return (
          <g key={i} style={{ cursor: onPick ? 'pointer' : 'default' }} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)} onClick={() => onPick && onPick(i)}>
            <rect x={cx - step / 2} y={0} width={step} height={H - B} fill="transparent" />
            <rect x={cx - ov / 2} y={H - B - sc(d.cost)} width={bw} height={sc(d.cost)} rx="7" fill="var(--lime)" opacity={dim} />
            <rect x={cx - bw + ov / 2} y={H - B - sc(d.income)} width={bw} height={sc(d.income)} rx="7" fill="var(--sidebar)" stroke="#fff" strokeWidth="2" opacity={dim} />
            <text x={cx} y={H - 5} textAnchor="middle" fontSize="11.5" fill="#7B847C" fontWeight="700">{d.label}</text>
          </g>); })}
      </svg>
      {hover !== null && data[hover] && (
        <div className="absolute z-10 pointer-events-none bg-surface border border-line rounded-xl px-3 py-2 text-[12px] shadow-pop whitespace-nowrap"
             style={{ left: Math.min(L + step * hover + step / 2 + 14, W - 160), top: 6 }}>
          <div className="font-800 text-ink mb-0.5">{data[hover].title || data[hover].label}</div>
          <div className="flex gap-3 justify-between"><span className="text-muted">Income</span><b className="num">{money0USD(data[hover].income)}</b></div>
          <div className="flex gap-3 justify-between"><span className="text-muted">Costs</span><b className="num">{money0USD(data[hover].cost)}</b></div>
          <div className="flex gap-3 justify-between"><span className="text-muted">{data[hover].income >= data[hover].cost ? 'Profit' : 'Loss'}</span><b className="num">{money0USD(Math.abs(data[hover].income - data[hover].cost))}</b></div>
        </div>
      )}
    </div>
  );
}

/* One bar per line, biggest first, each line clickable (Vehicles: fuel or repairs per truck).
   rows: [{ label, sub, value, onOpen }]. Stays readable at 20+ lines. */
function BarList({ rows, color = 'var(--sidebar)' }) {
  const max = Math.max(1, ...rows.map(r => r.value));
  return (
    <div className="flex flex-col">
      {rows.map(r => (
        <button key={r.label} type="button" onClick={r.onOpen} title={r.sub}
          className="grid grid-cols-[96px_1fr_84px] gap-3 items-center px-1.5 py-[5px] rounded-lg text-[13px] text-left hover:bg-[#F6F8F3]">
          <b className="num font-700 truncate">{r.label}</b>
          <span className="h-3 rounded-full overflow-hidden" style={{ background: '#EEF1EA' }}>
            <span className="block h-full rounded-full" style={{ width: `${r.value / max * 100}%`, background: color }} />
          </span>
          <span className="num text-right font-800">{money0USD(r.value)}</span>
        </button>
      ))}
    </div>
  );
}

/* One bar per month (Vehicles: fuel per month, all trucks together). data: [{ label, value, title }]. */
function MonthBars({ data, onPick, color = '#E6F4BE' }) {
  const [box, { w: W, h: H }] = useBoxSize({ w: 600, h: 180 });
  const [hover, setHover] = useState(null);
  const L = 44, B = 22, T = 8;
  const max = Math.max(1, ...data.map(d => d.value)) * 1.12;
  const step = (W - L) / Math.max(1, data.length), bw = Math.max(6, Math.min(30, step * 0.55));
  return (
    <div ref={box} className="relative w-full h-full">
      <svg width={W} height={H} className="block">
        {[0, 1 / 3, 2 / 3, 1].map(t => { const y = H - B - t * (H - B - T); return (
          <g key={t}>
            <line x1={L} x2={W} y1={y} y2={y} stroke={t === 0 ? '#D9DED5' : '#EEF1EA'} strokeDasharray={t === 0 ? undefined : '3 4'} />
            <text x={L - 6} y={y + 4} textAnchor="end" fontSize="11" fill="#9AA298" fontWeight="600">{_k(t * max)}</text>
          </g>); })}
        {data.map((d, i) => { const cx = L + step * i + step / 2, h = d.value / max * (H - B - T); return (
          <g key={i} style={{ cursor: onPick ? 'pointer' : 'default' }} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)} onClick={() => onPick && onPick(i)}>
            <rect x={cx - step / 2} y={0} width={step} height={H - B} fill="transparent" />
            <rect x={cx - bw / 2} y={H - B - h} width={bw} height={h} rx="7" fill={hover === i ? '#CFE88A' : color} />
            <text x={cx} y={H - 5} textAnchor="middle" fontSize="11.5" fill="#7B847C" fontWeight="700">{d.label}</text>
          </g>); })}
      </svg>
      {hover !== null && data[hover] && (
        <div className="absolute z-10 pointer-events-none bg-surface border border-line rounded-xl px-3 py-2 text-[12px] shadow-pop whitespace-nowrap"
             style={{ left: Math.min(L + step * hover + step / 2 + 14, W - 130), top: 6 }}>
          <div className="font-800 text-ink">{data[hover].title || data[hover].label}</div><b className="num">{money0USD(data[hover].value)}</b>
        </div>
      )}
    </div>
  );
}

/* The heat table (Vehicles: fuel per truck, by month). One row per truck, one cell per month, pale lime
   to olive (darker = more). A red edge marks a month 25% or more above that truck's own usual (its
   average over the months it had fuel). Readable at 20 to 30 trucks. rows: [{ label, sub, cells: [{ value,
   onOpen }] }], months: ['Jan', ...]. */
const HEAT_RAMP = [[246, 250, 234], [226, 241, 184], [178, 204, 120], [110, 138, 70]];
function heatColor(x) {
  const t = Math.min(0.999, Math.max(0, x)) * (HEAT_RAMP.length - 1), i = Math.floor(t), f = t - i;
  return 'rgb(' + HEAT_RAMP[i].map((c, k) => Math.round(c + (HEAT_RAMP[i + 1][k] - c) * f)).join(',') + ')';
}
function heatJump(value, values) {
  const used = values.filter(v => v > 0);
  if (!used.length || !(value > 0)) return false;
  return value >= 1.25 * used.reduce((a, b) => a + b, 0) / used.length;
}
function HeatTable({ rows, months, above = '25% above that truck\'s usual' }) {
  const all = rows.flatMap(r => r.cells.map(c => c.value)).filter(v => v > 0);
  const lo = Math.min(...all, 0), hi = Math.max(...all, 1);
  const [tip, setTip] = useState(null);
  return (
    <div className="relative">
      <div className="overflow-x-auto scroll-area">
        <table className="w-full border-collapse" style={{ tableLayout: 'fixed', minWidth: 140 + months.length * 46 }}>
          <thead><tr>
            <th className="w-[110px]" />
            {months.map(m => <th key={m} className="text-[11px] uppercase tracking-wide text-muted font-600 text-center pb-1.5">{m}</th>)}
            <th className="w-[84px] text-[11px] uppercase tracking-wide text-muted font-600 text-right pb-1.5">Total</th>
          </tr></thead>
          <tbody>
            {rows.map(r => {
              const vals = r.cells.map(c => c.value), total = vals.reduce((a, b) => a + b, 0);
              return (
                <tr key={r.label}>
                  <td className="text-[13px] font-700 num pr-2 py-[2px] truncate" title={r.sub}>{r.label}</td>
                  {r.cells.map((c, i) => { const jump = heatJump(c.value, vals); return (
                    <td key={i} className="p-[2px]">
                      <button type="button" onClick={c.onOpen} disabled={!c.value}
                        onMouseEnter={e => setTip({ x: e.currentTarget.offsetLeft, y: e.currentTarget.offsetTop, text: `${r.label} · ${months[i]}`, value: c.value, jump })}
                        onMouseLeave={() => setTip(null)}
                        className="block w-full h-[26px] rounded-[7px]"
                        style={{ background: c.value ? heatColor((c.value - lo) / ((hi - lo) || 1)) : '#F6F8F3', boxShadow: jump ? 'inset 0 0 0 2px var(--neg)' : undefined, cursor: c.value ? 'pointer' : 'default' }} />
                    </td>); })}
                  <td className="text-[13px] font-800 num text-right pl-2">{money0USD(total)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      {tip && (
        <div className="absolute z-10 pointer-events-none bg-surface border border-line rounded-xl px-3 py-2 text-[12px] shadow-pop whitespace-nowrap" style={{ left: tip.x + 24, top: tip.y - 44 }}>
          <div className="font-800 text-ink">{tip.text}</div><b className="num">{tip.value ? money0USD(tip.value) : 'no fuel'}</b>
          {tip.jump && <div style={{ color: 'var(--neg)' }} className="font-700">{above}</div>}
        </div>
      )}
      <div className="flex flex-wrap items-center gap-3.5 mt-2.5 text-[12px] text-muted">
        <span className="inline-flex items-center gap-1.5">Less <span className="inline-flex gap-0.5">{[0, 0.25, 0.5, 0.75, 1].map(x => <i key={x} className="inline-block w-[18px] h-[10px] rounded-[3px]" style={{ background: heatColor(x) }} />)}</span> More</span>
        <span className="inline-flex items-center gap-1.5"><i className="inline-block w-[14px] h-[10px] rounded-[3px]" style={{ boxShadow: 'inset 0 0 0 2px var(--neg)' }} /> a month {above}</span>
      </div>
    </div>
  );
}

/* palette for categories / vehicles */
const CHART_PALETTE = ['#0F3B2C', '#D1F470', '#4E7D62', '#E6F4BE', '#7FB653', '#2E5E48', '#BFD9AA', '#93A89A', '#C9CFC6'];

Object.assign(window, { PairBars, BarList, MonthBars, HeatTable, heatColor, heatJump, useBoxSize, GroupedBars, Donut, HBars, MiniCompare, LegendRow, CHART_PALETTE });
