import {
  BoltIcon,
  SunIcon,
  Squares2X2Icon,
  SparklesIcon,
} from "@heroicons/react/24/outline";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/shadcn_components/ui/card";
import { Separator } from "@/app/shadcn_components/ui/separator";
import { formatDateTime } from "@/app/utils";
import {
  formatRetrofitFeatures,
  formatGeneralFeatures,
  getNonIntrusiveSurvey,
  getPropertyMeta,
  getConditionReport,
  getSpatialData,
} from "../utils";
import { getSolarData, getSolarScenarioData } from "../solar-analysis/utils";
import PropertyMapWrapper from "../solar-analysis/PropertyMapWrapper";
import SolarSimulationWrapper from "../solar-analysis/SolarSimulationWrapper";
import { CurrentEfficiencyCard } from "@/app/components/building-passport/CurrentEfficiencyCard";

// ── Helpers ────────────────────────────────────────────────────────────────────

function getDirectionLabel(az: number): { label: string; short: string } {
  const norm = ((az % 360) + 360) % 360;
  if (norm >= 337.5 || norm < 22.5)  return { short: "N",  label: "North" };
  if (norm < 67.5)                   return { short: "NE", label: "North-East" };
  if (norm < 112.5)                  return { short: "E",  label: "East" };
  if (norm < 157.5)                  return { short: "SE", label: "South-East" };
  if (norm < 202.5)                  return { short: "S",  label: "South" };
  if (norm < 247.5)                  return { short: "SW", label: "South-West" };
  if (norm < 292.5)                  return { short: "W",  label: "West" };
  return                               { short: "NW", label: "North-West" };
}

function getRatingClasses(rating: string): string {
  switch (rating) {
    case "Very good": return "bg-green-600 text-white";
    case "Good":      return "bg-green-100 text-green-800";
    case "Poor":      return "bg-surface-container text-on-surface-variant";
    case "Very poor": return "bg-error-container text-error";
    default:          return "bg-gray-100 text-gray-400";
  }
}

function formatDate(date: Date): string {
  return new Date(date).toLocaleDateString("en-GB", {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
  });
}

const SEGMENT_THEMES: Record<string, {
  gradient: string;
  border: string;
  badge: string;
  label: string;
  dot: string;
}> = {
  S:  { gradient: "from-amber-50  to-orange-50/60", border: "border-amber-200/80",  badge: "bg-amber-100  text-amber-800  border-amber-300",  label: "text-amber-900",  dot: "bg-amber-400"  },
  SE: { gradient: "from-orange-50 to-amber-50/60",  border: "border-orange-200/80", badge: "bg-orange-100 text-orange-800 border-orange-300", label: "text-orange-900", dot: "bg-orange-400" },
  SW: { gradient: "from-orange-50 to-amber-50/60",  border: "border-orange-200/80", badge: "bg-orange-100 text-orange-800 border-orange-300", label: "text-orange-900", dot: "bg-orange-400" },
  E:  { gradient: "from-sky-50    to-blue-50/40",   border: "border-sky-200/80",    badge: "bg-sky-100    text-sky-800    border-sky-300",    label: "text-sky-900",    dot: "bg-sky-400"    },
  W:  { gradient: "from-sky-50    to-blue-50/40",   border: "border-sky-200/80",    badge: "bg-sky-100    text-sky-800    border-sky-300",    label: "text-sky-900",    dot: "bg-sky-400"    },
  N:  { gradient: "from-slate-50  to-gray-50/40",   border: "border-slate-200/80",  badge: "bg-slate-100  text-slate-700  border-slate-300",  label: "text-slate-800",  dot: "bg-slate-400"  },
  NE: { gradient: "from-slate-50  to-gray-50/40",   border: "border-slate-200/80",  badge: "bg-slate-100  text-slate-700  border-slate-300",  label: "text-slate-800",  dot: "bg-slate-400"  },
  NW: { gradient: "from-slate-50  to-gray-50/40",   border: "border-slate-200/80",  badge: "bg-slate-100  text-slate-700  border-slate-300",  label: "text-slate-800",  dot: "bg-slate-400"  },
};

// ── Sub-components ─────────────────────────────────────────────────────────────

function RoofSegmentCard({
  index,
  azimuthDegrees,
  pitchDegrees,
  areaMeters2,
  groundAreaMeters2,
  sunshineQuantiles,
  planeHeightAtCenterMeters,
}: {
  index: number;
  azimuthDegrees: number;
  pitchDegrees: number;
  areaMeters2: number;
  groundAreaMeters2: number;
  sunshineQuantiles: number[];
  planeHeightAtCenterMeters: number;
}) {
  const dir = getDirectionLabel(azimuthDegrees);
  const theme = SEGMENT_THEMES[dir.short] ?? SEGMENT_THEMES["N"];
  const medianSunshine = sunshineQuantiles?.[4] ?? null;
  const peakSunshine = sunshineQuantiles?.[8] ?? null;

  return (
    <div className={`rounded-2xl border bg-gradient-to-br ${theme.gradient} ${theme.border} shadow-sm overflow-hidden`}>
      <div className="px-5 pt-5 pb-4">
        <div className="flex items-start justify-between mb-3">
          <div>
            <p className="text-[10px] font-bold uppercase tracking-widest text-gray-400 mb-1">
              Segment {index + 1}
            </p>
            <h3 className={`text-lg font-bold leading-tight ${theme.label}`}>
              {dir.label}
            </h3>
          </div>
          <div className={`flex items-center gap-1 text-xs font-bold px-2.5 py-1 rounded-full border ${theme.badge}`}>
            <span className={`w-1.5 h-1.5 rounded-full ${theme.dot}`} />
            {dir.short}
          </div>
        </div>
        {medianSunshine !== null && (
          <div className="mt-3">
            <div className="flex items-center justify-between text-[10px] text-gray-400 mb-1">
              <span>Median sunshine</span>
              <span className="font-semibold text-gray-600">{Math.round(medianSunshine)} hrs/yr</span>
            </div>
            <div className="h-1.5 bg-white/60 rounded-full overflow-hidden">
              <div
                className={`h-full rounded-full ${theme.dot} opacity-70`}
                style={{ width: `${Math.min(100, (medianSunshine / 1600) * 100)}%` }}
              />
            </div>
          </div>
        )}
      </div>
      <Separator className="opacity-30" />
      <dl className="grid grid-cols-2 gap-px bg-black/5 text-sm">
        {[
          { label: "Roof area",   value: `${areaMeters2.toFixed(1)} m²` },
          { label: "Ground area", value: `${groundAreaMeters2.toFixed(1)} m²` },
          { label: "Pitch",       value: `${pitchDegrees.toFixed(1)}°` },
          { label: "Azimuth",     value: `${azimuthDegrees.toFixed(1)}°` },
          { label: "Height",      value: `${planeHeightAtCenterMeters.toFixed(1)} m` },
          peakSunshine !== null
            ? { label: "Peak (P90)", value: `${Math.round(peakSunshine)} hrs` }
            : { label: "", value: "" },
        ].map(({ label, value }, i) =>
          label ? (
            <div key={i} className="bg-white/40 px-4 py-3 hover:bg-white/60 transition-colors">
              <dt className="text-[10px] uppercase tracking-wide text-gray-400 font-medium mb-0.5">{label}</dt>
              <dd className="font-semibold text-gray-700 tabular-nums">{value}</dd>
            </div>
          ) : (
            <div key={i} className="bg-white/20" />
          )
        )}
      </dl>
    </div>
  );
}

// ── Page ───────────────────────────────────────────────────────────────────────

export default async function PreAssessmentReport(props: {
  params: Promise<{ slug: string; propertyId: string }>;
}) {
  const params = await props.params;
  const propertyMeta = await getPropertyMeta(params.propertyId);
  const conditionReport = await getConditionReport(params.propertyId);
  const spatial = await getSpatialData(Number(propertyMeta.uprn));
  const nonIntrusiveSurvey = await getNonIntrusiveSurvey(propertyMeta.uprn);

  if (conditionReport.totalFloorArea == null) {
    console.error("Total floor area is missing");
    return null;
  }

  const retrofitFeatures = formatRetrofitFeatures(conditionReport);
  const fundamentalDetails = [
    { feature: "Property type", description: propertyMeta.propertyType ?? "Unknown" },
    { feature: "Built form",    description: propertyMeta.builtForm ?? "Unknown" },
    { feature: "Floor area",    description: conditionReport.totalFloorArea != null ? `${Math.round(conditionReport.totalFloorArea)} m²` : "Unknown" },
    { feature: "Age",           description: propertyMeta.yearBuilt != null ? String(propertyMeta.yearBuilt) : "Unknown" },
  ];
  const generalFeatures = [
    ...fundamentalDetails,
    ...formatGeneralFeatures(conditionReport, propertyMeta.propertyType)
      .filter((f) => !["Mains gas", "Year built", "Property type", "Floor area", "Habitable rooms"].includes(f.feature))
      .slice(0, 4),
  ];

  const rawSolar = await getSolarData(Number(propertyMeta.uprn));
  const solarData = rawSolar ?? null;

  // Solar derived values
  const sp = solarData?.googleApiResponse?.solarPotential ?? null;
  const solarScenarioData = solarData ? await getSolarScenarioData(String(solarData.id)) : null;

  const maxAnnualKwh = sp
    ? Math.round(sp.solarPanelConfigs[sp.solarPanelConfigs.length - 1].yearlyEnergyDcKwh)
    : 0;
  const roofSegmentStats: any[] = sp?.roofSegmentStats ?? [];

  const lat = solarData?.googleApiResponse?.center?.latitude ?? spatial?.latitude ?? 0;
  const lng = solarData?.googleApiResponse?.center?.longitude ?? spatial?.longitude ?? 0;

  const imageryQuality = solarData?.googleApiResponse?.imageryQuality ?? null;
  const imageryDate = solarData?.googleApiResponse?.imageryDate ?? null;
  const imageryDateStr = imageryDate
    ? `${imageryDate.year}-${String(imageryDate.month).padStart(2, "0")}-${String(imageryDate.day).padStart(2, "0")}`
    : null;

  const qualityColors: Record<string, string> = {
    HIGH:   "bg-emerald-50 text-emerald-700 border-emerald-200",
    MEDIUM: "bg-amber-50 text-amber-700 border-amber-200",
    LOW:    "bg-gray-50 text-gray-600 border-gray-200",
  };
  const qualityBadge = imageryQuality ? (qualityColors[imageryQuality] ?? qualityColors.LOW) : "";
  const qualityText = imageryQuality === "HIGH" ? "High quality"
    : imageryQuality === "MEDIUM" ? "Medium quality"
    : "Base quality";

  return (
    <div className="max-w-7xl mx-auto py-10 space-y-8">

      {/* ── Page Header ─────────────────────────────────────────────────────── */}
      <header className="flex items-end justify-between">
        <div>
          <p className="font-manrope text-xs font-bold text-brandmidblue uppercase tracking-widest mb-2">
            Structural Analysis
          </p>
          <h1 className="font-manrope font-extrabold text-4xl text-brandblue tracking-tighter">
            Property Details
          </h1>
        </div>
        <p className="text-sm text-gray-400 font-medium">
          Last updated: {formatDateTime(propertyMeta.updatedAt)}
        </p>
      </header>

      {/* ── Row 1: EPC hero + energy metrics + general features ──────────── */}
      <div className="grid grid-cols-12 gap-6 items-stretch">

        {/* EPC Hero — matches overview page style */}
        <CurrentEfficiencyCard
          epcRating={propertyMeta.currentEpcRating ?? null}
          sapPoints={propertyMeta.currentSapPoints ?? 0}
          provenanceSignal={propertyMeta.provenanceSignal}
          lodgedEpcRating={propertyMeta.lodgedEpcRating}
          lodgedSapPoints={propertyMeta.lodgedSapPoints}
          originalSapPoints={propertyMeta.originalSapPoints}
        />

        {/* Right column: 3 metric cards + general features grid */}
        <div className="col-span-12 lg:col-span-7 flex flex-col gap-6">
          <div className="grid grid-cols-3 gap-6">
            <div className="bg-white border border-gray-100 p-7 rounded-2xl flex flex-col justify-between shadow-sm">
              <p className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-4">
                Energy Demand
              </p>
              <div>
                <p className="text-3xl font-black font-manrope text-brandblue">
                  {conditionReport.currentEnergyDemand != null
                    ? Number(conditionReport.currentEnergyDemand).toFixed(0)
                    : "—"}
                </p>
                <p className="text-sm font-medium text-gray-400 mt-1">kWh / year</p>
              </div>
            </div>
            <div className="bg-white border border-gray-100 p-7 rounded-2xl flex flex-col justify-between shadow-sm">
              <p className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-4">
                CO₂ Emissions
              </p>
              <div>
                <p className="text-3xl font-black font-manrope text-brandblue">
                  {conditionReport.co2Emissions ?? "—"}
                </p>
                <p className="text-sm font-medium text-gray-400 mt-1">tonnes / year</p>
              </div>
            </div>
            <div className="bg-white border border-gray-100 p-7 rounded-2xl flex flex-col justify-between shadow-sm">
              <p className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-4">
                Primary Energy
              </p>
              <div>
                <p className="text-3xl font-black font-manrope text-brandblue">
                  {conditionReport.primaryEnergyConsumption ?? "—"}
                </p>
                <p className="text-sm font-medium text-gray-400 mt-1">kWh / m² / year</p>
              </div>
            </div>
          </div>

          {/* General features grid — fills remaining height */}
          {generalFeatures.length > 0 && (
            <div className="flex-1 bg-white rounded-2xl p-6 shadow-sm border border-gray-100 flex flex-col">
              <p className="font-manrope text-xs font-bold text-brandmidblue uppercase tracking-widest mb-4">
                General Features
              </p>
              <div className="grid grid-cols-2 gap-3 flex-1">
                {generalFeatures.map((f) => {
                  const desc = String(f.description ?? "");
                  const isUnknown = desc === "Unknown" || desc === "";
                  return (
                    <div
                      key={f.feature}
                      className="bg-gray-50 rounded-xl px-4 py-3 flex flex-col justify-between"
                    >
                      <p className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1">
                        {f.feature}
                      </p>
                      <p className={`text-sm font-semibold ${isUnknown ? "text-gray-300 italic" : "text-brandblue"}`}>
                        {isUnknown ? "Unknown" : desc}
                      </p>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </div>

      {/* ── Row 2: Fabric table (full width) ─────────────────────────────────── */}
      <section className="bg-white rounded-2xl p-10 shadow-sm border border-gray-100">
        <h2 className="font-manrope font-bold text-xl text-brandblue mb-8">
          Existing Infrastructure Details
        </h2>
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="text-[10px] font-bold text-gray-400 uppercase tracking-widest border-b border-gray-100">
                <th className="pb-4 pr-4 w-40">Feature</th>
                <th className="pb-4 px-4">Description</th>
                <th className="pb-4 pl-4 text-right w-28">Rating</th>
              </tr>
            </thead>
            <tbody className="text-sm">
              {retrofitFeatures.map((f) => (
                <tr key={f.feature} className="hover:bg-gray-50 transition-colors">
                  <td className="py-4 pr-4 font-bold text-brandblue whitespace-nowrap">
                    {f.feature}
                  </td>
                  <td className="py-4 px-4 text-gray-500 font-medium">{f.description}</td>
                  <td className="py-4 pl-4 text-right whitespace-nowrap">
                    <span className={`px-3 py-1 rounded-full font-bold text-[10px] uppercase tracking-wider ${getRatingClasses(f.rating)}`}>
                      {f.rating}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>

      {/* ── Row 3: Non-Intrusive Survey ──────────────────────────────────────── */}
      {nonIntrusiveSurvey && (
        <section className="bg-white rounded-2xl p-10 shadow-sm border border-gray-100">
          <div className="flex flex-wrap items-end justify-between gap-4 mb-8">
            <h2 className="font-manrope font-bold text-xl text-brandblue">
              Non-Intrusive Survey
            </h2>
            <p className="text-sm text-gray-400">
              Conducted by{" "}
              <span className="font-semibold text-gray-600">{nonIntrusiveSurvey.surveyor}</span>
              {" "}on {formatDate(nonIntrusiveSurvey.surveyDate)}
            </p>
          </div>
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="text-[10px] font-bold text-gray-400 uppercase tracking-widest border-b border-gray-100">
                <th className="pb-4 pr-4 w-1/4">Feature</th>
                <th className="pb-4 pl-4">Recorded Observation</th>
              </tr>
            </thead>
            <tbody className="text-sm">
              {nonIntrusiveSurvey.notes.map((note: { title: string; note: string }, i: number) => (
                <tr key={i} className="hover:bg-gray-50 transition-colors">
                  <td className="py-4 pr-4 font-bold text-brandblue">{note.title}</td>
                  <td className="py-4 pl-4 text-gray-500">{note.note}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
      )}

      {/* ── Solar Section ────────────────────────────────────────────────────── */}

      {/* Solar section header — always shown if we have coords */}
      {(solarData || spatial?.latitude) && (
        <div className="flex items-center gap-4 pt-2">
          <div className="w-8 h-8 rounded-xl bg-amber-50 border border-amber-200/60 flex items-center justify-center shrink-0">
            <SunIcon className="w-4 h-4 text-amber-600" />
          </div>
          <div>
            <p className="font-manrope text-xs font-bold text-amber-600 uppercase tracking-widest">
              Solar Potential Analysis
            </p>
          </div>
        </div>
      )}

      {solarData && sp ? (
        <>
          {/* Row 4: Solar info + Rooftop Summary side by side, then map below */}
          <div className="grid grid-cols-12 gap-6">

            {/* Left: scenario context + imagery info + rooftop summary */}
            <div className="col-span-12 lg:col-span-5 flex flex-col gap-4">

              {/* Scenario / imagery context card */}
              <div className="bg-amber-50 border border-amber-200/60 rounded-2xl px-5 py-4 flex flex-col gap-3">
                <p className="text-sm font-medium text-amber-800 leading-snug">
                  {solarScenarioData?.scenrioType === "building"
                    ? "Figures represent the building as a whole."
                    : "Figures represent this individual unit."}
                </p>
                <div className="flex flex-wrap items-center gap-2">
                  {imageryQuality && (
                    <span className={`text-xs font-semibold px-2.5 py-1 rounded-full border ${qualityBadge}`}>
                      {qualityText}
                    </span>
                  )}
                  {imageryDateStr && (
                    <span className="text-xs text-amber-700/70 font-medium">
                      Imagery: {imageryDateStr}
                    </span>
                  )}
                </div>
              </div>

              {/* Rooftop Summary */}
              <Card className="flex-1 shadow-sm border-gray-200/80">
                <CardHeader className="pb-1 pt-6 px-6">
                  <CardTitle className="text-base font-bold text-brandblue font-manrope">
                    Rooftop Summary
                  </CardTitle>
                  <p className="text-xs text-gray-400 mt-0.5">
                    Key metrics extracted from aerial imagery analysis.
                  </p>
                </CardHeader>
                <CardContent className="px-6 pb-6 pt-2">
                  <div className="divide-y divide-gray-100 text-sm">
                    {[
                      {
                        icon: <BoltIcon className="w-3.5 h-3.5" />,
                        label: "Max annual output",
                        value: `${maxAnnualKwh.toLocaleString()} kWh`,
                      },
                      {
                        icon: <Squares2X2Icon className="w-3.5 h-3.5" />,
                        label: "Max panel count",
                        value: `${sp.maxArrayPanelsCount} panels`,
                      },
                      {
                        icon: <Squares2X2Icon className="w-3.5 h-3.5" />,
                        label: "Max array area",
                        value: `${sp.maxArrayAreaMeters2.toFixed(0)} m²`,
                      },
                      {
                        icon: <SparklesIcon className="w-3.5 h-3.5" />,
                        label: "Roof faces identified",
                        value: `${roofSegmentStats.length}`,
                      },
                      {
                        icon: <SunIcon className="w-3.5 h-3.5" />,
                        label: "Max sunshine hours",
                        value: `${Math.round(sp.maxSunshineHoursPerYear).toLocaleString()} hrs/yr`,
                      },
                      {
                        icon: <SparklesIcon className="w-3.5 h-3.5" />,
                        label: "Carbon offset factor",
                        value: `${Math.round(sp.carbonOffsetFactorKgPerMwh)} kg/MWh`,
                      },
                      {
                        icon: <Squares2X2Icon className="w-3.5 h-3.5" />,
                        label: "Panel dimensions",
                        value: `${sp.panelWidthMeters} m × ${sp.panelHeightMeters} m`,
                      },
                      {
                        icon: <BoltIcon className="w-3.5 h-3.5" />,
                        label: "Panel capacity",
                        value: `${sp.panelCapacityWatts} W`,
                      },
                    ].map(({ icon, label, value }, i) => (
                      <div key={i} className="flex items-center justify-between py-3 group">
                        <div className="flex items-center gap-2.5">
                          <span className="shrink-0 w-6 h-6 rounded-md bg-brandblue/5 flex items-center justify-center text-brandblue/60 group-hover:bg-brandblue/10 transition-colors">
                            {icon}
                          </span>
                          <span className="text-gray-500">{label}</span>
                        </div>
                        <span className="font-semibold text-gray-800 tabular-nums">{value}</span>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* Right: Map */}
            <div className="col-span-12 lg:col-span-7 rounded-2xl overflow-hidden border border-gray-200 shadow-sm min-h-[500px]">
              <PropertyMapWrapper latitude={lat} longitude={lng} />
            </div>
          </div>

          {/* Row 5: Roof Profile */}
          {roofSegmentStats.length > 0 && (
            <section>
              <div className="mb-6">
                <h2 className="font-manrope font-bold text-xl text-brandblue mb-1">
                  Roof Profile
                </h2>
                <p className="text-sm text-gray-400 leading-relaxed">
                  {roofSegmentStats.length} roof face{roofSegmentStats.length !== 1 ? "s" : ""} identified.
                  South-facing segments with low pitch typically yield the highest solar output.
                </p>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                {roofSegmentStats.map((seg: any, i: number) => (
                  <RoofSegmentCard
                    key={i}
                    index={i}
                    azimuthDegrees={seg.azimuthDegrees}
                    pitchDegrees={seg.pitchDegrees}
                    areaMeters2={seg.stats.areaMeters2}
                    groundAreaMeters2={seg.stats.groundAreaMeters2}
                    sunshineQuantiles={seg.stats.sunshineQuantiles}
                    planeHeightAtCenterMeters={seg.planeHeightAtCenterMeters}
                  />
                ))}
              </div>
            </section>
          )}

          {/* Row 6: Solar Simulation */}
          <section className="bg-white rounded-2xl p-10 shadow-sm border border-gray-100">
            <h2 className="font-manrope font-bold text-xl text-brandblue mb-2">
              Solar Configurations
            </h2>
            <p className="text-sm text-gray-400 mb-8 leading-relaxed">
              All array sizes modelled for this property. The efficiency curve reveals
              how output scales with system size — useful for understanding which roof
              faces are doing the most work.
            </p>
            <SolarSimulationWrapper
              solarPanelConfigs={sp.solarPanelConfigs}
              panelCapacityWatts={sp.panelCapacityWatts}
              panelLifetimeYears={sp.panelLifetimeYears}
              panelWidthMeters={sp.panelWidthMeters}
              panelHeightMeters={sp.panelHeightMeters}
            />
          </section>
        </>
      ) : (spatial?.latitude && spatial?.longitude) ? (
        /* No solar data — show map with annotation */
        <div className="grid grid-cols-12 gap-6">
          <div className="col-span-12 lg:col-span-7 rounded-2xl overflow-hidden border border-gray-200 shadow-sm relative" style={{ height: "400px" }}>
            <PropertyMapWrapper latitude={spatial.latitude} longitude={spatial.longitude} />
            <div className="absolute inset-0 flex items-end justify-start p-5 pointer-events-none">
              <div className="bg-white/90 backdrop-blur-sm border border-amber-200 rounded-xl px-4 py-3 shadow-sm max-w-xs">
                <p className="text-xs font-bold text-amber-700 uppercase tracking-widest mb-1">Solar data unavailable</p>
                <p className="text-xs text-gray-500 leading-snug">
                  Solar potential analysis has not been completed for this property. This may be due to insufficient aerial imagery coverage or the property type may not be suitable for solar assessment.
                </p>
              </div>
            </div>
          </div>
          <div className="col-span-12 lg:col-span-5 bg-white rounded-2xl p-8 shadow-sm border border-gray-100 flex flex-col justify-center">
            <div className="w-10 h-10 rounded-2xl bg-amber-50 border border-amber-200 flex items-center justify-center mb-4">
              <SunIcon className="w-5 h-5 text-amber-500" />
            </div>
            <h3 className="font-manrope font-bold text-lg text-brandblue mb-2">Solar Analysis Not Available</h3>
            <p className="text-sm text-gray-500 leading-relaxed">
              We were unable to retrieve solar potential data for this address. This can happen when aerial imagery quality is insufficient, the property is in a densely shaded area, or a solar survey has not yet been commissioned.
            </p>
          </div>
        </div>
      ) : null}

    </div>
  );
}
