"use client";

/**
 * HorizonForecast — 6.1 «Прогноз по горизонтам».
 *
 * Left: a demand-vs-supply line chart (inline SVG, two polylines) over
 * future_market.forecasts_by_horizon — mirrors the prototype's renderLineCharts
 * (no chart lib; the dark .chart tokens drive the look). Right: a compact
 * horizons table (горизонт · спрос · предложение · дефицит).
 */

import { useMemo } from "react";

import styles from "@/app/site-finder/analysis/[cad]/ptica/ptica.module.css";
import type { DemandSupplyForecast } from "@/types/forecast";
import { deficitTone, fmtInt, fmtSignedDeficit } from "./scenario-helpers";

interface Props {
  forecasts: DemandSupplyForecast[];
  targetHorizon: number;
  /** Segment caption (e.g. "Комфорт · 1–2К") — shown under the table when known. */
  segmentLabel: string | null;
}

const CHART_W = 600;
const CHART_H = 180;
const CHART_PAD = 28;

const DEFICIT_TONE_CLASS = {
  good: styles.numPos,
  bad: styles.numNeg,
  warn: styles.numNeg,
  neutral: "",
} as const;

interface ChartGeometry {
  gridLines: number[];
  demandPath: string;
  supplyPath: string;
  xLabels: { x: number; text: string }[];
}

function buildChart(rows: DemandSupplyForecast[]): ChartGeometry | null {
  if (rows.length < 2) return null;
  const demand = rows.map((r) => r.projected_demand_units);
  const supply = rows.map((r) => r.projected_supply_units);
  const all = [...demand, ...supply, 0];
  const min = Math.min(...all);
  const max = Math.max(...all);
  const span = max - min || 1;
  const x = (i: number, n: number) =>
    CHART_PAD + (i * (CHART_W - 2 * CHART_PAD)) / (n - 1);
  const y = (v: number) =>
    CHART_H - CHART_PAD - ((v - min) / span) * (CHART_H - 2 * CHART_PAD);
  const toPath = (arr: number[]) =>
    arr
      .map(
        (v, i) =>
          `${i ? "L" : "M"}${x(i, arr.length).toFixed(1)},${y(v).toFixed(1)}`,
      )
      .join(" ");

  const gridLines: number[] = [];
  for (let g = 0; g <= 4; g++) {
    gridLines.push(CHART_PAD + (g * (CHART_H - 2 * CHART_PAD)) / 4);
  }

  const xLabels = rows.map((r, i) => ({
    x: x(i, rows.length),
    text: `${r.horizon_months}м`,
  }));

  return {
    gridLines,
    demandPath: toPath(demand),
    supplyPath: toPath(supply),
    xLabels,
  };
}

export function HorizonForecast({
  forecasts,
  targetHorizon,
  segmentLabel,
}: Props) {
  const rows = useMemo(
    () => [...forecasts].sort((a, b) => a.horizon_months - b.horizon_months),
    [forecasts],
  );
  const chart = useMemo(() => buildChart(rows), [rows]);

  if (rows.length === 0) {
    return (
      <div className={`${styles.panel} ${styles.emptyPanel}`}>
        Прогноз по горизонтам недоступен.
      </div>
    );
  }

  return (
    <>
      <div className={styles.sectionLabel}>
        6.1 · <b>прогноз по горизонтам</b>
      </div>
      <section className={styles.forecastGrid}>
        <div className={styles.panel}>
          <div className={styles.cardHead}>
            <h3 className={styles.cardTitle}>Спрос vs предложение</h3>
            <div className={styles.legendInline}>
              <span>
                <i className={styles.legendDemand} />
                Спрос
              </span>
              <span>
                <i className={styles.legendSupply} />
                Предложение
              </span>
            </div>
          </div>
          {chart ? (
            <div className={styles.chart}>
              <svg
                viewBox={`0 0 ${CHART_W} ${CHART_H}`}
                preserveAspectRatio="none"
                role="img"
                aria-label="Прогноз спроса и предложения по горизонтам, квартир"
              >
                {chart.gridLines.map((gy, i) => (
                  <line
                    key={i}
                    className={styles.chartGrid}
                    x1={CHART_PAD}
                    y1={gy}
                    x2={CHART_W - CHART_PAD}
                    y2={gy}
                  />
                ))}
                <path className={styles.chartDemand} d={chart.demandPath} />
                <path className={styles.chartSupply} d={chart.supplyPath} />
                {chart.xLabels.map((l, i) => (
                  <text
                    key={i}
                    className={styles.chartLbl}
                    x={l.x.toFixed(1)}
                    y={CHART_H - 8}
                    textAnchor="middle"
                  >
                    {l.text}
                  </text>
                ))}
              </svg>
            </div>
          ) : (
            <div className={styles.emptyState}>
              Недостаточно точек для графика
            </div>
          )}
        </div>

        <div className={styles.panel}>
          <div className={styles.cardHead}>
            <h3 className={styles.cardTitle}>По горизонтам</h3>
          </div>
          <table className={styles.dtable}>
            <thead>
              <tr>
                <th>Горизонт</th>
                <th className={styles.thNum}>Спрос</th>
                <th className={styles.thNum}>Предлож.</th>
                <th className={styles.thNum}>Дефицит</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((f) => {
                const isTarget = f.horizon_months === targetHorizon;
                const tone = deficitTone(f.deficit_index);
                return (
                  <tr
                    key={f.horizon_months}
                    className={isTarget ? styles.rowTarget : undefined}
                  >
                    <td>
                      {f.horizon_months} мес
                      {isTarget && (
                        <span className={styles.targetTag}>целевой</span>
                      )}
                    </td>
                    <td className={styles.tdNum}>
                      {fmtInt(f.projected_demand_units)}
                    </td>
                    <td className={styles.tdNum}>
                      {fmtInt(f.projected_supply_units)}
                    </td>
                    <td
                      className={`${styles.tdNum} ${DEFICIT_TONE_CLASS[tone]}`}
                    >
                      {fmtSignedDeficit(f.deficit_index)}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {segmentLabel && (
            <div className={`${styles.scKvRow} ${styles.scKvRowSpaced}`}>
              <span className={styles.scK}>Сегмент</span>
              <span className={styles.scV}>{segmentLabel}</span>
            </div>
          )}
        </div>
      </section>
    </>
  );
}
