"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Sparkles, ArrowLeft, RotateCcw, CheckCircle, MessageCircle, AlertCircle, Compass, Award } from "lucide-react";

type CountryTarget = "both" | "usa" | "canada";
type EducationLevel = "phd" | "master" | "bachelor" | "diploma";
type WorkExperience = "high" | "mid" | "low";
type LanguageLevel = "advanced" | "intermediate" | "basic";
type AchievementType = "research" | "tech" | "business" | "general";

export default function LiveEligibilityScanner() {
  const [target, setTarget] = useState<CountryTarget>("both");
  const [education, setEducation] = useState<EducationLevel>("master");
  const [experience, setExperience] = useState<WorkExperience>("mid");
  const [language, setLanguage] = useState<LanguageLevel>("intermediate");
  const [achievement, setAchievement] = useState<AchievementType>("research");
  const [analyzed, setAnalyzed] = useState(false);

  // Compute matched pathway
  const calculateResult = () => {
    let score = 75;
    let mainProgram = "";
    let reason = "";
    let recommendedCountry = "";

    if (achievement === "research" || education === "phd" || (education === "master" && experience === "high")) {
      score = 94;
      mainProgram = "ویزای نخبگان آمریکا (EB-2 NIW)";
      recommendedCountry = "ایالات متحده آمریکا 🇺🇸";
      reason = "شما واجد بالاترین امتیاز برای معافیت منافع ملی (NIW) بدون نیاز به کارفرمای حامی هستید.";
    } else if (language === "advanced" && (education === "master" || education === "bachelor") && experience !== "low") {
      score = 89;
      mainProgram = "اکسپرس انتری کانادا (Express Entry FSW)";
      recommendedCountry = "کانادا 🇨🇦";
      reason = "ترکیب مدرک دانشگاهی و زبان پیشرفته بالاترین امتیاز CRS را برای اقامت دائم کانادا به همراه دارد.";
    } else if (achievement === "tech" || achievement === "business") {
      score = 82;
      mainProgram = "جاب‌آفر استانی کانادا (PNP) یا ویزای کاری EB-3 آمریکا";
      recommendedCountry = "کانادا 🇨🇦 و آمریکا 🇺🇸";
      reason = "سوابق مهارتی و فنی شما فرصت مناسبی برای جذب اسپانسر رسمی و کارفرما فراهم می‌کند.";
    } else {
      score = 78;
      mainProgram = "ویزای تحصیلی (Study Permit) با قابلیت تبدیل به اقامت";
      recommendedCountry = "کانادا 🇨🇦 یا آمریکا 🇺🇸";
      reason = "بهترین و مطمئن‌ترین استراتژی ورود، اخذ پذیرش تحصیلی و پس از آن اخذ مجوز کار پس از فارغ‌التحصیلی است.";
    }

    return { score, mainProgram, recommendedCountry, reason };
  };

  const result = calculateResult();

  const generateWhatsAppLink = () => {
    const text = encodeURIComponent(
      `سلام وقت بخیر، ارزیابی هوشمند راویس ویزا را انجام دادم:\n` +
      `🎯 مقصد مد نظر: ${target === "usa" ? "آمریکا" : target === "canada" ? "کانادا" : "آمریکا و کانادا"}\n` +
      `🎓 مدرک: ${education}\n` +
      `💼 سابقه کار: ${experience}\n` +
      `🌐 سطح زبان: ${language}\n` +
      `🏆 زمینه فعالیت: ${achievement}\n` +
      `📌 نتیجه اولیه سیستم: ${result.mainProgram} (امتیاز تطابق: ${result.score}%)\n` +
      `لطفاً پرونده من را جهت مشاوره و بررسی دقیق مدارک در اختیار کارشناسان قرار دهید.`
    );
    return `https://wa.me/16135122792?text=${text}`;
  };

  return (
    <section id="scanner" className="py-24 px-4 sm:px-6 max-w-5xl mx-auto">
      <div className="relative rounded-3xl p-8 sm:p-12 bg-gradient-to-b from-[#0F172A] to-[#070E1A] border border-[#D4A343]/30 shadow-[0_20px_60px_rgba(0,0,0,0.6)] overflow-hidden">
        {/* Ambient Top Glow */}
        <div className="absolute top-0 left-1/2 -translate-x-1/2 w-96 h-36 bg-[#D4A343]/15 rounded-full blur-[80px] pointer-events-none" />

        {/* Header */}
        <div className="text-center max-w-2xl mx-auto mb-10 relative z-10">
          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[#D4A343]/10 border border-[#D4A343]/30 text-xs font-bold text-[#F0CE80] mb-3">
            <Sparkles className="w-3.5 h-3.5" />
            <span>ماشین ارزیابی زنده شرایط</span>
          </div>
          <h2 className="text-2xl sm:text-4xl font-black text-white tracking-tight mb-3">
            اسکن اولیه صلاحیت پرونده مهاجرتی
          </h2>
          <p className="text-xs sm:text-sm text-white/60">
            با انتخاب وضعیت فعلی خود، نزدیک‌ترین و امن‌ترین مسیر حقوقی به آمریکا یا کانادا را بدون نیاز به درج اطلاعات هویتی بسنجید.
          </p>
        </div>

        {/* Interactive Controls Grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 mb-10 relative z-10">
          {/* 1. Country Target */}
          <div className="p-4 rounded-2xl bg-white/[0.03] border border-white/8">
            <label className="block text-xs font-bold text-[#F0CE80] mb-2.5">
              ۱. اولویت کشور مقصد
            </label>
            <div className="grid grid-cols-3 gap-1.5 text-xs">
              {[
                { id: "both", label: "هر دو" },
                { id: "usa", label: "آمریکا 🇺🇸" },
                { id: "canada", label: "کانادا 🇨🇦" },
              ].map((item) => (
                <button
                  key={item.id}
                  type="button"
                  onClick={() => setTarget(item.id as CountryTarget)}
                  className={`py-2 px-1 rounded-lg font-medium transition-all ${
                    target === item.id
                      ? "bg-[#D4A343] text-[#070E1A] font-bold shadow-md"
                      : "bg-white/5 text-white/70 hover:bg-white/10"
                  }`}
                >
                  {item.label}
                </button>
              ))}
            </div>
          </div>

          {/* 2. Education */}
          <div className="p-4 rounded-2xl bg-white/[0.03] border border-white/8">
            <label className="block text-xs font-bold text-[#F0CE80] mb-2.5">
              ۲. بالاترین مقطع تحصیلی
            </label>
            <div className="grid grid-cols-2 gap-1.5 text-xs">
              {[
                { id: "phd", label: "دکتری / محقق" },
                { id: "master", label: "کارشناسی ارشد" },
                { id: "bachelor", label: "کارشناسی" },
                { id: "diploma", label: "دیپلم / کاردانی" },
              ].map((item) => (
                <button
                  key={item.id}
                  type="button"
                  onClick={() => setEducation(item.id as EducationLevel)}
                  className={`py-2 px-2 rounded-lg font-medium transition-all ${
                    education === item.id
                      ? "bg-[#D4A343] text-[#070E1A] font-bold shadow-md"
                      : "bg-white/5 text-white/70 hover:bg-white/10"
                  }`}
                >
                  {item.label}
                </button>
              ))}
            </div>
          </div>

          {/* 3. Work Experience */}
          <div className="p-4 rounded-2xl bg-white/[0.03] border border-white/8">
            <label className="block text-xs font-bold text-[#F0CE80] mb-2.5">
              ۳. سابقه کار تخصصی
            </label>
            <div className="grid grid-cols-3 gap-1.5 text-xs">
              {[
                { id: "high", label: "+۵ سال" },
                { id: "mid", label: "۲ تا ۵ سال" },
                { id: "low", label: "زیر ۲ سال" },
              ].map((item) => (
                <button
                  key={item.id}
                  type="button"
                  onClick={() => setExperience(item.id as WorkExperience)}
                  className={`py-2 px-1 rounded-lg font-medium transition-all ${
                    experience === item.id
                      ? "bg-[#D4A343] text-[#070E1A] font-bold shadow-md"
                      : "bg-white/5 text-white/70 hover:bg-white/10"
                  }`}
                >
                  {item.label}
                </button>
              ))}
            </div>
          </div>

          {/* 4. Language */}
          <div className="p-4 rounded-2xl bg-white/[0.03] border border-white/8">
            <label className="block text-xs font-bold text-[#F0CE80] mb-2.5">
              ۴. سطح زبان (انگلیسی / فرانسه)
            </label>
            <div className="grid grid-cols-3 gap-1.5 text-xs">
              {[
                { id: "advanced", label: "IELTS 7+" },
                { id: "intermediate", label: "IELTS 6-6.5" },
                { id: "basic", label: "مقدماتی" },
              ].map((item) => (
                <button
                  key={item.id}
                  type="button"
                  onClick={() => setLanguage(item.id as LanguageLevel)}
                  className={`py-2 px-1 rounded-lg font-medium transition-all ${
                    language === item.id
                      ? "bg-[#D4A343] text-[#070E1A] font-bold shadow-md"
                      : "bg-white/5 text-white/70 hover:bg-white/10"
                  }`}
                >
                  {item.label}
                </button>
              ))}
            </div>
          </div>

          {/* 5. Special Achievement */}
          <div className="p-4 rounded-2xl bg-white/[0.03] border border-white/8 sm:col-span-2">
            <label className="block text-xs font-bold text-[#F0CE80] mb-2.5">
              ۵. برجسته‌ترین دستاورد رزومه شما
            </label>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-1.5 text-xs">
              {[
                { id: "research", label: "مقاله ISI / پژوهش" },
                { id: "tech", label: "تخصص فنی / مهندسی" },
                { id: "business", label: "مدیریت / بیزینس" },
                { id: "general", label: "نیروی کاری ماهر" },
              ].map((item) => (
                <button
                  key={item.id}
                  type="button"
                  onClick={() => setAchievement(item.id as AchievementType)}
                  className={`py-2 px-2 rounded-lg font-medium transition-all ${
                    achievement === item.id
                      ? "bg-[#D4A343] text-[#070E1A] font-bold shadow-md"
                      : "bg-white/5 text-white/70 hover:bg-white/10"
                  }`}
                >
                  {item.label}
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Live Result Box */}
        <div className="relative z-10 p-6 sm:p-8 rounded-2xl bg-[#070E1A]/90 border border-emerald-500/30 flex flex-col md:flex-row items-center justify-between gap-6 shadow-2xl">
          <div className="space-y-2 text-start w-full">
            <div className="flex items-center gap-3">
              <span className="px-3 py-1 rounded-full bg-emerald-500/15 text-emerald-300 font-bold text-xs flex items-center gap-1 border border-emerald-500/25">
                <CheckCircle className="w-3.5 h-3.5" />
                <span>تطابق اولیه: {result.score}٪</span>
              </span>
              <span className="text-xs text-white/40">پیشنهاد هوشمند دپارتمان راویس</span>
            </div>

            <h3 className="text-lg sm:text-2xl font-black text-white flex items-center gap-2">
              <span>مسیر پیشنهادی:</span>
              <span className="text-[#F0CE80]">{result.mainProgram}</span>
            </h3>

            <p className="text-xs sm:text-sm text-white/70 max-w-xl leading-relaxed">
              {result.reason}
            </p>
          </div>

          {/* Action Dispatcher to WhatsApp */}
          <a
            href={generateWhatsAppLink()}
            target="_blank"
            rel="noopener noreferrer"
            className="w-full md:w-auto shrink-0 btn-pill px-6 py-3.5 rounded-full bg-gradient-to-r from-emerald-500 to-teal-400 hover:from-emerald-400 hover:to-teal-300 text-[#070E1A] font-black text-xs sm:text-sm flex items-center justify-center gap-2.5 shadow-[0_0_25px_rgba(16,185,129,0.3)] transition-all hover:scale-105 active:scale-95"
          >
            <MessageCircle className="w-4 h-4 fill-[#070E1A]" />
            <span>ارسال این نتیجه به کارشناس کانادا</span>
            <ArrowLeft className="w-4 h-4" />
          </a>
        </div>
      </div>
    </section>
  );
}
