// screens-roi.jsx — ROI Calculator screen (CP-16)
//
// Calculation flow (migrated to Python backend):
//   1. User changes any input → debounce fires after 400 ms.
//   2. Keeper.api.calculateRoi(inputs) sends POST /api/v1/roi/calculate to the
//      api_gateway, which proxies to the reporting_service Python domain logic.
//   3. On success the backend result replaces the local result state.
//   4. On network/backend error the screen falls back silently to the local
//      Keeper.roi.calculate() formula so the UI remains interactive.
//
// Local formula (Keeper.roi.calculate) is still used for:
//   - The initial synchronous render before the first API response arrives.
//   - Any transient backend failure (debounce cycle restores backend path).
//
// The formula note at the bottom now reflects the backend source.
//
// Pattern mirrors other screens (screens-overview.jsx, screens-work.jsx):
//   - React.useState / React.useEffect for local state
//   - Keeper.api.calculateRoi for async backend calculation
//   - Keeper.roi.calculate as synchronous fallback
//   - Keeper.roi.formatNumber() for consistent number display
//   - Exported to window.RoiCalculator so App.jsx can reference it

/* ─── CP-16 ROI Calculator ────────────────────────────────── */
function RoiCalculator() {
  // ── Demo defaults (snake_case keys match the backend POST body) ──────────
  const DEFAULTS = {
    hectares:     4,
    yield_per_ha: 280,
    price_per_ton: 900,
    gain_pct:     6,
    cost_per_ha:  38000,
  };

  const [inputs, setInputs] = React.useState(DEFAULTS);

  // result: current calculation output.
  // Initialised synchronously from the local formula so the first render is
  // instant; replaced by the backend response once the first API call returns.
  const [result, setResult] = React.useState(() => _localCalc(DEFAULTS));

  // Loading / error state — user feedback without blocking the UI.
  const [loading, setLoading] = React.useState(false);
  const [backendError, setBackendError] = React.useState(null);

  const fmt = Keeper.roi.formatNumber;

  // ── Local fallback helper ─────────────────────────────────────────────────
  // Adapts snake_case inputs → roi.js camelCase params and returns the result
  // in the display shape (camelCase) expected by the JSX below.
  function _localCalc(inp) {
    return Keeper.roi.calculate({
      hectares:   inp.hectares,
      yieldPerHa: inp.yield_per_ha,
      pricePerTon: inp.price_per_ton,
      gainPct:    inp.gain_pct,
      costPerHa:  inp.cost_per_ha,
    });
  }

  // ── Backend → display shape normalisation ────────────────────────────────
  // The backend returns snake_case; the JSX was originally written against the
  // roi.js camelCase shape.  We adapt here so both paths share one render tree.
  function _normaliseBackendResult(r) {
    return {
      baselineRevenue:    r.baseline_revenue,
      incrementalRevenue: r.incremental_revenue,
      implementationCost: r.implementation_cost,
      paybackRatio:       r.payback_ratio,
      payback: r.payback ? {
        status: r.payback.status,
        months: r.payback.months,
        years:  r.payback.years,
        reason: r.payback.reason,
      } : null,
      breakdown: r.breakdown ? {
        revenue: (r.breakdown.revenue || []).map(item => ({
          id:       item.id,
          label:    item.label,
          value:    item.value,
          sharePct: item.share_pct,
        })),
        cost: r.breakdown.cost || [],
        chart: {
          incrementalVsBaselinePct: r.breakdown.chart
            ? r.breakdown.chart.incremental_vs_baseline_pct
            : 0,
        },
        totals: r.breakdown.totals || { revenue: 0, cost: 0 },
      } : null,
    };
  }

  // ── Backend calculation (debounced 400 ms) ────────────────────────────────
  React.useEffect(() => {
    let cancelled = false;

    const timer = setTimeout(async () => {
      if (cancelled) return;

      // Guard: skip if API module is not available (e.g. tests or offline dev).
      if (!window.Keeper || !window.Keeper.api || typeof window.Keeper.api.calculateRoi !== "function") {
        setResult(_localCalc(inputs));
        return;
      }

      setLoading(true);
      setBackendError(null);

      try {
        const backendResult = await Keeper.api.calculateRoi(inputs);
        if (!cancelled) {
          setResult(_normaliseBackendResult(backendResult));
          setLoading(false);
        }
      } catch (err) {
        if (!cancelled) {
          // Silently fall back — the user still sees numbers, just from the
          // local formula.  A small banner tells them backend is unavailable.
          setResult(_localCalc(inputs));
          setBackendError(
            (err && err.backendMessage)
              ? err.backendMessage
              : "Backend unavailable — using local calculation."
          );
          setLoading(false);
        }
      }
    }, 400);

    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [inputs]);

  function handleChange(field, raw) {
    const value = parseFloat(raw) || 0;
    setInputs(prev => ({ ...prev, [field]: value }));
  }

  const paybackMonths = result.payback ? result.payback.months : null;

  return (
    <div className="page" data-screen-label="16 ROI-калькулятор">
      <div className="page-head">
        <div>
          <div className="page-title">ROI-калькулятор</div>
          <div className="page-sub">
            Прогноз дополнительной выручки и окупаемости на основе агрономических параметров
          </div>
        </div>
        <div className="actions">
          {loading && (
            <span style={{ fontSize: 12, color: "var(--fg-muted)", display: "flex", alignItems: "center", gap: 6 }}>
              <i className="ri-loader-4-line" style={{ fontSize: 14 }}></i>
              Расчёт…
            </span>
          )}
          <button className="btn btn--secondary" onClick={() => setInputs(DEFAULTS)}>
            <i className="ri-refresh-line"></i>Сбросить
          </button>
        </div>
      </div>

      {backendError && (
        <div style={{
          padding: "8px 14px",
          background: "rgba(160,66,0,.06)",
          border: "1px solid rgba(160,66,0,.2)",
          borderRadius: 8,
          fontSize: 12,
          color: "#a04200",
          marginBottom: 12,
          display: "flex",
          alignItems: "center",
          gap: 8,
        }}>
          <i className="ri-wifi-off-line" style={{ fontSize: 14 }}></i>
          <span>{backendError}</span>
        </div>
      )}

      <div className="page-row row-2">
        {/* ── Input panel ─────────────────────────────────────────────────── */}
        <div className="card">
          <h3 className="card-title">Параметры расчёта</h3>

          <div className="stack" style={{ gap: 16 }}>

            <div className="row">
              <div>
                <div className="l">Площадь, га</div>
                <div className="desc">Суммарная площадь теплиц под расчёт</div>
              </div>
              <div>
                <input
                  type="number"
                  min="0"
                  step="0.1"
                  value={inputs.hectares}
                  onChange={e => handleChange("hectares", e.target.value)}
                  style={{
                    height: 36,
                    border: "1px solid var(--border)",
                    borderRadius: 8,
                    padding: "0 12px",
                    font: "500 14px Inter",
                    width: 140,
                    textAlign: "right",
                  }}
                />
              </div>
            </div>

            <div className="row">
              <div>
                <div className="l">Базовая урожайность, т/га</div>
                <div className="desc">Плановый урожай без применения системы</div>
              </div>
              <div>
                <input
                  type="number"
                  min="0"
                  step="1"
                  value={inputs.yield_per_ha}
                  onChange={e => handleChange("yield_per_ha", e.target.value)}
                  style={{
                    height: 36,
                    border: "1px solid var(--border)",
                    borderRadius: 8,
                    padding: "0 12px",
                    font: "500 14px Inter",
                    width: 140,
                    textAlign: "right",
                  }}
                />
              </div>
            </div>

            <div className="row">
              <div>
                <div className="l">Цена реализации, $/т</div>
                <div className="desc">Средняя отпускная цена за тонну продукции</div>
              </div>
              <div>
                <input
                  type="number"
                  min="0"
                  step="10"
                  value={inputs.price_per_ton}
                  onChange={e => handleChange("price_per_ton", e.target.value)}
                  style={{
                    height: 36,
                    border: "1px solid var(--border)",
                    borderRadius: 8,
                    padding: "0 12px",
                    font: "500 14px Inter",
                    width: 140,
                    textAlign: "right",
                  }}
                />
              </div>
            </div>

            <div className="row">
              <div>
                <div className="l">Прирост урожайности, %</div>
                <div className="desc">Ожидаемый прирост от оптимизации опыления</div>
              </div>
              <div>
                <input
                  type="number"
                  min="0"
                  max="100"
                  step="0.5"
                  value={inputs.gain_pct}
                  onChange={e => handleChange("gain_pct", e.target.value)}
                  style={{
                    height: 36,
                    border: "1px solid var(--border)",
                    borderRadius: 8,
                    padding: "0 12px",
                    font: "500 14px Inter",
                    width: 140,
                    textAlign: "right",
                  }}
                />
              </div>
            </div>

            <div className="row">
              <div>
                <div className="l">Стоимость внедрения, ₽/га</div>
                <div className="desc">Единовременные затраты на подключение системы</div>
              </div>
              <div>
                <input
                  type="number"
                  min="0"
                  step="1000"
                  value={inputs.cost_per_ha}
                  onChange={e => handleChange("cost_per_ha", e.target.value)}
                  style={{
                    height: 36,
                    border: "1px solid var(--border)",
                    borderRadius: 8,
                    padding: "0 12px",
                    font: "500 14px Inter",
                    width: 140,
                    textAlign: "right",
                  }}
                />
              </div>
            </div>

          </div>

          {/* Formula note */}
          <div style={{
            marginTop: 20,
            padding: "10px 12px",
            background: "var(--n-50)",
            borderRadius: 8,
            fontSize: 11,
            color: "var(--fg-muted)",
            fontFamily: "ui-monospace, Menlo, monospace",
            lineHeight: 1.7,
          }}>
            <div style={{ fontWeight: 700, marginBottom: 4, color: "var(--fg)" }}>
              Формула (Python backend · reporting_service)
            </div>
            <div>baseline_revenue = га × т/га × $/т</div>
            <div>incremental_revenue = baseline_revenue × (% / 100)</div>
            <div>implementation_cost = га × ₽/га</div>
            <div>payback_ratio = incremental_revenue / implementation_cost</div>
          </div>
        </div>

        {/* ── Results panel ───────────────────────────────────────────────── */}
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>

          {/* KPI row */}
          <div className="kpi-grid" style={{ gridTemplateColumns: "repeat(2, 1fr)" }}>
            <div className="kpi">
              <div className="kpi-lbl">
                Базовая выручка
                <i className="ri-money-dollar-circle-line"></i>
              </div>
              <div className="kpi-val">
                ${fmt(result.baselineRevenue)}
              </div>
              <div className="kpi-delta">
                в год без системы
              </div>
            </div>

            <div className="kpi">
              <div className="kpi-lbl">
                Доп. выручка
                <i className="ri-arrow-up-circle-line"></i>
              </div>
              <div className="kpi-val" style={{ color: result.incrementalRevenue > 0 ? "var(--color-ok, #26972B)" : undefined }}>
                +${fmt(result.incrementalRevenue)}
              </div>
              <div className="kpi-delta up">
                ежегодный прирост
              </div>
            </div>

            <div className="kpi">
              <div className="kpi-lbl">
                Стоимость внедрения
                <i className="ri-funds-line"></i>
              </div>
              <div className="kpi-val">
                ₽{fmt(result.implementationCost)}
              </div>
              <div className="kpi-delta">
                единовременно
              </div>
            </div>

            <div className="kpi">
              <div className="kpi-lbl">
                Коэффициент окупаемости
                <i className="ri-exchange-funds-line"></i>
              </div>
              <div className="kpi-val" style={{ color: result.paybackRatio >= 1 ? "var(--color-ok, #26972B)" : result.paybackRatio > 0 ? "#a04200" : undefined }}>
                {result.paybackRatio.toFixed(2)}x
              </div>
              <div className={`kpi-delta ${result.paybackRatio >= 1 ? "up" : ""}`}>
                доход / затраты
              </div>
            </div>
          </div>

          {/* Summary card */}
          <div className="card">
            <h3 className="card-title">Итог расчёта</h3>
            <div
              style={{ fontSize: 14, lineHeight: 1.8, color: "var(--fg)" }}
              dangerouslySetInnerHTML={{ __html: Keeper.roi.renderHtml(result) }}
            />
            {result.payback && (
              <div style={{
                marginTop: 12,
                padding: "10px 14px",
                background: result.paybackRatio >= 1 ? "rgba(38,151,43,.08)" : "rgba(160,66,0,.06)",
                border: `1px solid ${result.paybackRatio >= 1 ? "rgba(38,151,43,.3)" : "rgba(160,66,0,.25)"}`,
                borderRadius: 8,
                fontSize: 13,
                display: "flex",
                gap: 8,
                alignItems: "flex-start",
              }}>
                <i
                  className={result.paybackRatio >= 1 ? "ri-checkbox-circle-line" : "ri-information-line"}
                  style={{ fontSize: 16, marginTop: 1, color: result.paybackRatio >= 1 ? "#26972B" : "#a04200" }}
                ></i>
                <span>
                  {result.payback.status === "instant"
                    ? "При текущих параметрах система окупается мгновенно (нулевые затраты на внедрение)."
                    : result.paybackRatio >= 1 && paybackMonths !== null
                    ? `При текущих параметрах система окупается приблизительно за ${paybackMonths} мес.`
                    : "При текущих параметрах дополнительная выручка не перекрывает затраты на внедрение. Проверьте входные данные."}
                </span>
              </div>
            )}
          </div>

          {/* Breakdown bar */}
          {result.baselineRevenue > 0 && result.breakdown && (
            <div className="card">
              <h3 className="card-title">Структура выручки</h3>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                <div>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 4 }}>
                    <span style={{ color: "var(--fg-muted)" }}>Базовая выручка</span>
                    <b>${fmt(result.baselineRevenue)}</b>
                  </div>
                  <div style={{ height: 8, background: "var(--n-150)", borderRadius: 4, overflow: "hidden" }}>
                    <div style={{ height: "100%", width: "100%", background: "#FFB300", borderRadius: 4 }}></div>
                  </div>
                </div>
                <div>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 4 }}>
                    <span style={{ color: "var(--fg-muted)" }}>Прирост от системы</span>
                    <b style={{ color: "#26972B" }}>+${fmt(result.incrementalRevenue)}</b>
                  </div>
                  <div style={{ height: 8, background: "var(--n-150)", borderRadius: 4, overflow: "hidden" }}>
                    <div style={{
                      height: "100%",
                      width: `${result.breakdown.chart.incrementalVsBaselinePct}%`,
                      background: "linear-gradient(90deg,#26972B,#7FB539)",
                      borderRadius: 4,
                      transition: "width 300ms ease",
                    }}></div>
                  </div>
                </div>
              </div>
            </div>
          )}

        </div>
      </div>
    </div>
  );
}

window.RoiCalculator = RoiCalculator;
