/* Three report mockups: P&L waterfall, Balance stacked, DDS line chart. */
const RC = window.Recharts;

/* P&L waterfall — built on stacked bars with invisible base */
function PLWaterfall() {
  const steps = [
    { name: "Выручка",      v:  6480 },
    { name: "Себестоимость",v: -2720 },
    { name: "Валовая",      v:  3760, total: true },
    { name: "Маркетинг",    v:  -380 },
    { name: "ФОТ и аренда", v: -2010 },
    { name: "Налоги",       v:  -388 },
    { name: "Чистая",       v:   982, total: true },
  ];
  // build cumulative for waterfall
  let cum = 0;
  const data = steps.map((s) => {
    if (s.total) {
      const row = { name: s.name, base: 0, up: s.v > 0 ? s.v : 0, down: s.v < 0 ? -s.v : 0, total: s.v };
      cum = s.v;
      return row;
    }
    const base = s.v >= 0 ? cum : cum + s.v;
    const up   = s.v > 0 ? s.v : 0;
    const down = s.v < 0 ? -s.v : 0;
    cum += s.v;
    return { name: s.name, base, up, down };
  });
  return (
    <RC.ResponsiveContainer width="100%" height="100%">
      <RC.BarChart data={data} margin={{ top: 8, right: 4, left: 4, bottom: 0 }}>
        <RC.CartesianGrid vertical={false} />
        <RC.XAxis dataKey="name" axisLine={false} tickLine={false} interval={0} tick={{ fontSize: 9.5 }} />
        <RC.YAxis tickFormatter={(v) => v + "к"} axisLine={false} tickLine={false} />
        <RC.Tooltip formatter={(v, n) => [fmt(v*1000) + " ₽", ""]} />
        <RC.Bar dataKey="base"  stackId="a" fill="transparent" />
        <RC.Bar dataKey="up"    stackId="a" fill="#0F766E" radius={[2,2,0,0]} />
        <RC.Bar dataKey="down"  stackId="a" fill="#B45741" radius={[2,2,0,0]} />
        <RC.Bar dataKey="total" stackId="b" fill="#4A7A7D" radius={[2,2,0,0]} />
      </RC.BarChart>
    </RC.ResponsiveContainer>
  );
}

/* Balance — stacked horizontal */
function BalanceMini() {
  const assets = [
    { label: "Деньги на счетах",  v: 1820, c: "#0F766E" },
    { label: "Дебиторка",         v: 2240, c: "#4A7A7D" },
    { label: "Запасы",            v: 1480, c: "#8AABAD" },
    { label: "Основные средства", v: 3360, c: "#B3C7C8" },
  ];
  const liab = [
    { label: "Кредиторка",        v: 1640, c: "#C9A961" },
    { label: "Налоги к уплате",   v:  410, c: "#B89146" },
    { label: "Займы",             v: 1200, c: "#8C6A30" },
    { label: "Собственный капитал", v: 5650, c: "#2E4D4F" },
  ];
  const totA = assets.reduce((a,r) => a+r.v, 0);
  const totL = liab.reduce((a,r) => a+r.v, 0);

  const Bar = ({ rows, total }) => (
    <div className="flex w-full h-3 rounded-full overflow-hidden bg-paper/60 border border-line">
      {rows.map((r,i) => (
        <div key={i} title={r.label} style={{ width: (r.v/total)*100 + "%", background: r.c }} />
      ))}
    </div>
  );
  const Legend = ({ rows, total }) => (
    <div className="grid grid-cols-2 gap-x-3 gap-y-1.5 mt-3 text-[11px]">
      {rows.map((r,i) => (
        <div key={i} className="flex items-center justify-between gap-2 min-w-0">
          <div className="flex items-center gap-1.5 min-w-0">
            <span className="w-2 h-2 rounded-sm flex-shrink-0" style={{ background: r.c }}></span>
            <span className="truncate text-ink2">{r.label}</span>
          </div>
          <span className="num tnum text-mute">{r.v}к</span>
        </div>
      ))}
    </div>
  );
  return (
    <div className="space-y-4">
      <div>
        <div className="flex items-center justify-between text-[11px] mb-1.5">
          <span className="uppercase tracking-[0.18em] text-mute font-medium">Активы</span>
          <span className="num tnum text-ink">{totA.toLocaleString('ru')} тыс ₽</span>
        </div>
        <Bar rows={assets} total={totA} />
        <Legend rows={assets} total={totA} />
      </div>
      <div>
        <div className="flex items-center justify-between text-[11px] mb-1.5">
          <span className="uppercase tracking-[0.18em] text-mute font-medium">Пассивы</span>
          <span className="num tnum text-ink">{totL.toLocaleString('ru')} тыс ₽</span>
        </div>
        <Bar rows={liab} total={totL} />
        <Legend rows={liab} total={totL} />
      </div>
    </div>
  );
}

/* DDS — line chart in/out */
function DDSMini() {
  const data = [
    { m:"Янв", in: 5.1, out: 4.6 },
    { m:"Фев", in: 4.7, out: 4.5 },
    { m:"Мар", in: 5.6, out: 4.9 },
    { m:"Апр", in: 6.1, out: 5.3 },
    { m:"Май", in: 6.4, out: 5.5 },
    { m:"Июн", in: 6.8, out: 5.7 },
    { m:"Июл", in: 5.9, out: 5.4 },
    { m:"Авг", in: 5.6, out: 5.2 },
    { m:"Сен", in: 6.5, out: 5.6 },
  ];
  return (
    <RC.ResponsiveContainer width="100%" height="100%">
      <RC.LineChart data={data} margin={{ top: 8, right: 6, left: 4, bottom: 0 }}>
        <RC.CartesianGrid vertical={false} />
        <RC.XAxis dataKey="m" axisLine={false} tickLine={false} tick={{ fontSize: 10 }} />
        <RC.YAxis tickFormatter={(v) => v + "м"} axisLine={false} tickLine={false} />
        <RC.Tooltip formatter={(v) => v + " млн ₽"} />
        <RC.Line type="monotone" dataKey="in"  name="Приток" stroke="#0F766E" strokeWidth={2}  dot={{ r:2.4, fill:"#0F766E" }} />
        <RC.Line type="monotone" dataKey="out" name="Отток"  stroke="#B45741" strokeWidth={2} strokeDasharray="3 3" dot={{ r:2.4, fill:"#B45741" }} />
      </RC.LineChart>
    </RC.ResponsiveContainer>
  );
}

function ReportCard({ title, abbr, tagline, footer, children, h = 150 }) {
  return (
    <Card className="p-6 flex flex-col gap-4 hover:border-teal-300 transition-colors">
      <div className="flex items-start justify-between gap-4">
        <div className="min-w-0">
          <div className="text-[11px] uppercase tracking-[0.22em] text-teal-700 font-medium mb-1.5">{abbr}</div>
          <h3 className="font-serif text-[22px] leading-tight text-ink tracking-tightish">{title}</h3>
        </div>
        <div className="text-[11px] text-mute font-mono whitespace-nowrap">янв–сен 2026</div>
      </div>
      <p className="text-[13.5px] text-ink2 leading-relaxed">{tagline}</p>
      <div style={{ height: h }} className="mt-1">
        {children}
      </div>
      {footer && (
        <div className="pt-3 border-t border-line text-[12px] text-mute flex items-center justify-between">
          {footer}
        </div>
      )}
    </Card>
  );
}

window.PLWaterfall = PLWaterfall;
window.BalanceMini = BalanceMini;
window.DDSMini     = DDSMini;
window.ReportCard  = ReportCard;
