"use client";

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

interface Props {
  executiveBrief: ExecutiveBrief | null | undefined;
}

const SEVERITY_COLORS: Record<string, string> = {
  critical: "bg-red-100 text-red-800 border-red-200",
  high: "bg-amber-100 text-amber-800 border-amber-200",
  moderate: "bg-yellow-100 text-yellow-800 border-yellow-200",
};

function ScoreBar({ current, p30, p60, p90, max }: { current: number; p30: number; p60: number; p90: number; max: number }) {
  const pct = (v: number) => Math.min(100, Math.round((v / max) * 100));
  return (
    <div className="relative">
      <div className="flex justify-between text-xs text-slate-400 mb-1.5">
        <span>Current</span>
        <span>30d</span>
        <span>60d</span>
        <span>90d</span>
      </div>
      <div className="relative h-3 bg-slate-100 rounded-full overflow-hidden">
        <div className="absolute inset-y-0 left-0 bg-slate-300 rounded-full" style={{ width: `${pct(current)}%` }} />
        <div className="absolute inset-y-0 left-0 bg-blue-400 rounded-full opacity-60" style={{ width: `${pct(p30)}%` }} />
        <div className="absolute inset-y-0 left-0 bg-blue-500 rounded-full opacity-50" style={{ width: `${pct(p60)}%` }} />
        <div className="absolute inset-y-0 left-0 bg-blue-600 rounded-full opacity-40" style={{ width: `${pct(p90)}%` }} />
      </div>
      <div className="flex justify-between text-xs font-semibold text-slate-700 mt-1.5">
        <span>{current}</span>
        <span className="text-blue-600">{p30}</span>
        <span className="text-blue-600">{p60}</span>
        <span className="text-blue-600">{p90}</span>
      </div>
    </div>
  );
}

export function ExecutiveBriefSection({ executiveBrief }: Props) {
  if (!executiveBrief) return null;

  const { headline, crossCuttingThemes, criticalFinding, topFindings, topQuickWins, ninetyDayOutlook, closingPage } = executiveBrief;

  return (
    <div id="audit-executive-brief" className="space-y-8">

      {/* ── 1. Headline ── */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 sm:p-8 shadow-sm">
        <div className="flex flex-wrap items-start justify-between gap-4 mb-6">
          <div>
            <div className="text-5xl font-black text-slate-900 leading-none">{headline.auditScore}</div>
            <div className="text-sm font-semibold text-slate-500 mt-1">{headline.scoreLabel}</div>
          </div>
          <span className="text-xs font-medium text-indigo-700 bg-indigo-50 border border-indigo-200 px-3 py-1.5 rounded-full">
            {headline.industryPosition}
          </span>
        </div>

        <div className="bg-slate-50 border border-slate-200 rounded-xl p-4 mb-5">
          <p className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1">Standout Metric</p>
          <p className="text-base font-semibold text-slate-900">{headline.keyMetric}</p>
        </div>

        <p className="text-[15px] text-slate-700 leading-[1.7]">{headline.narrative}</p>
      </div>

      {/* ── 2. Cross-Cutting Themes ── */}
      {crossCuttingThemes.length > 0 && (
        <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
          <p className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-4">Cross-Cutting Themes</p>
          <div className="space-y-3">
            {crossCuttingThemes.map((theme, i) => (
              <div key={i} className="border border-slate-200 border-l-[3px] border-l-indigo-500 rounded-r-xl rounded-l-sm bg-slate-50/60 p-4">
                <p className="text-sm font-semibold text-slate-900 mb-1">{theme.title}</p>
                <p className="text-sm text-slate-600 leading-relaxed">{theme.description}</p>
                {theme.affectedAreas.length > 0 && (
                  <div className="flex flex-wrap gap-1.5 mt-2">
                    {theme.affectedAreas.map((area) => (
                      <span key={area} className="text-[10px] font-medium text-slate-500 bg-slate-100 px-2 py-0.5 rounded-full">{area}</span>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── 3. Critical Finding ── */}
      <div className="bg-red-50 rounded-2xl border border-red-200 p-6 shadow-sm">
        <div className="flex items-center gap-2 mb-4">
          <span className="text-red-500 text-lg">!</span>
          <p className="text-[11px] font-semibold uppercase tracking-widest text-red-400">The Critical Finding</p>
        </div>
        <h3 className="text-lg font-bold text-red-900 mb-3">{criticalFinding.title}</h3>
        <p className="text-sm text-red-800 leading-relaxed mb-4">{criticalFinding.framing}</p>
        <div className="grid sm:grid-cols-2 gap-3">
          <div className="bg-white/70 rounded-lg p-3 border border-red-100">
            <p className="text-[10px] font-semibold uppercase tracking-widest text-red-400 mb-1">Business Impact</p>
            <p className="text-sm text-red-900">{criticalFinding.affectedBusinessOutcome}</p>
          </div>
          <div className="bg-white/70 rounded-lg p-3 border border-red-100">
            <p className="text-[10px] font-semibold uppercase tracking-widest text-red-400 mb-1">Primary Remediation</p>
            <p className="text-sm text-red-900">{criticalFinding.primaryRemediation}</p>
          </div>
        </div>
      </div>

      {/* ── 4. Top 5 Findings ── */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <p className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-4">Top 5 Findings</p>
        <div className="space-y-3">
          {topFindings.map((finding) => (
            <div key={finding.rank} className="flex items-start gap-4 p-4 border border-slate-100 rounded-xl hover:bg-slate-50/60 transition-colors">
              <div className="shrink-0 w-7 h-7 rounded-full bg-slate-100 flex items-center justify-center text-xs font-bold text-slate-600">
                {finding.rank}
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex flex-wrap items-center gap-2 mb-1">
                  <span className={`text-[10px] font-semibold uppercase tracking-wide px-2 py-0.5 rounded-full border ${SEVERITY_COLORS[finding.severity] ?? "bg-slate-100 text-slate-600 border-slate-200"}`}>
                    {finding.severity}
                  </span>
                  <span className="text-[10px] text-slate-400">{finding.affectedSection}</span>
                </div>
                <p className="text-sm font-semibold text-slate-900 mb-1">{finding.title}</p>
                <p className="text-sm text-slate-600">{finding.impactSummary}</p>
                {finding.quantifiedOpportunity && (
                  <p className="text-xs text-indigo-600 font-medium mt-1.5 bg-indigo-50 px-2.5 py-1 rounded-lg inline-block">
                    {finding.quantifiedOpportunity}
                  </p>
                )}
                <p className="text-xs text-slate-500 mt-2">{finding.primaryRecommendation}</p>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── 5. Top 3 Quick Wins ── */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <p className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-4">Top 3 Quick Wins</p>
        <div className="grid gap-4 sm:grid-cols-3">
          {topQuickWins.map((win) => (
            <div key={win.rank} className="border border-slate-200 rounded-xl p-4 bg-slate-50/40">
              <div className="flex items-center justify-between mb-3">
                <div className="w-7 h-7 rounded-full bg-emerald-100 flex items-center justify-center text-xs font-bold text-emerald-700">
                  {win.rank}
                </div>
                <span className="text-[10px] font-medium text-slate-500">{win.effortHours}h effort</span>
              </div>
              <p className="text-sm font-semibold text-slate-900 mb-2">{win.title}</p>
              <p className="text-xs text-emerald-700 font-medium bg-emerald-50 px-2 py-0.5 rounded-full inline-block mb-2">{win.expectedLift}</p>
              <p className="text-xs text-slate-600 leading-relaxed mb-2">{win.implementationNote}</p>
              <p className="text-xs text-indigo-600 font-medium">{win.whyFirst}</p>
            </div>
          ))}
        </div>
      </div>

      {/* ── 6. 90-Day Outlook ── */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <p className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-4">90-Day Strategic Outlook</p>
        <div className="mb-6">
          <ScoreBar
            current={ninetyDayOutlook.currentScore}
            p30={ninetyDayOutlook.projectedScore30d}
            p60={ninetyDayOutlook.projectedScore60d}
            p90={ninetyDayOutlook.projectedScore90d}
            max={ninetyDayOutlook.maxPossibleScore}
          />
          <div className="flex justify-between text-xs text-slate-400 mt-2">
            <span>Max: {ninetyDayOutlook.maxPossibleScore}</span>
            <span>Total effort: ~{ninetyDayOutlook.totalEffortHours}h</span>
          </div>
        </div>

        <div className="space-y-2 mb-4">
          {ninetyDayOutlook.phaseHighlights.map((phase, i) => (
            <div key={i} className="flex items-start gap-3 p-3 border border-slate-100 rounded-lg">
              <span className="text-[10px] font-semibold text-slate-400 bg-slate-100 px-2 py-0.5 rounded shrink-0 mt-0.5">{phase.phaseName}</span>
              <div className="min-w-0">
                <p className="text-xs font-medium text-slate-700">{phase.primaryFocus}</p>
                <p className="text-xs text-slate-400 mt-0.5">{phase.keyMilestone}</p>
              </div>
            </div>
          ))}
        </div>

        <p className="text-xs text-slate-400 italic">{ninetyDayOutlook.confidenceNote}</p>
      </div>

      {/* ── 7. Closing Section (audit-type-specific) ── */}
      {closingPage.type === "behavioral_highlights" && closingPage.behavioralHighlights && (
        <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
          <p className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-2">Behavioral Intelligence Highlights</p>
          <p className="text-sm text-slate-700 leading-relaxed mb-5">{closingPage.behavioralHighlights.narrative}</p>
          <div className="space-y-3">
            {closingPage.behavioralHighlights.topInsights.map((insight, i) => (
              <div key={i} className="border border-slate-200 rounded-xl p-4 bg-slate-50/40">
                <p className="text-sm font-semibold text-slate-900 mb-1">{insight.insight}</p>
                <p className="text-xs text-indigo-600 font-medium mb-1.5">{insight.supportingData}</p>
                <p className="text-xs text-slate-500">Connected action: {insight.connectedAction}</p>
              </div>
            ))}
          </div>
          <p className="text-xs text-slate-400 italic mt-4">{closingPage.behavioralHighlights.patentRelevance}</p>
        </div>
      )}

      {closingPage.type === "first_party_preview" && closingPage.firstPartyPreview && (
        <div className="bg-indigo-50 rounded-2xl border border-indigo-200 p-6 shadow-sm">
          <p className="text-[11px] font-semibold uppercase tracking-widest text-indigo-400 mb-2">What First-Party Data Would Reveal</p>
          <p className="text-sm text-indigo-900 leading-relaxed mb-5">{closingPage.firstPartyPreview.narrative}</p>
          <div className="space-y-3 mb-6">
            {closingPage.firstPartyPreview.previewCallouts.map((callout, i) => (
              <div key={i} className="bg-white rounded-xl border border-indigo-100 p-4">
                <div className="grid sm:grid-cols-2 gap-3 mb-2">
                  <div>
                    <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">Current Estimate</p>
                    <p className="text-sm text-slate-700">{callout.currentEstimate}</p>
                  </div>
                  <div>
                    <p className="text-[10px] font-semibold uppercase tracking-widest text-indigo-400 mb-1">With Site Tag</p>
                    <p className="text-sm text-indigo-900 font-medium">{callout.firstPartyReveal}</p>
                  </div>
                </div>
                <p className="text-xs text-slate-500 border-t border-slate-100 pt-2">{callout.businessRelevance}</p>
              </div>
            ))}
          </div>
          <div className="text-center">
            <span className="inline-block bg-indigo-600 text-white text-sm font-semibold px-5 py-3 rounded-xl">
              {closingPage.firstPartyPreview.ctaText}
            </span>
          </div>
        </div>
      )}
    </div>
  );
}
