"use client";

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

interface Props {
  behavioralActionBridge: BehavioralActionBridge | null | undefined;
}

const SEVERITY_CONFIG = {
  critical: { label: "Critical", class: "bg-red-500/20 text-red-400 border border-red-500/30" },
  high: { label: "High", class: "bg-orange-500/20 text-orange-400 border border-orange-500/30" },
  moderate: { label: "Moderate", class: "bg-amber-500/20 text-amber-400 border border-amber-500/30" },
  low: { label: "Low", class: "bg-slate-500/20 text-slate-400 border border-slate-500/30" },
} as const;

const CONFIDENCE_CONFIG = {
  high: { class: "bg-emerald-500/20 text-emerald-400", label: "High confidence" },
  moderate: { class: "bg-amber-500/20 text-amber-400", label: "Moderate confidence" },
  low: { class: "bg-slate-500/20 text-slate-400", label: "Low confidence" },
} as const;

const SOURCE_CONFIG = {
  "signal-center": { label: "Behavioral Telemetry", class: "bg-violet-500/15 text-violet-400" },
  "page-strategic-pass": { label: "Page Review", class: "bg-blue-500/15 text-blue-400" },
  "ai-attribution": { label: "AI Attribution", class: "bg-emerald-500/15 text-emerald-400" },
} as const;

function fmt(n: number): string {
  return n % 1 === 0 ? n.toLocaleString() : n.toFixed(1);
}

export function BehavioralActionBridgeSection({ behavioralActionBridge }: Props) {
  if (!behavioralActionBridge) return null;

  const { enhancedActions, newBehavioralFindings, topBehavioralPatterns } = behavioralActionBridge;

  const hasContent =
    enhancedActions.length > 0 ||
    newBehavioralFindings.length > 0 ||
    topBehavioralPatterns.length > 0;

  if (!hasContent) return null;

  return (
    <section id="audit-behavioral-bridge" className="space-y-8">
      {/* Header */}
      <div>
        <h2 className="text-lg font-semibold text-slate-100">
          Behavioral Intelligence: Quantified Action Bridge
        </h2>
        <p className="text-sm text-slate-400 mt-1">
          First-party behavioral telemetry cross-referenced with priority recommendations
        </p>
      </div>

      {/* Top Behavioral Patterns */}
      {topBehavioralPatterns.length > 0 && (
        <div className="space-y-3">
          <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">
            Behavioral Patterns Detected
          </h3>
          <div className="grid gap-3 sm:grid-cols-3">
            {topBehavioralPatterns.map((pattern, i) => (
              <div
                key={i}
                className="rounded-xl bg-slate-900/60 border border-white/10 p-4 space-y-2"
              >
                <p className="text-sm font-semibold text-slate-200">{pattern.pattern}</p>
                <p className="text-xs text-slate-400">{pattern.impact}</p>
                {pattern.relatedActions.length > 0 && (
                  <div className="flex flex-wrap gap-1 pt-1">
                    {pattern.relatedActions.slice(0, 2).map((action, j) => (
                      <span key={j} className="text-[10px] text-slate-500 bg-slate-800 px-2 py-0.5 rounded truncate max-w-[160px]">
                        {action}
                      </span>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Enhanced Actions */}
      {enhancedActions.length > 0 && (
        <div className="space-y-3">
          <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">
            Actions Enhanced with Behavioral Evidence
          </h3>
          <div className="space-y-4">
            {enhancedActions.map((action, i) => {
              const conf = CONFIDENCE_CONFIG[action.quantifiedImpactEstimate.confidence];
              return (
                <div
                  key={i}
                  className="rounded-xl bg-slate-900/60 border border-white/10 overflow-hidden"
                >
                  <div className="px-5 py-4 border-b border-white/10 flex items-start justify-between gap-3">
                    <h4 className="text-sm font-semibold text-slate-200">
                      {action.originalActionTitle}
                    </h4>
                    <span className={`shrink-0 text-xs px-2 py-0.5 rounded-full ${conf.class}`}>
                      {conf.label}
                    </span>
                  </div>

                  <div className="px-5 py-4 space-y-4">
                    {/* Rewritten description */}
                    <p className="text-sm text-slate-300 leading-relaxed">
                      {action.rewrittenActionDescription}
                    </p>

                    {/* Impact estimate */}
                    <div className="rounded-lg bg-slate-800/60 p-3 grid grid-cols-3 gap-3 text-xs">
                      <div>
                        <div className="text-slate-500 mb-1">Metric</div>
                        <div className="font-semibold text-slate-300">{action.quantifiedImpactEstimate.metric}</div>
                      </div>
                      <div>
                        <div className="text-slate-500 mb-1">Current</div>
                        <div className="font-semibold text-slate-300">{fmt(action.quantifiedImpactEstimate.currentValue)}</div>
                      </div>
                      <div>
                        <div className="text-slate-500 mb-1">Projected</div>
                        <div className="font-semibold text-emerald-400">{fmt(action.quantifiedImpactEstimate.projectedValue)}</div>
                      </div>
                    </div>

                    {/* Behavioral evidence */}
                    {action.behavioralEvidence.length > 0 && (
                      <div className="space-y-2">
                        <div className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                          Supporting Evidence
                        </div>
                        {action.behavioralEvidence.map((ev, j) => {
                          const src = SOURCE_CONFIG[ev.source];
                          return (
                            <div key={j} className="flex items-start gap-2.5">
                              <span className={`mt-0.5 shrink-0 text-[10px] font-semibold px-2 py-0.5 rounded ${src.class}`}>
                                {src.label}
                              </span>
                              <span className="text-xs text-slate-400">{ev.signal}</span>
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* New Behavioral Findings */}
      {newBehavioralFindings.length > 0 && (
        <div className="space-y-3">
          <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">
            New Findings from Behavioral Analysis
          </h3>
          <div className="space-y-3">
            {newBehavioralFindings.map((finding, i) => {
              const sev = SEVERITY_CONFIG[finding.severity];
              return (
                <div
                  key={i}
                  className="rounded-xl bg-slate-900/60 border border-white/10 p-4 space-y-3"
                >
                  <div className="flex items-start justify-between gap-3">
                    <h4 className="text-sm font-semibold text-slate-200">{finding.title}</h4>
                    <span className={`shrink-0 text-xs font-semibold px-2.5 py-1 rounded-full ${sev.class}`}>
                      {sev.label}
                    </span>
                  </div>
                  <p className="text-sm text-slate-300 leading-relaxed">{finding.description}</p>
                  {finding.behavioralEvidence.length > 0 && (
                    <ul className="space-y-1">
                      {finding.behavioralEvidence.map((ev, j) => (
                        <li key={j} className="flex items-start gap-2 text-xs text-slate-400">
                          <span className="shrink-0 mt-1 w-1 h-1 rounded-full bg-slate-500" />
                          {ev}
                        </li>
                      ))}
                    </ul>
                  )}
                  <p className="text-sm text-slate-300 leading-relaxed border-t border-white/5 pt-3">
                    {finding.recommendation}
                  </p>
                  {finding.affectedUrls.length > 0 && (
                    <div className="flex flex-wrap gap-1.5">
                      {finding.affectedUrls.slice(0, 4).map((url, j) => (
                        <span key={j} className="text-[10px] text-slate-500 bg-slate-800 px-2 py-0.5 rounded font-mono truncate max-w-[240px]">
                          {url}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}
    </section>
  );
}
