import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import { zodValidator } from "@tanstack/zod-adapter";
import {
  ArrowLeft,
  AlertTriangle,
  ArrowRight,
  CalendarDays,
  ExternalLink,
  Loader2,
  RefreshCw,
  ShieldCheck,
  Sparkles,
  Star,
  Tag,
  TrendingUp,
} from "lucide-react";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Legend,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { AppShell } from "@/components/AppShell";
import { PageHeader } from "@/components/PageHeader";
import { BriefingSkeleton } from "@/components/BriefingSkeleton";
import { Button } from "@/components/ui/button";
import { Sources } from "@/components/Sources";
import { useBriefing } from "@/hooks/useBriefing";
import { useT, useSettings } from "@/hooks/useSettings";
import {
  generateDeepDive,
  getDeepDive,
  type DeepDive,
  type DeepDiveRecord,
} from "@/lib/deepDive.functions";
import { authHeaders } from "@/lib/authHeaders";

const searchSchema = z.object({
  topic: z.enum(["industry", "competitor"]),
  subjectKey: z.string().min(1),
  title: z.string().min(1),
  context: z.string().default(""),
});

export const Route = createFileRoute("/deep-dive")({
  validateSearch: zodValidator(searchSchema),
  head: () => ({
    meta: [
      { title: "Deep Dive — The Daily Ledger" },
      {
        name: "description",
        content: "Cross-validated AI deep-dive analysis with sources, charts, and recommended moves.",
      },
    ],
  }),
  component: DeepDivePage,
});

function DeepDivePage() {
  const { topic, subjectKey, title, context } = Route.useSearch();
  const { hotel, isAllHotels, isHotelLoading, refresh } = useBriefing();
  const { lang } = useSettings();
  const t = useT();
  const navigate = useNavigate();
  const qc = useQueryClient();

  const cacheKey = ["deepDive", topic, subjectKey, lang] as const;

  const cachedQuery = useQuery<DeepDiveRecord | null>({
    queryKey: cacheKey,
    enabled: !isHotelLoading,
    queryFn: async () =>
      getDeepDive({ data: { topic, subjectKey, language: lang }, headers: await authHeaders() }),
    staleTime: 5 * 60 * 1000,
  });

  const generate = useMutation({
    mutationFn: async (refreshFlag: boolean) =>
      generateDeepDive({
        data: {
          topic,
          subjectKey,
          title,
          context,
          language: lang,
          hotelId: hotel?.id ?? null,
          refresh: refreshFlag,
        },
        headers: await authHeaders(),
      }),
    onSuccess: (record) => {
      qc.setQueryData(cacheKey, record);
    },
  });

  const record = (generate.data ?? cachedQuery.data) as DeepDiveRecord | null;
  const data: DeepDive | null = record?.payload ?? null;

  const isInitialLoading = cachedQuery.isLoading;
  const isWorking = generate.isPending;
  const error = (generate.error as Error | null) ?? (cachedQuery.error as Error | null);

  if (isHotelLoading) {
    return (
      <div className="flex min-h-dvh items-center justify-center">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  const backTo = topic === "industry" ? "/industry" : "/competitors";

  return (
    <AppShell hotel={hotel ?? null} isLoading={false} onRefresh={refresh}>
      <PageHeader
        eyebrow={t("common.deepDive")}
        title={title}
        subtitle={t("deepDive.subtitle")}
      >
        <Button
          size="sm"
          variant="ghost"
          onClick={() => navigate({ to: backTo })}
          className="text-muted-foreground"
        >
          <ArrowLeft className="mr-1.5 h-3.5 w-3.5" />
          {t("deepDive.back")}
        </Button>
      </PageHeader>

      {isAllHotels || !hotel ? (
        <div className="rounded-2xl border bg-card p-6 text-sm text-muted-foreground">
          {t("deepDive.selectHotel")}
        </div>
      ) : isInitialLoading ? (
        <BriefingSkeleton />
      ) : !data ? (
        <EmptyState
          working={isWorking}
          error={error}
          onGenerate={() => generate.mutate(false)}
        />
      ) : (
        <div className="space-y-6">
          {/* Hero */}
          <article className="overflow-hidden rounded-2xl border bg-card shadow-[var(--shadow-elegant)]">
            {record?.cover_image ? (
              <div className="relative aspect-[16/7] w-full overflow-hidden bg-muted">
                <img
                  src={record.cover_image}
                  alt={title}
                  className="h-full w-full object-cover"
                  loading="lazy"
                />
              </div>
            ) : null}
            <div className="p-5 sm:p-8">
              <div className="flex flex-wrap items-center justify-between gap-3">
                <div className="inline-flex items-center gap-2 text-xs uppercase tracking-[0.18em] text-accent">
                  <Sparkles className="h-3.5 w-3.5" />
                  {topic === "industry" ? t("deepDive.industryEyebrow") : t("deepDive.competitorEyebrow")}
                </div>
                <div className="flex items-center gap-2">
                  {record?.generated_at ? (
                    <span className="text-[11px] text-muted-foreground">
                      {t("deepDive.generated")} {new Date(record.generated_at).toLocaleString()}
                    </span>
                  ) : null}
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => generate.mutate(true)}
                    disabled={isWorking}
                  >
                    <RefreshCw className={`mr-1.5 h-3.5 w-3.5 ${isWorking ? "animate-spin" : ""}`} />
                    {isWorking ? t("deepDive.refreshing") : t("deepDive.refresh")}
                  </Button>
                </div>
              </div>
              <p className="mt-4 font-serif text-lg italic leading-relaxed text-foreground sm:text-xl">
                {data.summary}
              </p>
            </div>
          </article>

          {error ? (
            <div className="rounded-xl border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">
              {(error as Error).message}
            </div>
          ) : null}

          {/* Property profile from context (competitor topic only) */}
          {topic === "competitor" && context ? (
            <PropertyProfile context={context} />
          ) : null}

          {/* Charts */}
          <MetricsCharts metrics={data.metrics} />

          {data.ratings && data.ratings.length > 0 ? <RatingsGrid ratings={data.ratings} /> : null}
          {data.occupancy_breakdown && data.occupancy_breakdown.length > 0 ? (
            <OccupancyBreakdown points={data.occupancy_breakdown} />
          ) : null}
          {data.ota_pricing && data.ota_pricing.length > 0 ? (
            <OtaPricingTable rows={data.ota_pricing} />
          ) : null}
          {data.events && data.events.length > 0 ? <EventsList events={data.events} /> : null}

          {/* Findings */}
          <Section icon={<TrendingUp className="h-3.5 w-3.5" />} title={t("deepDive.keyFindings")}>
            <BulletList items={data.key_findings} />
          </Section>

          <div className="grid gap-4 sm:grid-cols-2">
            <Section
              icon={<TrendingUp className="h-3.5 w-3.5 text-emerald-700" />}
              title={t("deepDive.opportunities")}
              tone="good"
            >
              <BulletList items={data.opportunities} />
            </Section>
            <Section
              icon={<AlertTriangle className="h-3.5 w-3.5 text-destructive" />}
              title={t("deepDive.risks")}
              tone="warn"
            >
              <BulletList items={data.risks} />
            </Section>
          </div>

          <Section icon={<ArrowRight className="h-3.5 w-3.5 text-brand" />} title={t("deepDive.moves")}>
            <ol className="space-y-2">
              {data.recommended_moves.map((m, i) => (
                <li key={i} className="flex gap-3 text-sm text-foreground">
                  <span className="mt-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-brand text-[11px] font-medium text-primary-foreground">
                    {i + 1}
                  </span>
                  <span className="leading-relaxed">{m}</span>
                </li>
              ))}
            </ol>
          </Section>

          <div className="rounded-xl border border-accent/30 bg-accent/5 p-4 text-xs leading-relaxed text-foreground">
            <div className="mb-1 inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wider text-accent">
              <ShieldCheck className="h-3 w-3" /> {t("deepDive.crossValidated")}
            </div>
            <p>{data.cross_validation_note}</p>
          </div>

          <Sources items={data.sources} label={t("common.backedBy")} />
        </div>
      )}
    </AppShell>
  );
}

function EmptyState({
  working,
  error,
  onGenerate,
}: {
  working: boolean;
  error: Error | null;
  onGenerate: () => void;
}) {
  const t = useT();
  return (
    <div className="rounded-2xl border bg-card p-8 text-center shadow-[var(--shadow-elegant)]">
      <Sparkles className="mx-auto h-6 w-6 text-brand" />
      <h2 className="mt-3 font-serif text-xl text-foreground">{t("deepDive.notYet.title")}</h2>
      <p className="mx-auto mt-1 max-w-md text-sm text-muted-foreground">
        {t("deepDive.notYet.body")}
      </p>
      {error ? (
        <p className="mx-auto mt-3 max-w-md text-xs text-destructive">{error.message}</p>
      ) : null}
      <Button className="mt-5" onClick={onGenerate} disabled={working}>
        {working ? (
          <>
            <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
            {t("deepDive.loading")}
          </>
        ) : (
          <>
            <Sparkles className="mr-1.5 h-3.5 w-3.5" />
            {t("deepDive.generate")}
          </>
        )}
      </Button>
    </div>
  );
}

function MetricsCharts({ metrics }: { metrics: DeepDive["metrics"] }) {
  const t = useT();
  const kpiData = metrics.kpis.map((k) => ({
    label: k.label,
    value: k.value,
    benchmark: k.benchmark ?? null,
  }));
  const hasBenchmark = metrics.kpis.some((k) => typeof k.benchmark === "number");
  const hasTrend = metrics.trend && metrics.trend.length > 1;

  return (
    <div className="grid gap-4 lg:grid-cols-2">
      <div className="rounded-xl border bg-card p-4">
        <div className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
          {metrics.chart_title}
        </div>
        <div className="h-56 w-full">
          <ResponsiveContainer width="100%" height="100%">
            <BarChart data={kpiData} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
              <XAxis dataKey="label" tick={{ fontSize: 11 }} interval={0} />
              <YAxis tick={{ fontSize: 11 }} />
              <Tooltip
                contentStyle={{
                  background: "hsl(var(--card))",
                  border: "1px solid hsl(var(--border))",
                  borderRadius: 8,
                  fontSize: 12,
                }}
              />
              <Legend wrapperStyle={{ fontSize: 11 }} />
              <Bar dataKey="value" name={t("deepDive.subject")} fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} />
              {hasBenchmark ? (
                <Bar dataKey="benchmark" name={t("deepDive.benchmark")} fill="hsl(var(--accent))" radius={[4, 4, 0, 0]} />
              ) : null}
            </BarChart>
          </ResponsiveContainer>
        </div>
        <ul className="mt-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-3">
          {metrics.kpis.map((k, i) => (
            <li key={i} className="rounded-md bg-muted/40 px-2 py-1.5">
              <div className="text-[10px] uppercase tracking-wider text-muted-foreground">{k.label}</div>
              <div className="font-serif text-base font-medium text-brand">
                {k.value.toLocaleString()}
                {k.unit ? <span className="ml-0.5 text-[11px] text-muted-foreground">{k.unit}</span> : null}
              </div>
            </li>
          ))}
        </ul>
      </div>

      {hasTrend ? (
        <div className="rounded-xl border bg-card p-4">
          <div className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
            {metrics.trend_label || t("deepDive.trend")}
          </div>
          <div className="h-56 w-full">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={metrics.trend} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                <XAxis dataKey="period" tick={{ fontSize: 11 }} />
                <YAxis tick={{ fontSize: 11 }} />
                <Tooltip
                  contentStyle={{
                    background: "hsl(var(--card))",
                    border: "1px solid hsl(var(--border))",
                    borderRadius: 8,
                    fontSize: 12,
                  }}
                />
                <Line
                  type="monotone"
                  dataKey="value"
                  stroke="hsl(var(--primary))"
                  strokeWidth={2}
                  dot={{ r: 3 }}
                />
              </LineChart>
            </ResponsiveContainer>
          </div>
        </div>
      ) : null}
    </div>
  );
}

function Section({
  icon,
  title,
  children,
  tone,
}: {
  icon: React.ReactNode;
  title: string;
  children: React.ReactNode;
  tone?: "good" | "warn";
}) {
  const cls =
    tone === "good"
      ? "border-emerald-500/30 bg-emerald-500/5"
      : tone === "warn"
        ? "border-amber-500/30 bg-amber-500/5"
        : "border-border bg-card";
  return (
    <div className={`rounded-xl border p-4 ${cls}`}>
      <div className="mb-2 inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
        {icon}
        {title}
      </div>
      {children}
    </div>
  );
}

function BulletList({ items }: { items: string[] }) {
  return (
    <ul className="space-y-1.5 text-sm leading-relaxed text-foreground">
      {items.map((x, i) => (
        <li key={i} className="flex gap-2">
          <span className="mt-2 h-1 w-1 shrink-0 rounded-full bg-foreground/40" />
          <span>{x}</span>
        </li>
      ))}
    </ul>
  );
}

function RatingsGrid({ ratings }: { ratings: NonNullable<DeepDive["ratings"]> }) {
  const t = useT();
  return (
    <div className="rounded-xl border bg-card p-4">
      <div className="mb-3 inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
        <Star className="h-3.5 w-3.5 text-amber-500" />
        {t("deepDive.ratings") || "Ratings"}
      </div>
      <ul className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
        {ratings.map((r, i) => {
          const pct = Math.max(0, Math.min(100, (r.score / (r.scale || 5)) * 100));
          const Wrap: React.ElementType = r.url ? "a" : "div";
          const wrapProps = r.url ? { href: r.url, target: "_blank", rel: "noopener noreferrer" } : {};
          return (
            <li key={i}>
              <Wrap
                {...wrapProps}
                className="block rounded-lg border bg-background/60 p-3 transition-colors hover:bg-muted/60"
              >
                <div className="flex items-center justify-between">
                  <span className="text-xs font-medium text-foreground">{r.platform}</span>
                  {r.url ? <ExternalLink className="h-3 w-3 opacity-60" /> : null}
                </div>
                <div className="mt-1 flex items-baseline gap-1">
                  <span className="font-serif text-2xl font-medium text-brand">{r.score}</span>
                  <span className="text-[10px] text-muted-foreground">/ {r.scale}</span>
                </div>
                <div className="mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-muted">
                  <div className="h-full rounded-full bg-amber-500" style={{ width: `${pct}%` }} />
                </div>
                <div className="mt-1.5 flex flex-wrap items-center gap-x-2 text-[10px] uppercase tracking-wider text-muted-foreground">
                  {typeof r.reviews === "number" ? <span>{r.reviews.toLocaleString()} reviews</span> : null}
                  {r.trend ? <span className="text-emerald-700 normal-case tracking-normal">{r.trend}</span> : null}
                </div>
              </Wrap>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

function OccupancyBreakdown({
  points,
}: {
  points: NonNullable<DeepDive["occupancy_breakdown"]>;
}) {
  const t = useT();
  return (
    <div className="rounded-xl border bg-card p-4">
      <div className="mb-3 inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
        <TrendingUp className="h-3.5 w-3.5" />
        {t("deepDive.occupancyBreakdown") || "Occupancy breakdown"}
      </div>
      <ul className="space-y-2">
        {points.map((p, i) => {
          const pct = Math.max(0, Math.min(100, p.occupancy_pct));
          const tone = pct >= 80 ? "bg-emerald-500" : pct >= 60 ? "bg-brand" : pct >= 40 ? "bg-amber-500" : "bg-destructive";
          return (
            <li key={i} className="flex items-center gap-3">
              <span className="w-24 shrink-0 text-xs text-muted-foreground">{p.period}</span>
              <div className="relative h-5 flex-1 overflow-hidden rounded-md bg-muted">
                <div className={`h-full ${tone}`} style={{ width: `${pct}%` }} />
                <span className="absolute inset-0 flex items-center pl-2 text-[11px] font-medium text-foreground">
                  {pct.toFixed(0)}%
                </span>
              </div>
              {p.note ? (
                <span className="hidden flex-1 text-[11px] text-muted-foreground sm:block">{p.note}</span>
              ) : null}
            </li>
          );
        })}
      </ul>
    </div>
  );
}

function OtaPricingTable({ rows }: { rows: NonNullable<DeepDive["ota_pricing"]> }) {
  const t = useT();
  // Group by check_in date for clearer reading
  const grouped = rows.reduce<Record<string, typeof rows>>((acc, r) => {
    const k = r.check_in;
    (acc[k] ||= []).push(r);
    return acc;
  }, {});
  // Determine cheapest per group for highlight
  const cheapestByDate: Record<string, number> = {};
  Object.entries(grouped).forEach(([k, list]) => {
    cheapestByDate[k] = Math.min(...list.map((x) => x.price));
  });

  return (
    <div className="rounded-xl border bg-card p-4">
      <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
        <div className="inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
          <Tag className="h-3.5 w-3.5" />
          {t("deepDive.otaPricing") || "OTA pricing snapshot"}
        </div>
        <span className="text-[10px] text-muted-foreground">
          {rows.length} rows • {Object.keys(grouped).length} dates
        </span>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full min-w-[640px] text-xs">
          <thead className="text-left text-[10px] uppercase tracking-wider text-muted-foreground">
            <tr className="border-b">
              <th className="py-2 pr-2">Check-in</th>
              <th className="py-2 pr-2">OTA</th>
              <th className="py-2 pr-2">Room type</th>
              <th className="py-2 pr-2 text-right">Price / night</th>
              <th className="py-2 pr-2">Availability</th>
              <th className="py-2 pr-2">Notes</th>
            </tr>
          </thead>
          <tbody>
            {Object.entries(grouped).map(([date, list]) =>
              list
                .sort((a, b) => a.price - b.price)
                .map((r, i) => {
                  const isCheapest = r.price === cheapestByDate[date];
                  return (
                    <tr key={`${date}-${i}`} className="border-b last:border-0">
                      <td className="py-2 pr-2 text-foreground">{i === 0 ? date : ""}</td>
                      <td className="py-2 pr-2 font-medium text-foreground">{r.ota}</td>
                      <td className="py-2 pr-2 text-muted-foreground">{r.room_type}</td>
                      <td className="py-2 pr-2 text-right font-serif">
                        <span className={isCheapest ? "font-medium text-emerald-700" : "text-foreground"}>
                          {(r.currency || "MYR")} {r.price.toLocaleString()}
                        </span>
                        {isCheapest ? (
                          <span className="ml-1 inline-flex items-center rounded-full bg-emerald-500/15 px-1.5 py-px text-[9px] font-semibold uppercase tracking-wider text-emerald-700">
                            best
                          </span>
                        ) : null}
                      </td>
                      <td className="py-2 pr-2 text-muted-foreground">{r.availability ?? "—"}</td>
                      <td className="py-2 pr-2 text-muted-foreground">{r.notes ?? ""}</td>
                    </tr>
                  );
                }),
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function EventsList({ events }: { events: NonNullable<DeepDive["events"]> }) {
  const t = useT();
  const impactStyle: Record<string, string> = {
    high: "border-destructive/40 bg-destructive/5 text-destructive",
    medium: "border-amber-500/40 bg-amber-500/10 text-amber-700",
    low: "border-border bg-muted/40 text-muted-foreground",
  };
  return (
    <div className="rounded-xl border bg-card p-4">
      <div className="mb-3 inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
        <CalendarDays className="h-3.5 w-3.5" />
        {t("deepDive.events") || "Events & campaigns"}
      </div>
      <ul className="space-y-3">
        {events.map((e, i) => {
          const dateRange = e.end_date && e.end_date !== e.start_date ? `${e.start_date} → ${e.end_date}` : e.start_date;
          return (
            <li key={i} className="rounded-lg border bg-background/60 p-3">
              <div className="flex flex-wrap items-start justify-between gap-2">
                <div className="min-w-0 flex-1">
                  <div className="flex flex-wrap items-center gap-2">
                    <h4 className="font-serif text-sm font-medium leading-snug text-foreground">{e.name}</h4>
                    <span
                      className={`inline-flex items-center rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wider ${impactStyle[e.impact_level] ?? impactStyle.medium}`}
                    >
                      {e.impact_level} impact
                    </span>
                    {e.category ? (
                      <span className="rounded-full bg-muted px-1.5 py-0.5 text-[9px] uppercase tracking-wider text-muted-foreground">
                        {e.category}
                      </span>
                    ) : null}
                  </div>
                  <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">
                    <span className="inline-flex items-center gap-1">
                      <CalendarDays className="h-3 w-3" />
                      {dateRange}
                    </span>
                    {e.venue ? <span>{e.venue}</span> : null}
                    {typeof e.expected_attendance === "number" ? (
                      <span>{e.expected_attendance.toLocaleString()} attendees</span>
                    ) : null}
                  </div>
                </div>
                {e.url ? (
                  <a
                    href={e.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1 text-[11px] text-brand hover:underline"
                  >
                    Source <ExternalLink className="h-3 w-3" />
                  </a>
                ) : null}
              </div>
              <div className="mt-2 grid gap-2 sm:grid-cols-2">
                <div className="rounded-md bg-muted/40 p-2">
                  <div className="text-[9px] font-medium uppercase tracking-wider text-muted-foreground">
                    Predicted market effect
                  </div>
                  <p className="mt-0.5 text-xs leading-relaxed text-foreground">{e.predicted_effect}</p>
                </div>
                <div className="rounded-md bg-brand-soft/40 p-2">
                  <div className="text-[9px] font-medium uppercase tracking-wider text-brand">
                    Effect to us — move
                  </div>
                  <p className="mt-0.5 text-xs leading-relaxed text-foreground">{e.effect_to_us}</p>
                </div>
              </div>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

function PropertyProfile({ context }: { context: string }) {
  // Parse "Key: value" lines from the context blob built in competitors.tsx
  const lines = context.split("\n").map((l) => l.trim()).filter(Boolean);
  const fields: { label: string; value: string }[] = [];
  for (const line of lines) {
    const idx = line.indexOf(":");
    if (idx < 1) continue;
    const label = line.slice(0, idx).trim();
    const value = line.slice(idx + 1).trim();
    if (!value) continue;
    fields.push({ label, value });
  }
  if (fields.length === 0) return null;
  return (
    <div className="rounded-xl border bg-card p-4 sm:p-5">
      <div className="mb-3 inline-flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
        <Star className="h-3.5 w-3.5 text-amber-500" />
        Property snapshot
      </div>
      <dl className="grid gap-x-6 gap-y-3 sm:grid-cols-2">
        {fields.map((f, i) => (
          <div key={i} className="min-w-0">
            <dt className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
              {f.label}
            </dt>
            <dd className="mt-0.5 text-sm leading-relaxed text-foreground break-words">
              {f.value}
            </dd>
          </div>
        ))}
      </dl>
    </div>
  );
}
