"use client";

/**
 * CTA Optimizer Panel — analyzes conversion data and recommends
 * optimal CTA text, type, and position via AI.
 */

import { useState } from "react";
import { Sparkles, Loader2, Check, Zap } from "lucide-react";

interface CTARecommendation {
  recommendedText: string;
  recommendedType: "form" | "phone" | "both";
  recommendedPosition: "hero" | "sticky_bottom" | "after_testimonials";
  reasoning: string;
  alternatives: string[];
}

interface Props {
  brandId: string;
  currentCTA: string;
  onApply: (text: string) => void;
}

export default function CTAOptimizerPanel({ brandId, currentCTA, onApply }: Props) {
  const [loading, setLoading] = useState(false);
  const [rec, setRec] = useState<CTARecommendation | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [applied, setApplied] = useState<string | null>(null);

  async function optimize() {
    setLoading(true); setError(null); setRec(null);
    try {
      const res = await fetch("/api/page-studio/optimize-cta", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId, currentCTA }),
      });
      if (!res.ok) { const d = await res.json().catch(() => ({})); throw new Error(d.error || "Failed"); }
      setRec(await res.json());
    } catch (err) {
      setError(err instanceof Error ? err.message : "Optimization failed");
    } finally { setLoading(false); }
  }

  function handleApply(text: string) {
    onApply(text);
    setApplied(text);
    setTimeout(() => setApplied(null), 1500);
  }

  return (
    <div className="border border-slate-200 rounded-xl p-3 bg-gradient-to-b from-violet-50/50 to-white">
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center gap-1.5">
          <Zap className="w-3.5 h-3.5 text-violet-600" />
          <span className="text-[11px] font-bold text-slate-700">CTA Optimizer</span>
        </div>
        <button onClick={optimize} disabled={loading}
          className="flex items-center gap-1 px-2.5 py-1 bg-violet-600 text-white text-[10px] font-semibold rounded-md hover:bg-violet-700 disabled:opacity-50">
          {loading ? <Loader2 className="w-3 h-3 animate-spin" /> : <Sparkles className="w-3 h-3" />}
          {loading ? "Analyzing…" : "Optimize"}
        </button>
      </div>

      {error && <p className="text-[10px] text-red-600 mt-1">{error}</p>}

      {rec && (
        <div className="space-y-2.5 mt-2">
          {/* Main recommendation */}
          <div className="bg-white border border-violet-200 rounded-lg p-2.5">
            <div className="flex items-center justify-between mb-1">
              <span className="text-[10px] font-bold uppercase tracking-widest text-violet-600">Recommended</span>
              <span className="text-[9px] font-semibold text-slate-400 capitalize">{rec.recommendedType} · {rec.recommendedPosition.replace(/_/g, " ")}</span>
            </div>
            <p className="text-sm font-bold text-slate-900 mb-1">&ldquo;{rec.recommendedText}&rdquo;</p>
            <p className="text-[11px] text-slate-500 leading-snug mb-2">{rec.reasoning}</p>
            <button onClick={() => handleApply(rec.recommendedText)}
              className="flex items-center gap-1 px-3 py-1.5 bg-violet-600 text-white text-[10px] font-semibold rounded-md hover:bg-violet-700">
              {applied === rec.recommendedText ? <Check className="w-3 h-3" /> : null}
              {applied === rec.recommendedText ? "Applied" : "Apply"}
            </button>
          </div>

          {/* Alternatives */}
          {rec.alternatives.length > 0 && (
            <div>
              <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1.5">Alternatives</p>
              <div className="space-y-1">
                {rec.alternatives.map((alt, i) => (
                  <button key={i} onClick={() => handleApply(alt)}
                    className="w-full flex items-center justify-between px-2.5 py-2 rounded-lg border border-slate-100 hover:border-violet-200 hover:bg-violet-50/50 transition-colors text-left">
                    <span className="text-xs text-slate-700">&ldquo;{alt}&rdquo;</span>
                    {applied === alt
                      ? <Check className="w-3 h-3 text-green-600 shrink-0" />
                      : <span className="text-[10px] text-violet-600 font-semibold shrink-0">Apply</span>
                    }
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
