"use client";

import type { SellTimeSensitivityResponse, SellTimeBucket } from "@/types/trade-in";

type Props = { data: SellTimeSensitivityResponse };

const BUCKET_LABELS: Record<string, string> = {
  cheap: "−5% от рынка",
  median: "По медиане",
  plus5: "+5%",
  plus10: "+10%",
};

const BUCKET_COLORS: Record<string, string> = {
  cheap: "var(--success-soft)",   // light green
  median: "var(--accent-soft)",   // light blue
  plus5: "var(--warn-soft)",      // light yellow
  plus10: "var(--danger-soft)",   // light red
};

function BucketCard({ bucket }: { bucket: SellTimeBucket }) {
  const hasData = bucket.median_exposure_days !== null && bucket.n_lots > 0;
  return (
    <div
      className="card"
      style={{
        padding: 12,
        flex: 1,
        minWidth: 0,
        background: BUCKET_COLORS[bucket.price_premium_label] ?? "#f9fafb",
        border:
          bucket.price_premium_label === "median"
            ? "2px solid var(--viz-1)"
            : "1px solid var(--border, #e5e7eb)",
      }}
    >
      <div style={{ fontSize: 11, color: "#374151", marginBottom: 4, fontWeight: 500 }}>
        {BUCKET_LABELS[bucket.price_premium_label]}
      </div>
      <div style={{ fontSize: 22, fontWeight: 700, lineHeight: 1.1 }}>
        {hasData ? `~${bucket.median_exposure_days} дн.` : "—"}
      </div>
      {hasData && bucket.p25_days != null && bucket.p75_days != null && (
        <div style={{ fontSize: 10, color: "#5f6570", marginTop: 4 }}>
          обычно {bucket.p25_days}–{bucket.p75_days} дн.
        </div>
      )}
      <div style={{ fontSize: 10, color: "#5f6570", marginTop: 2 }}>
        {bucket.n_lots > 0
          ? `${bucket.n_lots} аналог${bucket.n_lots === 1 ? "" : bucket.n_lots < 5 ? "а" : "ов"}`
          : "нет данных"}
      </div>
    </div>
  );
}

export function SellTimeSensitivity({ data }: Props) {
  if (data.buckets.every((b) => b.n_lots === 0)) return null;

  return (
    <article className="card" style={{ marginTop: 12, padding: 16 }}>
      <header style={{ marginBottom: 12 }}>
        <h4 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>
          Срок продажи в зависимости от цены
        </h4>
        <small style={{ color: "var(--muted, #6b7280)" }}>
          Медиана экспозиции по архивным лотам · benchmark{" "}
          {data.target_median_price_per_m2
            ? `${data.target_median_price_per_m2.toLocaleString("ru-RU")} ₽/м²`
            : "—"}
        </small>
      </header>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
        {data.buckets.map((b) => (
          <BucketCard key={b.price_premium_label} bucket={b} />
        ))}
      </div>
    </article>
  );
}
