"use client";

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

interface Props {
  backlinkProfile: NonNullable<SeoSection["backlinkProfile"]>;
}

function fmt(n: number | null | undefined): string {
  if (n == null) return "—";
  return n.toLocaleString();
}

function SpamMeter({ score }: { score: number | null | undefined }) {
  if (score == null) return null;
  const color = score < 30 ? "bg-emerald-500" : score < 60 ? "bg-amber-500" : "bg-red-500";
  const label = score < 30 ? "Low" : score < 60 ? "Medium" : "High";
  return (
    <div className="mt-1">
      <div className="flex items-center gap-2">
        <div className="flex-1 bg-white/10 rounded-full h-1.5 overflow-hidden">
          <div className={`h-full rounded-full ${color}`} style={{ width: `${score}%` }} />
        </div>
        <span className="text-xs text-slate-400 w-12 shrink-0">{score}% {label}</span>
      </div>
    </div>
  );
}

export function BacklinkProfileSection({ backlinkProfile: bp }: Props) {
  return (
    <div className="rounded-2xl bg-slate-900/60 border border-white/10 overflow-hidden">
      <div className="px-6 py-5 border-b border-white/10">
        <h3 className="text-sm font-semibold text-slate-100">Backlink Profile</h3>
        <p className="text-xs text-slate-400 mt-0.5">Domain authority and inbound link health</p>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-4 divide-x divide-white/10">
        <div className="px-5 py-5">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">
            Domain rank
          </p>
          <div className="text-3xl font-black tabular-nums text-white leading-none">
            {fmt(bp.domainRank)}
          </div>
          <p className="text-[10px] text-slate-500 mt-1">0–100 scale</p>
        </div>

        <div className="px-5 py-5">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">
            Referring domains
          </p>
          <div className="text-3xl font-black tabular-nums text-white leading-none">
            {fmt(bp.referringDomains)}
          </div>
        </div>

        <div className="px-5 py-5">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">
            Total backlinks
          </p>
          <div className="text-3xl font-black tabular-nums text-white leading-none">
            {fmt(bp.totalBacklinks)}
          </div>
        </div>

        <div className="px-5 py-5">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">
            Spam score
          </p>
          <SpamMeter score={bp.spamScore} />
          {bp.spamScore == null && (
            <span className="text-2xl font-black text-slate-500">—</span>
          )}
        </div>
      </div>
    </div>
  );
}
