"use client";

import type { IMVBenchmarkResponse } from "@/types/trade-in";

interface Props {
  benchmark: IMVBenchmarkResponse | undefined;
  isLoading: boolean;
}

function formatRub(n: number | null | undefined): string {
  if (n == null) return "—";
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)} млн ₽`;
  return new Intl.NumberFormat("ru-RU").format(n) + " ₽";
}

export function IMVBenchmark({ benchmark, isLoading }: Props) {
  if (isLoading) {
    return (
      <div className="imv-benchmark imv-benchmark--loading">
        <span className="imv-benchmark__label">Avito IMV</span>
        <span className="imv-benchmark__value">загрузка…</span>
      </div>
    );
  }

  if (!benchmark || !benchmark.available) {
    return null; // нет данных от Avito — не показываем
  }

  const {
    recommended_price,
    lower_price,
    higher_price,
    market_count,
    our_median_price,
    diff_pct,
  } = benchmark;

  const diffLabel =
    diff_pct == null
      ? null
      : diff_pct > 0
        ? `выше Avito на ${diff_pct.toFixed(1)}%`
        : diff_pct < 0
          ? `ниже Avito на ${Math.abs(diff_pct).toFixed(1)}%`
          : "совпадает с Avito";

  return (
    <section className="imv-benchmark" aria-label="Avito IMV benchmark">
      <header className="imv-benchmark__head">
        <span className="imv-benchmark__title">Avito <abbr title="Information Market Value — оценка рыночной стоимости от Avito">IMV</abbr></span>
        <a
          href="https://www.avito.ru/evaluation/realty"
          target="_blank"
          rel="noopener noreferrer"
          className="imv-benchmark__source"
        >
          источник: avito.ru/evaluation/realty
        </a>
      </header>
      <div className="imv-benchmark__row">
        <div className="imv-benchmark__metric">
          <div className="imv-benchmark__metric-label">Avito рекомендует</div>
          <div className="imv-benchmark__metric-value">
            {formatRub(recommended_price)}
          </div>
        </div>
        <div className="imv-benchmark__metric">
          <div className="imv-benchmark__metric-label">Диапазон</div>
          <div className="imv-benchmark__metric-value">
            {formatRub(lower_price)} – {formatRub(higher_price)}
          </div>
        </div>
        <div className="imv-benchmark__metric">
          <div className="imv-benchmark__metric-label">Аналогов в рынке</div>
          <div className="imv-benchmark__metric-value">
            {market_count != null
              ? new Intl.NumberFormat("ru-RU").format(market_count)
              : "—"}
          </div>
        </div>
      </div>
      {our_median_price != null && diffLabel && (
        <footer className="imv-benchmark__compare">
          Наша оценка: <strong>{formatRub(our_median_price)}</strong> ({diffLabel})
        </footer>
      )}
    </section>
  );
}
