"use client";

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

const PRIORITY_ORDER = { critical: 0, high: 1, moderate: 2, low: 3 };

const PRIORITY_PILL: Record<string, string> = {
  critical: "bg-red-500/15 text-red-400 border border-red-500/20",
  high: "bg-orange-500/15 text-orange-400 border border-orange-500/20",
  moderate: "bg-amber-500/15 text-amber-400 border border-amber-500/20",
  low: "bg-slate-500/15 text-slate-400 border border-slate-500/20",
};

const DIFFICULTY_PILL: Record<string, string> = {
  easy: "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20",
  moderate: "bg-amber-500/10 text-amber-400 border border-amber-500/20",
  hard: "bg-red-500/10 text-red-400 border border-red-500/20",
};

interface Props {
  schemaOpportunityForecast: SchemaOpportunityForecast | null | undefined;
}

export function SchemaOpportunityForecastSection({ schemaOpportunityForecast }: Props) {
  if (!schemaOpportunityForecast) return null;

  const {
    industryVertical,
    industrySubVertical,
    prioritySchemaTypes,
    currentCoveragePercent,
    cumulativeLiftEstimate,
    hasSchemaConflicts,
    schemaConflicts,
  } = schemaOpportunityForecast;

  const sorted = [...prioritySchemaTypes].sort(
    (a, b) => PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority],
  );

  return (
    <section
      id="audit-schema-opportunities"
      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">Schema Opportunity Forecast</h3>
        <p className="text-xs text-slate-400 mt-1">
          Industry-specific structured data priorities and citation eligibility lift estimates
        </p>
        <p className="text-xs text-slate-500 mt-0.5">
          {industryVertical}
          {industrySubVertical ? ` · ${industrySubVertical}` : ""}
        </p>
      </div>

      <div className="px-6 py-4 border-b border-white/10 grid grid-cols-3 gap-4">
        <div>
          <p className="text-[10px] uppercase tracking-widest text-slate-500 mb-1">Current Coverage</p>
          <p className="text-2xl font-bold tabular-nums text-slate-100">{currentCoveragePercent}%</p>
        </div>
        <div>
          <p className="text-[10px] uppercase tracking-widest text-slate-500 mb-1">Potential Coverage</p>
          <p className="text-2xl font-bold tabular-nums text-slate-100">100%</p>
        </div>
        <div>
          <p className="text-[10px] uppercase tracking-widest text-slate-500 mb-1">Lift Available</p>
          <p className={`text-2xl font-bold tabular-nums ${cumulativeLiftEstimate > 0 ? "text-emerald-400" : "text-slate-400"}`}>
            +{cumulativeLiftEstimate}%
          </p>
        </div>
      </div>

      <div className="hidden md:block overflow-x-auto">
        <table className="w-full text-xs">
          <thead>
            <tr className="text-slate-500 border-b border-white/5">
              <th className="text-left font-medium py-3 px-6">Schema Type</th>
              <th className="text-left font-medium py-3 px-3">Status</th>
              <th className="text-left font-medium py-3 px-3">Expected Impact</th>
              <th className="text-center font-medium py-3 px-3">Lift</th>
              <th className="text-center font-medium py-3 px-3">Difficulty</th>
              <th className="text-left font-medium py-3 px-6">How-To</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-white/5">
            {sorted.map((s) => (
              <tr key={s.schemaType} className="hover:bg-white/[0.02] transition-colors">
                <td className="py-3 px-6">
                  <div className="flex items-center gap-2">
                    <span className="font-medium text-slate-200">{s.schemaType}</span>
                    <span className={`text-[10px] px-1.5 py-0.5 rounded-full font-medium ${PRIORITY_PILL[s.priority]}`}>
                      {s.priority}
                    </span>
                  </div>
                </td>
                <td className="py-3 px-3">
                  {s.present ? (
                    <div>
                      <span className="text-emerald-400 font-medium">✓ Present</span>
                      {s.presentOnPages.length > 0 && (
                        <div className="mt-1 space-y-0.5">
                          {s.presentOnPages.slice(0, 2).map((url) => {
                            let path = url;
                            try { path = new URL(url).pathname || "/"; } catch { /* keep full */ }
                            return (
                              <p key={url} className="text-slate-500 font-mono truncate max-w-[140px]">{path}</p>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  ) : (
                    <span className="text-red-400 font-medium">✗ Not detected</span>
                  )}
                </td>
                <td className="py-3 px-3 max-w-[180px]">
                  <p className="text-slate-400 italic leading-relaxed">{s.expectedImpact}</p>
                </td>
                <td className="py-3 px-3 text-center">
                  <span className={`font-semibold tabular-nums ${!s.present ? "text-emerald-400" : "text-slate-500"}`}>
                    +{s.estimatedLiftPercent}%
                  </span>
                </td>
                <td className="py-3 px-3 text-center">
                  <span className={`text-[10px] px-2 py-0.5 rounded-full font-medium ${DIFFICULTY_PILL[s.implementationDifficulty]}`}>
                    {s.implementationDifficulty}
                  </span>
                </td>
                <td className="py-3 px-6 max-w-[200px]">
                  <p className="text-slate-500 leading-relaxed">{s.implementationNote}</p>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="md:hidden divide-y divide-white/5">
        {sorted.map((s) => (
          <div key={s.schemaType} className="px-6 py-4 space-y-2">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="font-medium text-slate-200 text-sm">{s.schemaType}</span>
              <span className={`text-[10px] px-1.5 py-0.5 rounded-full font-medium ${PRIORITY_PILL[s.priority]}`}>
                {s.priority}
              </span>
              <span className={`text-[10px] px-1.5 py-0.5 rounded-full font-medium ${DIFFICULTY_PILL[s.implementationDifficulty]}`}>
                {s.implementationDifficulty}
              </span>
            </div>
            <div className="flex items-center gap-3">
              {s.present ? (
                <span className="text-xs text-emerald-400 font-medium">✓ Present</span>
              ) : (
                <span className="text-xs text-red-400 font-medium">✗ Not detected</span>
              )}
              <span className={`text-xs font-semibold tabular-nums ${!s.present ? "text-emerald-400" : "text-slate-500"}`}>
                +{s.estimatedLiftPercent}%
              </span>
            </div>
            <p className="text-xs text-slate-400 italic">{s.expectedImpact}</p>
            <p className="text-xs text-slate-500">{s.implementationNote}</p>
          </div>
        ))}
      </div>

      {hasSchemaConflicts && schemaConflicts.length > 0 && (
        <div className="mx-6 mb-6 mt-4 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3">
          <p className="text-xs font-semibold text-red-400 mb-2">Schema Conflicts Detected</p>
          <ul className="space-y-1">
            {schemaConflicts.slice(0, 3).map((c, i) => (
              <li key={i} className="text-xs text-slate-400">
                <span className="font-mono text-slate-500 mr-1">{c.url}</span>— {c.issue}
              </li>
            ))}
          </ul>
        </div>
      )}
    </section>
  );
}
