// Overlay 04 "ПРОДАЖИ В ДОМЕ" body for the /trade-in/v2 "МЕРА Оценка" port.
// Faithful markup port of the design's showHistory block (МЕРА Оценка.dc.html,
// lines 457-489): "История продаж в этом доме" card (house sales) +
// "ДКП-сделки на улице" card (3 KPI + dealine table + footer count).
// Data arrives via the composite `data` prop (mapHistory); the design fixtures
// are the default for unwired/storybook usage. No fetch / no local state.

import { tokens } from "./tokens";
import { history, dkpRows } from "./fixtures";
import { pluralRu } from "./mappers";
import type { HistoryData } from "./mappers";

// Shared grid templates (kept verbatim from the design column tracks).
const houseGrid = "2fr 1.4fr 1fr 1fr";

// Default presentation data (unwired usage): the existing design fixtures.
const HISTORY_FIXTURE: HistoryData = { ...history, dkpRows };

interface HistoryViewProps {
  data?: HistoryData;
}

export default function HistoryView({
  data = HISTORY_FIXTURE,
}: HistoryViewProps) {
  const showAsk = data.dkpRows.some((r) => r.ask && r.ask !== "—");
  const dkpGridCols = showAsk
    ? "2.2fr 1fr 1.3fr 1fr .9fr 2fr"
    : "2.2fr 1fr 1.3fr 1fr .9fr";
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "22px" }}>
      {/* ── История продаж в этом доме ───────────────────────────── */}
      <div
        style={{
          background: tokens.surface.w55,
          border: `1px solid ${tokens.line2}`,
          borderRadius: "8px",
          overflow: "hidden",
        }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            padding: "14px 18px",
            borderBottom: `1px solid ${tokens.lineSoft}`,
          }}
        >
          <span
            style={{
              fontSize: "12px",
              fontWeight: 600,
              letterSpacing: "1px",
              color: tokens.ink2,
            }}
          >
            История продаж в этом доме
          </span>
          <span
            style={{
              fontSize: "10px",
              letterSpacing: "1px",
              color: tokens.muted2,
            }}
          >
            {data.houseSales.length}{" "}
            {pluralRu(data.houseSales.length, ["ЛОТ", "ЛОТА", "ЛОТОВ"])}
          </span>
        </div>

        <div role="table" aria-label="История продаж в этом доме">
          <div
            role="row"
            style={{
              display: "grid",
              gridTemplateColumns: houseGrid,
              gap: "12px",
              padding: "9px 18px",
              fontSize: "9px",
              letterSpacing: "1.2px",
              // C1: primary column-header labels → body2 (above the muted rows).
              color: tokens.body2,
              borderBottom: `1px solid ${tokens.lineSoft2}`,
            }}
          >
            <span role="columnheader">ЛОТ</span>
            <span role="columnheader">ЦЕНА НАЧ. → ПОСЛ.</span>
            <span role="columnheader">ДАТА</span>
            <span role="columnheader">ЭКСПОЗИЦИЯ</span>
          </div>

          {data.houseSales.map((row, i) => (
            <div
              key={i}
              role="row"
              style={{
                display: "grid",
                gridTemplateColumns: houseGrid,
                gap: "12px",
                padding: "13px 18px",
                fontSize: "12px",
                borderBottom:
                  i < data.houseSales.length - 1
                    ? `1px solid ${tokens.lineSoft4}`
                    : undefined,
              }}
            >
              <span role="cell" style={{ color: tokens.body }}>{row.lot}</span>
              <span
                role="cell"
                style={{ fontFamily: tokens.font.mono, color: tokens.muted }}
              >
                {row.priceFrom} →{" "}
                <b style={{ color: tokens.ink2 }}>{row.priceTo}</b>
              </span>
              <span
                role="cell"
                style={{ fontFamily: tokens.font.mono, color: tokens.muted }}
              >
                {row.date}
              </span>
              <span
                role="cell"
                style={{ fontFamily: tokens.font.mono, color: tokens.muted }}
              >
                {row.exposure}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* ── ДКП-сделки на улице ──────────────────────────────────── */}
      <div
        style={{
          background: tokens.surface.w55,
          border: `1px solid ${tokens.line2}`,
          borderRadius: "8px",
          overflow: "hidden",
        }}
      >
        <div
          style={{
            padding: "14px 18px",
            borderBottom: `1px solid ${tokens.lineSoft}`,
          }}
        >
          <div
            style={{
              display: "flex",
              alignItems: "flex-start",
              justifyContent: "space-between",
            }}
          >
            <div>
              <div
                style={{
                  fontSize: "8.5px",
                  letterSpacing: "2px",
                  // C1: primary section eyebrow → body2 (ObjectSummary pattern).
                  color: tokens.body2,
                  marginBottom: "5px",
                }}
              >
                ПОХОЖИЕ КВАРТИРЫ · ПО ВАШЕЙ УЛИЦЕ
              </div>
              <div
                style={{
                  fontSize: "12px",
                  fontWeight: 600,
                  letterSpacing: ".5px",
                  color: tokens.ink2,
                }}
              >
                {data.dkpHeader.title}
              </div>
              {/* M12 — расшифровка «ДКП» один раз на секцию, тем же lowercase
                  hint-стилем что ObjectSummary.rowHint() (fontSize 8/letterSpacing
                  0.2/muted3), а не uppercase ResultPanel §M8 стилем. */}
              <div
                style={{
                  fontSize: "8px",
                  letterSpacing: 0.2,
                  color: tokens.muted3,
                  marginTop: 2,
                }}
              >
                ДКП · договор купли-продажи
              </div>
            </div>
            <div
              style={{
                textAlign: "right",
                fontSize: "9.5px",
                color: tokens.muted2,
                lineHeight: 1.6,
              }}
            >
              Период:{" "}
              <b style={{ color: tokens.muted }}>{data.dkpHeader.period}</b>
              <br />
              Источник: Росреестр + объявления
            </div>
          </div>
          <div
            style={{
              fontSize: "10px",
              color: tokens.hint,
              marginTop: "8px",
            }}
          >
            {data.dkpHeader.note}
          </div>
        </div>

        {/* KPI band */}
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(3,1fr)",
            borderBottom: `1px solid ${tokens.lineSoft}`,
            background: tokens.surfaceTint,
          }}
        >
          <div
            style={{
              padding: "12px 18px",
              borderRight: `1px solid ${tokens.lineSoft2}`,
            }}
          >
            <div
              style={{
                fontSize: "9px",
                letterSpacing: "1.5px",
                // C1: primary KPI label → body2 (above the muted value/unit).
                color: tokens.body2,
              }}
            >
              СДЕЛОК ЗА 24 МЕС
            </div>
            <div
              style={{
                fontFamily: tokens.font.mono,
                fontSize: "22px",
                fontWeight: 300,
                color: tokens.ink2,
                marginTop: "4px",
              }}
            >
              {data.dkpKpi.count}
            </div>
          </div>
          <div
            style={{
              padding: "12px 18px",
              borderRight: `1px solid ${tokens.lineSoft2}`,
            }}
          >
            <div
              style={{
                fontSize: "9px",
                letterSpacing: "1.5px",
                // C1: primary KPI label → body2 (above the muted value/unit).
                color: tokens.body2,
              }}
            >
              МЕДИАНА
            </div>
            <div
              style={{
                fontFamily: tokens.font.mono,
                fontSize: "22px",
                fontWeight: 300,
                color: tokens.ink2,
                marginTop: "4px",
              }}
            >
              {data.dkpKpi.median}{" "}
              <span style={{ fontSize: "11px", color: tokens.muted }}>
                ₽/м²
              </span>
            </div>
          </div>
          <div style={{ padding: "12px 18px" }}>
            <div
              style={{
                fontSize: "9px",
                letterSpacing: "1.5px",
                // C1: primary KPI label → body2 (above the muted value/unit).
                color: tokens.body2,
              }}
            >
              ДИАПАЗОН
            </div>
            <div
              style={{
                fontFamily: tokens.font.mono,
                fontSize: "22px",
                fontWeight: 300,
                color: tokens.accent,
                marginTop: "4px",
              }}
            >
              {data.dkpKpi.range}{" "}
              <span style={{ fontSize: "11px", color: tokens.muted }}>
                млн ₽
              </span>
            </div>
          </div>
        </div>

        {/* Table header */}
        <div role="table" aria-label="ДКП-сделки по вашей улице">
          <div
            role="row"
            style={{
              display: "grid",
              gridTemplateColumns: dkpGridCols,
              gap: "10px",
              padding: "9px 18px",
              fontSize: "9px",
              letterSpacing: "1px",
              // C1: primary column-header labels → body2 (above the muted rows).
              color: tokens.body2,
              borderBottom: `1px solid ${tokens.lineSoft2}`,
            }}
          >
            <span role="columnheader">АДРЕС</span>
            <span role="columnheader">ПЛОЩАДЬ</span>
            <span role="columnheader">ЦЕНА СДЕЛКИ</span>
            <span role="columnheader">₽/М²</span>
            <span role="columnheader">ДАТА</span>
            {showAsk && <span role="columnheader">ОБЪЯВЛЕНИЕ ДО СДЕЛКИ</span>}
          </div>

          {data.dkpRows.map((r, i) => (
            <div
              key={i}
              role="row"
              style={{
                display: "grid",
                gridTemplateColumns: dkpGridCols,
                gap: "10px",
                padding: "11px 18px",
                fontSize: "11px",
                borderBottom: `1px solid ${tokens.lineSoft3}`,
                alignItems: "center",
              }}
            >
              <span role="cell" style={{ color: tokens.body }}>
                {r.addr ?? "—"}
              </span>
              <span
                role="cell"
                style={{ fontFamily: tokens.font.mono, color: tokens.muted }}
              >
                {r.area}
              </span>
              <span
                role="cell"
                style={{ fontFamily: tokens.font.mono, color: tokens.ink2 }}
              >
                {r.price}
              </span>
              <span
                role="cell"
                style={{ fontFamily: tokens.font.mono, color: tokens.muted }}
              >
                {r.ppm}
              </span>
              <span
                role="cell"
                style={{ fontFamily: tokens.font.mono, color: tokens.muted2 }}
              >
                {r.date ?? "—"}
              </span>
              {showAsk && (
                <span
                  role="cell"
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: "7px",
                    fontFamily: tokens.font.mono,
                    fontSize: "10px",
                    color: tokens.muted,
                  }}
                >
                  <span
                    style={{
                      fontSize: "8px",
                      letterSpacing: ".5px",
                      background: tokens.badgeTint,
                      border: `1px solid ${tokens.line2}`,
                      borderRadius: "3px",
                      padding: "1px 5px",
                      // accentDeep (not accent): 8px accent on badgeTint ~2.8:1 < AA;
                      // accentDeep keeps the blue brand cue at ≈5:1.
                      color: tokens.accentDeep,
                    }}
                  >
                    {r.source ?? "—"}
                  </span>
                  {r.ask}
                  <span style={{ color: r.deltaColor }}>{r.delta}</span>
                </span>
              )}
            </div>
          ))}
        </div>

        <div
          style={{
            padding: "11px 18px",
            fontSize: "10px",
            color: tokens.hint,
            background: tokens.surfaceTint,
          }}
        >
          Показано {data.dkpRows.length} из {data.dkpKpi.count} сделок
        </div>
      </div>
    </div>
  );
}
