/* The centerpiece: interactive "What if?" dashboard.
   Looks like a real working tool. Driven by 4 sliders that recompute KPIs + chart live. */
const R = window.Recharts;

const MONTHS = ["Янв","Фев","Мар","Апр","Май","Июн","Июл","Авг","Сен","Окт","Ноя","Дек"];

/* Base business state (rounded, plausible for ~25-50 person company) */
const BASE = {
  monthlyRevenue: 4_200_000,           // ₽
  revenueGrowthMoM: 0.012,             // 1.2% mom
  cogsRatio: 0.42,                     // себестоимость
  fixedOpex: 1_350_000,                // ФОТ + аренда + прочее
  marketingBase: 280_000,              // маркетинг
  avgCheck: 84_000,
  seasonality: [0.92,0.95,1.02,1.05,1.08,1.10,0.96,0.93,1.04,1.07,1.04,0.98],
  taxRate: 0.06,                       // УСН 6% упрощённо
};

function buildSeries({ revenueDelta, marketingDelta, hires, checkDelta }) {
  const data = [];
  let cashBalance = 1_800_000;
  let scnCashBalance = 1_800_000;

  const newOpexFromHires = hires * 110_000; // средняя стоимость найма + ФОТ в месяц

  for (let i = 0; i < 12; i++) {
    const seasonalFactor = BASE.seasonality[i];
    const growth = Math.pow(1 + BASE.revenueGrowthMoM, i);

    // base
    const bRev = BASE.monthlyRevenue * growth * seasonalFactor;
    const bCogs = bRev * BASE.cogsRatio;
    const bOpex = BASE.fixedOpex + BASE.marketingBase;
    const bGross = bRev - bCogs;
    const bEbit = bGross - BASE.fixedOpex - BASE.marketingBase;
    const bTax = bRev * BASE.taxRate;
    const bNet = bEbit - bTax;
    cashBalance += bNet;

    // scenario
    const checkBoost = 1 + (checkDelta / 100) * 0.6; // повышение чека не масштабируется один-к-одному
    const sRev = bRev * (1 + revenueDelta / 100) * checkBoost;
    const sCogs = sRev * BASE.cogsRatio;
    const sMarketing = BASE.marketingBase * (1 + marketingDelta / 100);
    const sOpex = BASE.fixedOpex + sMarketing + newOpexFromHires;
    const sGross = sRev - sCogs;
    const sEbit = sGross - sOpex;
    const sTax = sRev * BASE.taxRate;
    const sNet = sEbit - sTax;
    scnCashBalance += sNet;

    data.push({
      m: MONTHS[i],
      base: Math.round(bNet),
      scn: Math.round(sNet),
      baseCash: Math.round(cashBalance),
      scnCash: Math.round(scnCashBalance),
      rev: Math.round(sRev),
      gross: Math.round(sGross),
    });
  }
  return data;
}

function sum(arr, key) { return arr.reduce((a, r) => a + r[key], 0); }

const Slider = ({ label, value, setValue, min, max, step, suffix = "%", help }) => (
  <div>
    <div className="flex items-start justify-between gap-3 mb-2">
      <div className="min-w-0">
        <div className="text-[12px] uppercase tracking-[0.18em] text-mute font-medium leading-tight">{label}</div>
        {help && <div className="text-[11px] text-mute/80 mt-1 leading-snug">{help}</div>}
      </div>
      <div className="num text-teal-800 text-lg tnum leading-none pt-0.5 whitespace-nowrap">
        {value > 0 ? "+" : ""}{value}{suffix}
      </div>
    </div>
    <input type="range" className="rng w-full" min={min} max={max} step={step}
           value={value} onChange={(e) => setValue(parseFloat(e.target.value))} aria-label={label} />
    <div className="flex justify-between text-[10px] text-mute/70 mt-1 num tnum">
      <span>{min}{suffix}</span><span>0</span><span>+{max}{suffix}</span>
    </div>
  </div>
);

function KPI({ label, base, scn, format = fmtK, suffix = "₽", positive = true }) {
  const delta = scn - base;
  const pct = base === 0 ? 0 : (delta / Math.abs(base)) * 100;
  const goodSign = positive ? delta >= 0 : delta <= 0;
  return (
    <div className="px-5 py-4 border-r border-line last:border-r-0 first:pl-0 min-w-0">
      <div className="text-[10.5px] uppercase tracking-[0.2em] text-mute font-medium">{label}</div>
      <div className="mt-2 flex items-baseline gap-2 flex-wrap">
        <div className="num text-2xl text-ink tnum">{format(scn)} <span className="text-[15px] text-mute">{suffix}</span></div>
      </div>
      <div className="mt-1.5 flex items-center gap-1.5 text-[11px] tnum num">
        <span className={goodSign ? "text-emerald-700" : "text-danger"}>
          {delta >= 0 ? "▲" : "▼"} {pct.toFixed(1).replace('.', ',')}%
        </span>
        <span className="text-mute/80">vs база</span>
      </div>
    </div>
  );
}

function WhatIfDashboard() {
  const [revenueDelta, setRevenueDelta]   = useState(20);
  const [marketingDelta, setMarketingDelta] = useState(15);
  const [hires, setHires] = useState(1);
  const [checkDelta, setCheckDelta] = useState(8);
  const [tab, setTab] = useState("cash"); // cash | pl | scenarios

  const base = useMemo(() => buildSeries({ revenueDelta: 0, marketingDelta: 0, hires: 0, checkDelta: 0 }), []);
  const scn  = useMemo(() => buildSeries({ revenueDelta, marketingDelta, hires, checkDelta }), [revenueDelta, marketingDelta, hires, checkDelta]);

  const merged = base.map((r, i) => ({ ...r, base: r.base, baseCash: r.baseCash, scnCash: scn[i].scnCash, scn: scn[i].scn, rev: scn[i].rev, gross: scn[i].gross }));

  const kpis = {
    revBase: sum(base, "base") + sum(base, "base") * 0, // placeholder for revenue (use rev from each)
  };
  const annualRevBase = base.reduce((a, r) => a + (r.base + (BASE.fixedOpex + BASE.marketingBase) + r.base*0), 0); // not used
  const annualRev = {
    base: base.reduce((a) => a, 0) // placeholder
  };

  // Better KPI math: recompute totals directly
  const totBase = base.reduce((a, r) => ({ rev: a.rev + 0, net: a.net + r.base, cash: r.baseCash }), { rev: 0, net: 0, cash: base[base.length-1].baseCash });
  const totScn  = scn .reduce((a, r) => ({ rev: a.rev + r.rev, net: a.net + r.scn, cash: r.scnCash }), { rev: 0, net: 0, cash: scn[scn.length-1].scnCash });
  // recompute base revenue:
  let baseRev = 0, baseGross = 0;
  for (let i = 0; i < 12; i++) {
    const r = BASE.monthlyRevenue * Math.pow(1 + BASE.revenueGrowthMoM, i) * BASE.seasonality[i];
    baseRev += r; baseGross += r * (1 - BASE.cogsRatio);
  }
  totBase.rev = baseRev;
  const scnGross = scn.reduce((a, r) => a + r.gross, 0);

  const cashFloor = (arr, key) => Math.min(...arr.map(r => r[key]));
  const dipBase = cashFloor(base, "baseCash");
  const dipScn  = cashFloor(scn,  "scnCash");

  /* Scenario presets */
  const presets = [
    { id: "base",    label: "Базовый",       set: () => { setRevenueDelta(0); setMarketingDelta(0); setHires(0); setCheckDelta(0); } },
    { id: "growth",  label: "+20% продаж",   set: () => { setRevenueDelta(20); setMarketingDelta(15); setHires(1); setCheckDelta(8); } },
    { id: "stress",  label: "Стресс −15%",   set: () => { setRevenueDelta(-15); setMarketingDelta(-10); setHires(0); setCheckDelta(-5); } },
    { id: "scale",   label: "Масштаб",       set: () => { setRevenueDelta(40); setMarketingDelta(30); setHires(3); setCheckDelta(12); } },
  ];
  const activePreset =
       revenueDelta===0 && marketingDelta===0 && hires===0 && checkDelta===0 ? "base"
     : revenueDelta===20 && marketingDelta===15 && hires===1 && checkDelta===8 ? "growth"
     : revenueDelta===-15 && marketingDelta===-10 && hires===0 && checkDelta===-5 ? "stress"
     : revenueDelta===40 && marketingDelta===30 && hires===3 && checkDelta===12 ? "scale"
     : "custom";

  return (
    <div className="bg-white border border-line rounded-2xl shadow-pop overflow-hidden">
      {/* Top chrome — looks like a real app */}
      <div className="flex items-center justify-between px-5 py-3 bg-teal-900 text-paper border-b border-teal-950/40">
        <div className="flex items-center gap-3">
          <div className="flex gap-1.5">
            <span className="w-2.5 h-2.5 rounded-full bg-paper/20"></span>
            <span className="w-2.5 h-2.5 rounded-full bg-paper/20"></span>
            <span className="w-2.5 h-2.5 rounded-full bg-paper/20"></span>
          </div>
          <div className="hidden sm:flex items-center gap-2 text-[12px] text-paper/70 font-mono">
            <span className="text-paper/40">/</span>
            <span>модель</span>
            <span className="text-paper/40">/</span>
            <span className="text-paper">ремонт-сервис · 2026</span>
          </div>
        </div>
        <div className="flex items-center gap-1 text-[12px]">
          {["cash","pl","scenarios"].map((t) => (
            <button key={t} onClick={() => setTab(t)}
              className={"relative px-3 py-1.5 rounded-md transition-colors " + (tab === t ? "tab-active" : "text-paper/55 hover:text-paper/85")}>
              {t === "cash" ? "Денежный поток" : t === "pl" ? "P&L по месяцам" : "Сравнение сценариев"}
            </button>
          ))}
        </div>
      </div>

      {/* KPIs */}
      <div className="grid grid-cols-2 md:grid-cols-4 px-5 py-1 border-b border-line bg-paper/40">
        <KPI label="Выручка / год"  base={totBase.rev}    scn={totScn.rev}   />
        <KPI label="Чистая прибыль" base={totBase.net}    scn={totScn.net}   />
        <KPI label="Касса на конец" base={totBase.cash}   scn={totScn.cash}  />
        <KPI label="Мин. остаток"   base={dipBase}        scn={dipScn}       />
      </div>

      {/* Chart + controls */}
      <div className="grid grid-cols-1 lg:grid-cols-[1.7fr_1fr] gap-0">
        <div className="p-5 lg:p-6 lg:border-r border-line min-w-0">
          {/* preset chips + period */}
          <div className="flex items-center justify-between flex-wrap gap-3 mb-4">
            <div className="flex items-center gap-1.5 flex-wrap">
              {presets.map(p => (
                <button key={p.id} onClick={p.set}
                  className={"text-[12px] px-3 py-1.5 rounded-full border transition-colors " +
                    (activePreset === p.id
                      ? "bg-teal-900 text-paper border-teal-900"
                      : "bg-white text-ink2 border-line hover:border-teal-500 hover:text-teal-800")}>
                  {p.label}
                </button>
              ))}
              {activePreset === "custom" && (
                <span className="text-[11px] uppercase tracking-[0.18em] text-mute font-medium ml-1">· свой сценарий</span>
              )}
            </div>
            <div className="flex items-center gap-2 text-[12px] text-mute font-mono">
              <span className="inline-flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-teal-300"></span>База</span>
              <span className="inline-flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-emerald-600"></span>Сценарий</span>
            </div>
          </div>

          <div className="h-[300px]">
            <R.ResponsiveContainer width="100%" height="100%">
              {tab === "cash" ? (
                <R.AreaChart data={merged} margin={{ top: 8, right: 12, left: 8, bottom: 0 }}>
                  <defs>
                    <linearGradient id="gScn" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%"  stopColor="#0F766E" stopOpacity={0.18}/>
                      <stop offset="100%" stopColor="#0F766E" stopOpacity={0}/>
                    </linearGradient>
                  </defs>
                  <R.CartesianGrid vertical={false} />
                  <R.XAxis dataKey="m" axisLine={false} tickLine={false} />
                  <R.YAxis tickFormatter={(v) => (v/1_000_000).toFixed(1) + " млн"} axisLine={false} tickLine={false} />
                  <R.Tooltip formatter={(v) => fmt(v) + " ₽"} labelClassName="text-mute" contentStyle={{ background: "#fff" }}/>
                  <R.Area type="monotone" dataKey="scnCash" name="Сценарий" stroke="#0F766E" strokeWidth={2.2} fill="url(#gScn)" />
                  <R.Line type="monotone" dataKey="baseCash" name="База" stroke="#8AABAD" strokeWidth={1.6} strokeDasharray="4 3" dot={false} />
                  <R.ReferenceLine y={0} stroke="#B45741" strokeWidth={1} strokeDasharray="2 4" />
                </R.AreaChart>
              ) : tab === "pl" ? (
                <R.ComposedChart data={merged} margin={{ top: 8, right: 12, left: 8, bottom: 0 }}>
                  <R.CartesianGrid vertical={false} />
                  <R.XAxis dataKey="m" axisLine={false} tickLine={false} />
                  <R.YAxis tickFormatter={(v) => (v/1_000_000).toFixed(1) + " млн"} axisLine={false} tickLine={false} />
                  <R.Tooltip formatter={(v) => fmt(v) + " ₽"} />
                  <R.Bar dataKey="rev"   name="Выручка"    fill="#D8E2E2" radius={[3,3,0,0]} barSize={14} />
                  <R.Bar dataKey="gross" name="Валовая"     fill="#8AABAD" radius={[3,3,0,0]} barSize={14} />
                  <R.Line type="monotone" dataKey="scn" name="Чистая прибыль" stroke="#0F766E" strokeWidth={2.2} dot={{ r:2.5, fill: "#0F766E" }} />
                </R.ComposedChart>
              ) : (
                <R.BarChart data={[
                    { name: "Выручка",        base: totBase.rev,  scn: totScn.rev  },
                    { name: "Валовая",        base: baseGross,    scn: scnGross    },
                    { name: "Чистая прибыль", base: totBase.net,  scn: totScn.net  },
                    { name: "Касса (итог)",   base: totBase.cash, scn: totScn.cash },
                  ]} margin={{ top: 8, right: 12, left: 8, bottom: 0 }}>
                  <R.CartesianGrid vertical={false} />
                  <R.XAxis dataKey="name" axisLine={false} tickLine={false} />
                  <R.YAxis tickFormatter={(v) => (v/1_000_000).toFixed(0) + " млн"} axisLine={false} tickLine={false} />
                  <R.Tooltip formatter={(v) => fmt(v) + " ₽"} />
                  <R.Bar dataKey="base" name="База"      fill="#8AABAD" radius={[3,3,0,0]} barSize={26} />
                  <R.Bar dataKey="scn"  name="Сценарий"  fill="#0F766E" radius={[3,3,0,0]} barSize={26} />
                </R.BarChart>
              )}
            </R.ResponsiveContainer>
          </div>

          {/* footnote */}
          <div className="mt-4 flex items-start gap-2 text-[11.5px] text-mute leading-relaxed">
            <span className="num text-emerald-700 mt-px">●</span>
            <span>
              Модель пересчитывает 12 месяцев на лету. Это упрощённый демо-расчёт; в реальной работе модель строится
              на ваших данных из 1С, банков и Excel — учитывает сезонность, кассовые разрывы и налоговый режим.
            </span>
          </div>
        </div>

        {/* Controls */}
        <div className="p-5 lg:p-6 bg-paper/30">
          <div className="text-[11px] uppercase tracking-[0.22em] text-mute font-medium mb-1">Параметры сценария</div>
          <div className="text-sm text-ink2 mb-5">Двигайте бегунки — KPI и графики пересчитаются мгновенно.</div>

          <div className="space-y-6">
            <Slider label="Изменение продаж"  value={revenueDelta}   setValue={setRevenueDelta}   min={-40} max={60} step={1}  help="общий объём заказов" />
            <Slider label="Маркетинг"          value={marketingDelta} setValue={setMarketingDelta} min={-50} max={80} step={5}  help="бюджет на привлечение" />
            <Slider label="Средний чек"        value={checkDelta}     setValue={setCheckDelta}     min={-15} max={25} step={1}  help="цена / маржинальность" />
            <Slider label="Найм"               value={hires}          setValue={setHires}          min={0}   max={5}  step={1}  suffix=" чел." help="доп. ФОТ ~110 тыс ₽/мес на человека" />
          </div>

          <div className="mt-6 pt-5 border-t border-line/80 grid grid-cols-2 gap-3">
            <div>
              <div className="text-[10.5px] uppercase tracking-[0.18em] text-mute">Δ Чистая прибыль</div>
              <div className={"num tnum text-lg mt-1 " + (totScn.net - totBase.net >= 0 ? "text-emerald-700" : "text-danger")}>
                {totScn.net - totBase.net >= 0 ? "+" : "−"}{fmt(Math.abs(totScn.net - totBase.net))} ₽
              </div>
            </div>
            <div>
              <div className="text-[10.5px] uppercase tracking-[0.18em] text-mute">Кассовый разрыв</div>
              <div className={"num tnum text-lg mt-1 " + (dipScn >= 0 ? "text-emerald-700" : "text-danger")}>
                {dipScn >= 0 ? "не возникает" : "− " + fmtK(Math.abs(dipScn)) + " ₽"}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.WhatIfDashboard = WhatIfDashboard;
