"use client";

/**
 * AI Humanization Score panel. Shows a circular gauge (0-100) with
 * grade, expandable factor breakdown, suggestions, and a "Humanize"
 * button that rewrites content via Claude to improve the score.
 */

import { useState, useCallback } from "react";
import { ChevronDown, Sparkles, RefreshCw, Loader2 } from "lucide-react";

interface ScoringFactor { name: string; score: number; weight: number; feedback: string }
interface ScoreResult { score: number; grade: string; factors: ScoringFactor[]; suggestions: string[] }

interface Props {
  content: string;
  onContentReplace?: (humanized: string) => void;
}

const GRADE_COLORS: Record<string, { ring: string; text: string; bg: string }> = {
  "Very Human":  { ring: "#16a34a", text: "text-green-600",  bg: "bg-green-50" },
  "Mostly Human": { ring: "#3b82f6", text: "text-blue-600",   bg: "bg-blue-50" },
  "Mixed":        { ring: "#f59e0b", text: "text-amber-600",  bg: "bg-amber-50" },
  "AI-Detected":  { ring: "#f97316", text: "text-orange-600", bg: "bg-orange-50" },
  "Strongly AI":  { ring: "#ef4444", text: "text-red-600",    bg: "bg-red-50" },
};

export default function HumanizationPanel({ content, onContentReplace }: Props) {
  const [result, setResult] = useState<ScoreResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [humanizing, setHumanizing] = useState(false);
  const [expanded, setExpanded] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const runCheck = useCallback(async () => {
    if (!content || content.length < 50) return;
    setLoading(true); setError(null);
    try {
      const res = await fetch("/api/content/humanization-check", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ content, action: "score" }),
      });
      if (!res.ok) throw new Error("Scoring failed");
      setResult(await res.json());
    } catch (err) { setError(err instanceof Error ? err.message : "Failed"); }
    finally { setLoading(false); }
  }, [content]);

  const humanize = useCallback(async () => {
    if (!content) return;
    setHumanizing(true); setError(null);
    try {
      const res = await fetch("/api/content/humanization-check", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ content, action: "humanize" }),
      });
      if (!res.ok) throw new Error("Humanization failed");
      const data = await res.json();
      if (data.humanizedContent && onContentReplace) onContentReplace(data.humanizedContent);
      if (data.after) setResult(data.after);
    } catch (err) { setError(err instanceof Error ? err.message : "Failed"); }
    finally { setHumanizing(false); }
  }, [content, onContentReplace]);

  const colors = result ? GRADE_COLORS[result.grade] || GRADE_COLORS["Mixed"] : GRADE_COLORS["Mixed"];
  const dashArray = result ? `${(result.score / 100) * 169.6} 169.6` : "0 169.6";

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <div className="px-5 py-4 flex items-center gap-4">
        {/* Score ring */}
        <div className="relative w-[56px] h-[56px] shrink-0">
          <svg viewBox="0 0 64 64" className="w-[56px] h-[56px] -rotate-90">
            <circle cx="32" cy="32" r="27" fill="none" stroke="#e2e8f0" strokeWidth="5" />
            {result && <circle cx="32" cy="32" r="27" fill="none" stroke={colors.ring} strokeWidth="5" strokeLinecap="round" strokeDasharray={dashArray} />}
          </svg>
          <div className="absolute inset-0 flex flex-col items-center justify-center">
            <span className="text-base font-bold text-slate-900 leading-none">{result?.score ?? "—"}</span>
            <span className="text-[9px] text-slate-400 font-medium">/100</span>
          </div>
        </div>

        <div className="flex-1 min-w-0">
          <p className="text-sm font-bold text-slate-900">Humanization Score</p>
          {result ? (
            <span className={`inline-block text-[11px] font-bold px-2 py-0.5 rounded-full mt-1 ${colors.bg} ${colors.text}`}>{result.grade}</span>
          ) : (
            <p className="text-xs text-slate-500 mt-0.5">Check how human your content reads</p>
          )}
        </div>

        <button onClick={runCheck} disabled={loading || content.length < 50} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-200 text-[11px] font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50">
          {loading ? <Loader2 className="w-3 h-3 animate-spin" /> : <RefreshCw className="w-3 h-3" />}
          {result ? "Re-check" : "Check"}
        </button>
      </div>

      {result && (
        <>
          {/* Factor breakdown */}
          <div className="border-t border-slate-100">
            <button onClick={() => setExpanded(!expanded)} className="w-full flex items-center justify-between px-5 py-2.5 text-[11px] font-semibold text-slate-500 hover:bg-slate-50">
              <span>{result.factors.length} scoring factors</span>
              <ChevronDown className={`w-3.5 h-3.5 transition-transform ${expanded ? "rotate-180" : ""}`} />
            </button>
            {expanded && (
              <div className="px-5 pb-3 space-y-2">
                {result.factors.map((f) => (
                  <div key={f.name}>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-[11px] font-medium text-slate-600">{f.name}</span>
                      <span className={`text-[11px] font-bold ${f.score >= 70 ? "text-green-600" : f.score >= 40 ? "text-amber-600" : "text-red-500"}`}>{f.score}</span>
                    </div>
                    <div className="h-1 rounded-full bg-slate-100 overflow-hidden">
                      <div className={`h-full rounded-full ${f.score >= 70 ? "bg-green-500" : f.score >= 40 ? "bg-amber-400" : "bg-red-400"}`} style={{ width: `${f.score}%` }} />
                    </div>
                    <p className="text-[10px] text-slate-500 mt-0.5">{f.feedback}</p>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Suggestions */}
          {result.suggestions.length > 0 && (
            <div className="border-t border-slate-100 px-5 py-3">
              <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Suggestions</p>
              <ul className="space-y-1.5">
                {result.suggestions.map((s, i) => (
                  <li key={i} className="flex items-start gap-2 text-[11px] text-slate-600 leading-snug">
                    <span className="mt-1 w-1 h-1 rounded-full bg-amber-400 shrink-0" />
                    {s}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* Humanize button */}
          {result.score < 70 && onContentReplace && (
            <div className="border-t border-slate-100 px-5 py-3 bg-amber-50/50">
              <button onClick={humanize} disabled={humanizing} className="flex items-center gap-1.5 px-4 py-2 bg-brand-600 text-white text-xs font-semibold rounded-lg hover:bg-brand-700 disabled:opacity-60 w-full justify-center">
                {humanizing ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}
                {humanizing ? "Humanizing…" : "Humanize with AI"}
              </button>
              <p className="text-[10px] text-slate-500 text-center mt-1.5">Rewrites content to sound more natural while preserving headings and information</p>
            </div>
          )}
        </>
      )}

      {error && <div className="border-t border-slate-100 px-5 py-2 text-xs text-red-600">{error}</div>}
    </div>
  );
}
