"use client";

import type { IndustryBenchmarkComparison } from "@/lib/audit/types";

type Standing = "top-25" | "top-50" | "bottom-50" | "bottom-25";

function standingBadgeColor(standing: Standing): string {
  switch (standing) {
    case "top-25":    return "text-emerald-400 bg-emerald-400/10";
    case "top-50":    return "text-amber-400 bg-amber-400/10";
    case "bottom-50": return "text-orange-400 bg-orange-400/10";
    case "bottom-25": return "text-red-400 bg-red-400/10";
  }
}

function standingLabel(standing: Standing): string {
  switch (standing) {
    case "top-25":    return "Top 25%";
    case "top-50":    return "Top 50%";
    case "bottom-50": return "Bottom 50%";
    case "bottom-25": return "Bottom 25%";
  }
}

function overallStandingLabel(percentile: number): string {
  if (percentile >= 75) return "top 25%";
  if (percentile >= 50) return "top 50%";
  if (percentile >= 25) return "bottom 50%";
  return "bottom 25%";
}

function overallStandingColor(percentile: number): string {
  if (percentile >= 75) return "text-emerald-400";
  if (percentile >= 50) return "text-amber-400";
  return "text-red-400";
}

function barColor(standing: Standing): string {
  switch (standing) {
    case "top-25":    return "bg-emerald-500";
    case "top-50":    return "bg-amber-500";
    case "bottom-50": return "bg-orange-500";
    case "bottom-25": return "bg-red-500";
  }
}

interface DimensionCardProps {
  name: string;
  brandValue: number;
  industryAverage: number;
  industryP25: number;
  industryP75: number;
  brandPercentile: number;
  brandStanding: Standing;
  gapToAverage: number;
}

function DimensionCard({
  name,
  brandValue,
  industryAverage,
  industryP25,
  industryP75,
  brandPercentile,
  brandStanding,
  gapToAverage,
}: DimensionCardProps) {
  // Compute positions as percentages for the bar (cap at 0–100)
  const max = Math.max(industryP75 * 1.2, brandValue * 1.1, 1);
  const pct = (v: number) => Math.min(100, Math.max(0, (v / max) * 100));

  const p25Pct  = pct(industryP25);
  const p75Pct  = pct(industryP75);
  const avgPct  = pct(industryAverage);
  const brandPct = pct(brandValue);

  const isAbove = gapToAverage >= 0;
  const gapAbs = Math.abs(gapToAverage);
  const gapColor = isAbove ? "text-emerald-400" : "text-red-400";
  const gapText = isAbove
    ? `+${gapAbs.toFixed(1)} above industry average`
    : `${gapAbs.toFixed(1)} below industry average`;

  const badge = standingBadgeColor(brandStanding);
  const bar   = barColor(brandStanding);

  return (
    <div className="rounded-xl border border-white/10 bg-slate-900/50 p-4 flex flex-col gap-3">
      {/* Dimension name */}
      <p className="text-xs font-semibold text-slate-400 uppercase tracking-widest">
        {name}
      </p>

      {/* Value + badge */}
      <div className="flex items-center gap-3">
        <span className="text-2xl font-bold text-slate-100">
          {brandValue.toFixed(1)}
        </span>
        <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${badge}`}>
          {standingLabel(brandStanding)}
        </span>
        <span className="text-xs text-slate-500 ml-auto">
          {brandPercentile}th percentile
        </span>
      </div>

      {/* Visual bar */}
      <div className="relative">
        <div className="relative h-2 w-full rounded-full bg-white/10 overflow-visible">
          {/* Filled segment 0 → p75 */}
          <div
            className={`absolute left-0 top-0 h-full rounded-full opacity-30 ${bar}`}
            style={{ width: `${p75Pct}%` }}
          />
          {/* avg tick */}
          <div
            className="absolute top-0 h-full w-0.5 bg-white/40"
            style={{ left: `${avgPct}%` }}
          />
          {/* brand marker */}
          <div
            className={`absolute -top-1 h-4 w-1.5 rounded-full ${bar} shadow-md`}
            style={{ left: `calc(${brandPct}% - 3px)` }}
          />
        </div>
        {/* Labels */}
        <div className="relative h-4 mt-1">
          <span
            className="absolute text-[10px] text-slate-500 -translate-x-1/2"
            style={{ left: `${p25Pct}%` }}
          >
            p25
          </span>
          <span
            className="absolute text-[10px] text-slate-500 -translate-x-1/2"
            style={{ left: `${avgPct}%` }}
          >
            avg
          </span>
          <span
            className="absolute text-[10px] text-slate-500 -translate-x-1/2"
            style={{ left: `${p75Pct}%` }}
          >
            p75
          </span>
        </div>
      </div>

      {/* Gap callout */}
      <p className={`text-xs font-medium ${gapColor}`}>{gapText}</p>
    </div>
  );
}

interface Props {
  industryBenchmarkComparison: IndustryBenchmarkComparison | null | undefined;
}

export function IndustryBenchmarkSection({ industryBenchmarkComparison }: Props) {
  if (!industryBenchmarkComparison) return null;

  const { industryDisplayName, dimensions, overallPercentile } =
    industryBenchmarkComparison;

  const headlineLabel = overallStandingLabel(overallPercentile);
  const headlineColor = overallStandingColor(overallPercentile);

  return (
    <section
      id="audit-industry-benchmark"
      className="rounded-2xl bg-slate-950/80 border border-white/10 overflow-hidden"
    >
      {/* Header */}
      <div className="px-6 py-5 border-b border-white/10">
        <h3 className="text-sm font-semibold text-slate-100">Industry Benchmark</h3>
        <p className="text-xs text-slate-400 mt-1">
          How {industryDisplayName} peers compare on key signals
        </p>
      </div>

      {/* Headline */}
      <div className="px-6 pt-5">
        <p className="text-lg font-semibold text-slate-100">
          You&apos;re in the{" "}
          <span className={headlineColor}>{headlineLabel}</span>
          {" "}of your industry
        </p>
      </div>

      {/* Dimension cards */}
      <div className="px-6 pb-6 mt-4 grid grid-cols-1 gap-4 md:grid-cols-2">
        {dimensions.map((dim) => (
          <DimensionCard
            key={dim.name}
            name={dim.name}
            brandValue={dim.brandValue}
            industryAverage={dim.industryAverage}
            industryP25={dim.industryP25}
            industryP75={dim.industryP75}
            brandPercentile={dim.brandPercentile}
            brandStanding={dim.brandStanding}
            gapToAverage={dim.gapToAverage}
          />
        ))}
      </div>

      {/* Footer */}
      <div className="px-6 pb-4">
        <p className="text-xs text-slate-500">
          Benchmark estimates based on industry sample data. Percentile standings are indicative.
        </p>
      </div>
    </section>
  );
}
