import { ArrowRight, ShieldCheck } from 'lucide-react';
import Link from 'next/link';

import {
  gradeBadgeClass,
  institutionalGradeRubric,
  scoreBarClass,
  sovereignInstitutionGrades,
} from '@/lib/corporate-site-data';

const audienceLabels = {
  sovereign: 'Sovereign & public sector',
  regulated: 'Regulated counterparties',
  platform: 'Platform & L1',
} as const;

export function InstitutionalGradeSection() {
  const sovereignRows = sovereignInstitutionGrades.filter((e) => e.audience === 'sovereign');
  const otherRows = sovereignInstitutionGrades.filter((e) => e.audience !== 'sovereign');

  return (
    <section id="institutional-grade" className="scroll-mt-20 border-y border-gray-800/60 bg-gray-950 py-20">
      <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
          <div className="max-w-2xl">
            <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-orange-500/30 bg-orange-500/10 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-orange-300">
              <ShieldCheck className="h-3.5 w-3.5" aria-hidden />
              Institutional readiness
            </div>
            <h2 className="text-3xl font-bold tracking-tight text-white sm:text-4xl">
              Grade &amp; score for sovereign institutions
            </h2>
            <p className="mt-4 text-lg text-gray-400">
              Transparent engineering scorecards aligned with the DBIS institutional rubric — the same
              framework used for ecosystem readiness, jurisdiction matrices, and settlement evidence.
            </p>
          </div>
          <p className="max-w-md text-xs leading-relaxed text-gray-500">
            Informational only — not legal advice, a regulatory determination, or an audit certificate.
            Counsel owns statutory interpretation. Scores reflect repo artifacts and live probes as of each
            assessment date.
          </p>
        </div>

        {/* Rubric legend */}
        <div className="mt-10 overflow-x-auto rounded-xl border border-gray-800 bg-gray-900/40">
          <table className="w-full min-w-[640px] text-left text-sm">
            <thead>
              <tr className="border-b border-gray-800 text-xs uppercase tracking-wider text-gray-500">
                <th className="px-4 py-3 font-semibold">Grade</th>
                <th className="px-4 py-3 font-semibold">Score</th>
                <th className="px-4 py-3 font-semibold">Institutional meaning</th>
              </tr>
            </thead>
            <tbody>
              {institutionalGradeRubric.map((row) => (
                <tr key={row.grade} className="border-b border-gray-800/60 last:border-0">
                  <td className="px-4 py-3">
                    <span
                      className={`inline-flex min-w-[2rem] items-center justify-center rounded-md px-2 py-0.5 text-sm font-bold ring-1 ${gradeBadgeClass(row.grade)}`}
                    >
                      {row.grade}
                    </span>
                  </td>
                  <td className="px-4 py-3 font-mono text-gray-300">{row.range}</td>
                  <td className="px-4 py-3 text-gray-400">{row.meaning}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Sovereign institution scorecards */}
        <div className="mt-12">
          <h3 className="text-lg font-semibold text-white">{audienceLabels.sovereign}</h3>
          <div className="mt-6 grid gap-4 lg:grid-cols-2">
            {sovereignRows.map((entry) => (
              <GradeCard key={entry.id} entry={entry} />
            ))}
          </div>
        </div>

        <div className="mt-12">
          <h3 className="text-lg font-semibold text-white">Related institutional assessments</h3>
          <div className="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {otherRows.map((entry) => (
              <GradeCard key={entry.id} entry={entry} compact />
            ))}
          </div>
        </div>

        <div className="mt-10 flex flex-wrap items-center gap-4 text-sm">
          <Link
            href="https://d-bis.org/cb/dbis"
            className="inline-flex items-center gap-1.5 font-medium text-orange-300 no-underline hover:text-orange-200"
          >
            DBIS institutional registry
            <ArrowRight className="h-4 w-4" aria-hidden />
          </Link>
          <span className="text-gray-600" aria-hidden>
            ·
          </span>
          <Link
            href="https://docs.d-bis.org"
            className="inline-flex items-center gap-1.5 font-medium text-orange-300 no-underline hover:text-orange-200"
          >
            Compliance matrices &amp; onboarding charter
            <ArrowRight className="h-4 w-4" aria-hidden />
          </Link>
        </div>
      </div>
    </section>
  );
}

function GradeCard({
  entry,
  compact = false,
}: {
  entry: (typeof sovereignInstitutionGrades)[number];
  compact?: boolean;
}) {
  const pct = Math.round((entry.score / entry.maxScore) * 100);
  const inner = (
    <>
      <div className="flex items-start justify-between gap-3">
        <div>
          <p className="text-sm font-semibold text-white">{entry.name}</p>
          {!compact ? (
            <p className="mt-1 text-xs text-gray-500">Assessed {entry.assessmentDate}</p>
          ) : null}
        </div>
        <span
          className={`shrink-0 rounded-lg px-2.5 py-1 text-lg font-bold ring-1 ${gradeBadgeClass(entry.letterGrade)}`}
        >
          {entry.letterGrade}
        </span>
      </div>

      <div className="mt-4 flex items-baseline gap-2">
        <span className="text-3xl font-bold tabular-nums text-white">{entry.score}</span>
        <span className="text-sm text-gray-500">/ {entry.maxScore}</span>
      </div>

      <div className="mt-3 h-1.5 overflow-hidden rounded-full bg-gray-800">
        <div
          className={`h-full rounded-full transition-all ${scoreBarClass(entry.letterGrade)}`}
          style={{ width: `${pct}%` }}
          role="progressbar"
          aria-valuenow={entry.score}
          aria-valuemin={0}
          aria-valuemax={entry.maxScore}
          aria-label={`${entry.name} score ${entry.score} of ${entry.maxScore}`}
        />
      </div>

      <p className={`text-gray-400 ${compact ? 'mt-3 text-xs leading-relaxed' : 'mt-4 text-sm leading-relaxed'}`}>
        {entry.tier}
      </p>

      {compact ? (
        <p className="mt-2 text-xs text-gray-600">{entry.assessmentDate}</p>
      ) : null}
    </>
  );

  const className = compact
    ? 'rounded-xl border border-gray-800 bg-gray-900/30 p-4 transition hover:border-gray-700'
    : 'rounded-2xl border border-gray-800 bg-gray-900/40 p-6 transition hover:border-orange-500/30';

  if (entry.href) {
    return (
      <Link href={entry.href} className={`group block no-underline ${className}`}>
        {inner}
        {!compact ? (
          <span className="mt-4 inline-flex items-center gap-1 text-xs font-medium text-orange-400 group-hover:text-orange-300">
            View assessment
            <ArrowRight className="h-3 w-3" aria-hidden />
          </span>
        ) : null}
      </Link>
    );
  }

  return <article className={className}>{inner}</article>;
}
