"use client";

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

const PHASE_BADGE: Record<string, string> = {
  "week-1": "bg-emerald-500/15 text-emerald-400 border border-emerald-500/20",
  "weeks-2-4": "bg-blue-500/15 text-blue-400 border border-blue-500/20",
  "month-2": "bg-purple-500/15 text-purple-400 border border-purple-500/20",
  "month-3": "bg-orange-500/15 text-orange-400 border border-orange-500/20",
};

const TYPE_PILL: Record<string, string> = {
  Schema: "bg-violet-500/15 text-violet-400 border border-violet-500/20",
  Meta: "bg-sky-500/15 text-sky-400 border border-sky-500/20",
  CTA: "bg-pink-500/15 text-pink-400 border border-pink-500/20",
  Content: "bg-amber-500/15 text-amber-400 border border-amber-500/20",
  Performance: "bg-cyan-500/15 text-cyan-400 border border-cyan-500/20",
  Redirect: "bg-slate-500/15 text-slate-400 border border-slate-500/20",
};

const PHASE_KEYS = ["week-1", "weeks-2-4", "month-2", "month-3"];

function phaseKey(phaseName: string): string {
  const lower = phaseName.toLowerCase();
  if (lower.includes("week 1") || lower.includes("week-1")) return "week-1";
  if (lower.includes("week") || lower.includes("2-4")) return "weeks-2-4";
  if (lower.includes("month 2") || lower.includes("month-2")) return "month-2";
  if (lower.includes("month 3") || lower.includes("month-3")) return "month-3";
  return PHASE_KEYS[0];
}

function scoreColor(score: number): string {
  if (score >= 80) return "text-emerald-400";
  if (score >= 65) return "text-amber-400";
  return "text-slate-400";
}

interface Props {
  strategicRoadmap: StrategicRoadmap | null | undefined;
  currentScore?: number;
}

export function StrategicRoadmapSection({ strategicRoadmap, currentScore }: Props) {
  if (!strategicRoadmap || strategicRoadmap.phases.length === 0) return null;

  const { phases, totalEffortHours, finalProjectedScore } = strategicRoadmap;
  const baseScore = currentScore ?? (phases[0].projectedScoreAtEndOfPhase - phases[0].cumulativeLiftPoints);

  return (
    <section id="audit-roadmap" className="rounded-2xl bg-slate-950/80 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">Your 90-Day Strategic Roadmap</h3>
        <p className="text-xs text-slate-400 mt-1">Phased implementation timeline with expected score progression</p>
      </div>

      {/* Score Progression Strip */}
      <div className="px-6 pt-5 pb-4 border-b border-white/10 overflow-x-auto">
        <div className="flex items-center gap-0 min-w-max">
          <ScoreNode score={baseScore} label="Current Score" colorClass="text-slate-300" />
          {phases.map((phase, i) => (
            <div key={i} className="flex items-center gap-0">
              <Arrow />
              <ScoreNode
                score={phase.projectedScoreAtEndOfPhase}
                label={phase.phaseName}
                colorClass={scoreColor(phase.projectedScoreAtEndOfPhase)}
              />
            </div>
          ))}
          <div className="flex items-center gap-0">
            <Arrow />
            <ScoreNode score={finalProjectedScore} label="Final Score" colorClass="text-emerald-400" />
          </div>
        </div>
      </div>

      {/* Phase Cards */}
      <div className="px-6 pb-6 pt-4 space-y-4">
        {phases.map((phase, i) => {
          const key = phaseKey(phase.phaseName);
          const badgeCls = PHASE_BADGE[key] ?? PHASE_BADGE["week-1"];
          const totalPhaseHours = phase.actions.reduce((s, a) => s + a.effortHours, 0);
          return (
            <div key={i} className="rounded-xl border border-white/10 bg-slate-900/60">
              {/* Phase header */}
              <div className="px-4 py-3 border-b border-white/10 flex flex-wrap items-center gap-x-3 gap-y-1.5">
                <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full ${badgeCls}`}>
                  {phase.phaseName}
                </span>
                <span className="text-sm font-semibold text-slate-100">{phase.theme}</span>
                <span className="text-xs text-slate-500">{phase.timeframe}</span>
                <span className="text-xs text-slate-500 ml-auto">{totalPhaseHours}h total</span>
                <span className={`text-sm font-bold tabular-nums ${scoreColor(phase.projectedScoreAtEndOfPhase)}`}>
                  → {phase.projectedScoreAtEndOfPhase}
                </span>
              </div>

              {/* Actions */}
              <div className="divide-y divide-white/5">
                {phase.actions.map((action, j) => {
                  const pillCls = TYPE_PILL[action.type] ?? TYPE_PILL["Redirect"];
                  return (
                    <div key={j} className="px-4 py-2.5 flex items-center gap-3 flex-wrap">
                      <span className={`text-[10px] font-medium px-1.5 py-0.5 rounded-full shrink-0 border ${pillCls}`}>
                        {action.type}
                      </span>
                      <span className="text-xs text-slate-200 flex-1 min-w-0">{action.title}</span>
                      <span className="text-xs text-slate-500 tabular-nums shrink-0">{action.effortHours}h</span>
                      <span className="text-xs font-semibold text-emerald-400 tabular-nums shrink-0">
                        +{action.expectedLiftPoints} pts
                      </span>
                    </div>
                  );
                })}
              </div>

              {/* Success Metrics */}
              {phase.successMetrics.length > 0 && (
                <div className="px-4 py-3 border-t border-white/5">
                  <p className="text-[10px] uppercase tracking-widest text-slate-500 mb-2">Success Metrics</p>
                  <ul className="space-y-1">
                    {phase.successMetrics.map((metric, k) => (
                      <li key={k} className="flex items-start gap-2">
                        <span className="mt-0.5 h-3 w-3 rounded-full border border-slate-600 shrink-0" />
                        <span className="text-xs text-slate-400">{metric}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Footer */}
      <div className="px-6 py-4 border-t border-white/10 text-center">
        <p className="text-xs text-slate-500">
          Total Implementation Effort:{" "}
          <span className="text-slate-300 font-medium">{totalEffortHours} hours</span> over 90 days
        </p>
      </div>
    </section>
  );
}

function ScoreNode({ score, label, colorClass }: { score: number; label: string; colorClass: string }) {
  return (
    <div className="flex flex-col items-center gap-1 px-3">
      <span className={`text-2xl font-bold tabular-nums leading-none ${colorClass}`}>{score}</span>
      <span className="text-[10px] text-slate-500 text-center max-w-[72px] leading-tight">{label}</span>
    </div>
  );
}

function Arrow() {
  return (
    <svg width="20" height="16" viewBox="0 0 20 16" fill="none" className="text-slate-700 shrink-0">
      <path d="M1 8h15M12 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}
