"use client";

import type { BrandAuthorityScore, AuthoritySignal, AuthorityTier } from "@/lib/authority/types";

interface Props {
  brandAuthorityScore: BrandAuthorityScore | null | undefined;
}

const TIER_CONFIG: Record<AuthorityTier, { label: string; scoreClass: string; badgeClass: string; barClass: string }> = {
  Authoritative: {
    label: "Authoritative",
    scoreClass: "text-emerald-400",
    badgeClass: "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30",
    barClass: "bg-emerald-500",
  },
  Established: {
    label: "Established",
    scoreClass: "text-blue-400",
    badgeClass: "bg-blue-500/20 text-blue-400 border border-blue-500/30",
    barClass: "bg-blue-500",
  },
  Emerging: {
    label: "Emerging",
    scoreClass: "text-amber-400",
    badgeClass: "bg-amber-500/20 text-amber-400 border border-amber-500/30",
    barClass: "bg-amber-500",
  },
  Limited: {
    label: "Limited",
    scoreClass: "text-red-400",
    badgeClass: "bg-red-500/20 text-red-400 border border-red-500/30",
    barClass: "bg-red-500",
  },
};

const STATUS_CONFIG = {
  strong: { label: "Strong", class: "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30" },
  moderate: { label: "Moderate", class: "bg-amber-500/20 text-amber-400 border border-amber-500/30" },
  weak: { label: "Weak", class: "bg-orange-500/20 text-orange-400 border border-orange-500/30" },
  absent: { label: "Absent", class: "bg-red-500/20 text-red-400 border border-red-500/30" },
} as const;

function ScoreBar({ score, barClass }: { score: number; barClass: string }) {
  return (
    <div className="flex items-center gap-3">
      <div className="flex-1 h-2 bg-slate-700/60 rounded-full overflow-hidden">
        <div className={`h-full rounded-full transition-all ${barClass}`} style={{ width: `${Math.min(100, score)}%` }} />
      </div>
      <span className="text-sm font-bold text-slate-300 w-12 text-right">{score}/100</span>
    </div>
  );
}

function SignalCard({ signal }: { signal: AuthoritySignal }) {
  const statusCfg = STATUS_CONFIG[signal.status];
  const tierCfg = TIER_CONFIG[signal.rawScore >= 75 ? "Authoritative" : signal.rawScore >= 45 ? "Established" : signal.rawScore >= 15 ? "Emerging" : "Limited"];
  return (
    <div className="rounded-xl bg-slate-800/60 border border-slate-700/50 p-4 space-y-3">
      <div className="flex items-center justify-between gap-2">
        <span className="text-sm font-semibold text-slate-200">{signal.label}</span>
        <span className={`text-xs font-medium px-2 py-0.5 rounded-full ${statusCfg.class}`}>{statusCfg.label}</span>
      </div>

      <ScoreBar score={signal.rawScore} barClass={tierCfg.barClass} />

      <div className="flex items-center justify-between text-xs text-slate-500">
        <span>Weight: {Math.round(signal.weight * 100)}%</span>
        <span>Contribution: {signal.weightedContribution.toFixed(1)} pts</span>
      </div>

      {signal.evidence.length > 0 && (
        <ul className="space-y-1">
          {signal.evidence.slice(0, 2).map((e, i) => (
            <li key={i} className="flex items-start gap-2 text-xs text-slate-400">
              <span className="shrink-0 text-slate-500 mt-0.5">-</span>
              {e}
            </li>
          ))}
        </ul>
      )}

      {signal.recommendation && (
        <div className="rounded-lg bg-slate-900/60 border border-slate-700/40 p-3">
          <p className="text-xs text-slate-300 leading-relaxed">{signal.recommendation}</p>
        </div>
      )}
    </div>
  );
}

export function BrandAuthorityScoreSection({ brandAuthorityScore }: Props) {
  if (!brandAuthorityScore?.hasScore) return null;

  const { overall, tier, signals, topRecommendations, narrativeSummary, patentRelevance, costMetrics } = brandAuthorityScore;
  const tierCfg = TIER_CONFIG[tier];

  return (
    <section className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-slate-100">Brand Authority Score</h2>
        <span className={`text-xs font-medium px-3 py-1 rounded-full ${tierCfg.badgeClass}`}>{tierCfg.label}</span>
      </div>

      {/* Hero strip */}
      <div className="rounded-2xl bg-gradient-to-br from-slate-800/80 to-slate-900/80 border border-slate-700/50 p-6">
        <div className="flex items-center gap-6">
          <div className="shrink-0 text-center">
            <span className={`text-5xl font-black ${tierCfg.scoreClass}`}>{overall}</span>
            <p className="text-xs text-slate-500 mt-1">out of 100</p>
          </div>
          <div className="flex-1 space-y-3">
            <div className="flex items-center gap-3">
              <span className={`text-sm font-bold ${tierCfg.scoreClass}`}>{tier}</span>
            </div>
            <div className="h-3 bg-slate-700/60 rounded-full overflow-hidden">
              <div className={`h-full rounded-full ${tierCfg.barClass}`} style={{ width: `${overall}%` }} />
            </div>
            <p className="text-sm text-slate-400 leading-relaxed">{narrativeSummary}</p>
          </div>
        </div>
      </div>

      {/* 6 signal cards -- 2x3 grid on desktop */}
      <div>
        <h3 className="text-sm font-semibold text-slate-400 uppercase tracking-wider mb-4">Authority Signals</h3>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {signals.map((signal) => (
            <SignalCard key={signal.key} signal={signal} />
          ))}
        </div>
      </div>

      {/* Top 3 recommendations */}
      {topRecommendations.length > 0 && (
        <div className="rounded-xl bg-slate-800/40 border border-slate-700/40 p-5 space-y-3">
          <h3 className="text-sm font-semibold text-slate-300">Top Recommendations</h3>
          <ol className="space-y-3">
            {topRecommendations.map((rec, i) => (
              <li key={i} className="flex items-start gap-3">
                <span className="shrink-0 w-5 h-5 rounded-full bg-slate-700 text-slate-300 text-xs font-bold flex items-center justify-center mt-0.5">
                  {i + 1}
                </span>
                <p className="text-sm text-slate-300 leading-relaxed">{rec}</p>
              </li>
            ))}
          </ol>
        </div>
      )}

      {/* Vertical calibration footer */}
      <div className="flex items-start gap-3 text-xs text-slate-500 border-t border-slate-700/40 pt-4">
        <span className="shrink-0 font-medium text-slate-400">Methodology</span>
        <p>{patentRelevance}</p>
      </div>

      {costMetrics && (
        <p className="text-xs text-slate-600">
          Signals: {costMetrics.signalsSucceeded}/{costMetrics.signalsAttempted} collected in {costMetrics.runtimeSeconds.toFixed(1)}s
        </p>
      )}
    </section>
  );
}
