"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import {
    updateCandidateProfile,
    updateSkills,
    addExperience,
    updateExperience,
    deleteExperience,
    addEducation,
    updateEducation,
    deleteEducation,
    updateAvatarUrl,
} from "@/app/actions/profile";
import type { Profile, Experience, Education } from "@prisma/client";
import {
    User, Briefcase, GraduationCap, Tag, Link2, Settings2,
    Plus, X, Save, Loader2, CheckCircle, Trash2, Pencil,
} from "lucide-react";
import { FileUpload } from "@/components/ui/FileUpload";

// ─── Helpers ─────────────────────────────────────────────────────────────────

function fmtDate(d: Date | null | undefined) {
    if (!d) return "";
    return new Date(d).toISOString().split("T")[0];
}

function StatusMsg({ msg }: { msg: { type: "success" | "error"; text: string } | null }) {
    if (!msg) return null;
    return (
        <div className={`flex items-center gap-2 text-sm rounded-xl px-4 py-3 ${msg.type === "success" ? "bg-emerald-50 border border-emerald-200 text-emerald-700" : "bg-red-50 border border-red-200 text-red-700"}`}>
            {msg.type === "success" && <CheckCircle className="w-4 h-4 shrink-0" />}
            {msg.text}
        </div>
    );
}

// ─── Types ───────────────────────────────────────────────────────────────────

type Tab = "basic" | "experience" | "education" | "skills" | "links" | "preferences";

interface Props {
    profile: Profile | null;
    skillNames: string[];
    experiences: Experience[];
    educationList: Education[];
    userName: string;
    avatarUrl: string;
}

const JOB_TYPES = ["Full-time", "Part-time", "Contract", "Freelance", "Internship", "Remote"];

// ─── Main Component ───────────────────────────────────────────────────────────

export function CandidateProfileEditForm({ profile, skillNames, experiences, educationList, userName, avatarUrl }: Props) {
    const router = useRouter();
    const [activeTab, setActiveTab] = useState<Tab>("basic");

    const tabs: { id: Tab; label: string; icon: React.ElementType }[] = [
        { id: "basic", label: "Basic Info", icon: User },
        { id: "skills", label: "Skills", icon: Tag },
        { id: "experience", label: "Experience", icon: Briefcase },
        { id: "education", label: "Education", icon: GraduationCap },
        { id: "preferences", label: "Job Preferences", icon: Settings2 },
        { id: "links", label: "Links", icon: Link2 },
    ];

    // ── Basic Info ────────────────────────────────────────────────────────────
    const [basicMsg, setBasicMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
    const [isBasicPending, startBasicTransition] = useTransition();

    const handleSaveBasic = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setBasicMsg(null);
        const fd = new FormData(e.currentTarget);
        startBasicTransition(async () => {
            const result = await updateCandidateProfile(fd);
            if (result?.error) setBasicMsg({ type: "error", text: result.error });
            else {
                setBasicMsg({ type: "success", text: "Basic info saved!" });
                router.refresh();
            }
        });
    };

    // ── Skills ────────────────────────────────────────────────────────────────
    const [skills, setSkills] = useState<string[]>(skillNames);
    const [newSkill, setNewSkill] = useState("");
    const [skillMsg, setSkillMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
    const [isSkillPending, startSkillTransition] = useTransition();

    const addSkill = () => {
        const s = newSkill.trim();
        if (s && !skills.includes(s)) { setSkills([...skills, s]); setNewSkill(""); }
    };

    const handleSaveSkills = () => {
        setSkillMsg(null);
        startSkillTransition(async () => {
            const result = await updateSkills(skills);
            if (result?.error) setSkillMsg({ type: "error", text: result.error });
            else { setSkillMsg({ type: "success", text: "Skills updated!" }); router.refresh(); }
        });
    };

    // ── Experience ────────────────────────────────────────────────────────────
    const [exps, setExps] = useState<Experience[]>(experiences);
    const [expMsg, setExpMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
    const [isExpPending, startExpTransition] = useTransition();
    const [showExpForm, setShowExpForm] = useState(false);
    const [editingExp, setEditingExp] = useState<Experience | null>(null);

    const handleSaveExp = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setExpMsg(null);
        const fd = new FormData(e.currentTarget);
        startExpTransition(async () => {
            const result = editingExp
                ? await updateExperience(editingExp.id, fd)
                : await addExperience(fd);
            if (result?.error) setExpMsg({ type: "error", text: result.error });
            else {
                setExpMsg({ type: "success", text: editingExp ? "Experience updated!" : "Experience added!" });
                setShowExpForm(false);
                setEditingExp(null);
                router.refresh();
            }
        });
    };

    const handleDeleteExp = (id: string) => {
        startExpTransition(async () => {
            await deleteExperience(id);
            setExps(exps.filter((e) => e.id !== id));
            router.refresh();
        });
    };

    // ── Education ─────────────────────────────────────────────────────────────
    const [eduMsg, setEduMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
    const [isEduPending, startEduTransition] = useTransition();
    const [showEduForm, setShowEduForm] = useState(false);
    const [editingEdu, setEditingEdu] = useState<Education | null>(null);

    const handleSaveEdu = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setEduMsg(null);
        const fd = new FormData(e.currentTarget);
        startEduTransition(async () => {
            const result = editingEdu
                ? await updateEducation(editingEdu.id, fd)
                : await addEducation(fd);
            if (result?.error) setEduMsg({ type: "error", text: result.error });
            else {
                setEduMsg({ type: "success", text: editingEdu ? "Education updated!" : "Education added!" });
                setShowEduForm(false);
                setEditingEdu(null);
                router.refresh();
            }
        });
    };

    const handleDeleteEdu = (id: string) => {
        startEduTransition(async () => {
            await deleteEducation(id);
            router.refresh();
        });
    };

    // ── Job Preferences ───────────────────────────────────────────────────────
    const [selectedJobTypes, setSelectedJobTypes] = useState<string[]>(profile?.job_types || []);
    const [prefMsg, setPrefMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
    const [isPrefPending, startPrefTransition] = useTransition();

    const toggleJobType = (jt: string) =>
        setSelectedJobTypes((prev) => prev.includes(jt) ? prev.filter((x) => x !== jt) : [...prev, jt]);

    const handleSavePrefs = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setPrefMsg(null);
        const fd = new FormData(e.currentTarget);
        fd.append("jobTypes", JSON.stringify(selectedJobTypes));
        // Preserve existing profile fields
        if (profile?.headline) fd.append("headline", profile.headline);
        if (profile?.location) fd.append("location", profile.location);
        if (profile?.bio) fd.append("bio", profile.bio);
        startPrefTransition(async () => {
            const result = await updateCandidateProfile(fd);
            if (result?.error) setPrefMsg({ type: "error", text: result.error });
            else { setPrefMsg({ type: "success", text: "Job preferences saved!" }); router.refresh(); }
        });
    };

    // ── Links ─────────────────────────────────────────────────────────────────
    const [linkMsg, setLinkMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
    const [isLinkPending, startLinkTransition] = useTransition();

    const handleSaveLinks = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setLinkMsg(null);
        const fd = new FormData(e.currentTarget);
        // Preserve basic info fields from current profile
        if (profile?.headline) fd.append("headline", profile.headline);
        if (profile?.location) fd.append("location", profile.location);
        if (profile?.bio) fd.append("bio", profile.bio);
        startLinkTransition(async () => {
            const result = await updateCandidateProfile(fd);
            if (result?.error) setLinkMsg({ type: "error", text: result.error });
            else { setLinkMsg({ type: "success", text: "Links saved!" }); router.refresh(); }
        });
    };

    // ─── Render ───────────────────────────────────────────────────────────────
    return (
        <div className="space-y-6">
            {/* Tab Navigation */}
            <div className="flex gap-1 overflow-x-auto border-b border-slate-200 pb-0">
                {tabs.map(({ id, label, icon: Icon }) => (
                    <button
                        key={id}
                        onClick={() => setActiveTab(id)}
                        className={`flex items-center gap-2 px-4 py-3 text-sm font-medium whitespace-nowrap border-b-2 transition-colors -mb-px ${
                            activeTab === id
                                ? "border-primary text-primary"
                                : "border-transparent text-slate-500 hover:text-slate-800 hover:border-slate-300"
                        }`}
                    >
                        <Icon className="w-4 h-4" />
                        {label}
                    </button>
                ))}
            </div>

            {/* ── BASIC INFO ─────────────────────────────────────────────────── */}
            {activeTab === "basic" && (
                <div className="bg-white rounded-2xl border border-slate-100 p-6 shadow-sm">
                    <h2 className="font-bold text-slate-900 mb-5">Basic Information</h2>
                    
                    <div className="mb-6 pb-6 border-b border-slate-100">
                        <h3 className="text-sm font-semibold text-slate-700 mb-3">Profile Photo</h3>
                        <FileUpload 
                            label="Upload Avatar (JPEG, PNG, WEBP)"
                            accept="image/jpeg, image/png, image/webp"
                            maxSizeMB={2}
                            defaultUrl={avatarUrl || undefined}
                            onUploadSuccess={async (url) => {
                                if (url) {
                                  await updateAvatarUrl(url);
                                }
                            }}
                        />
                    </div>

                    <form onSubmit={handleSaveBasic} className="space-y-5">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label className="block text-sm font-semibold text-slate-700 mb-1.5">Professional Headline</label>
                                <input name="headline" defaultValue={profile?.headline || ""} placeholder="e.g. Senior Frontend Developer"
                                    className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm transition-all" />
                            </div>
                            <div>
                                <label className="block text-sm font-semibold text-slate-700 mb-1.5">Location</label>
                                <input name="location" defaultValue={profile?.location || ""} placeholder="e.g. Lagos, Nigeria"
                                    className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm transition-all" />
                            </div>
                            <div>
                                <label className="block text-sm font-semibold text-slate-700 mb-1.5">Phone</label>
                                <input name="phone" type="tel" defaultValue={profile?.phone || ""} placeholder="+234 800 000 0000"
                                    className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm transition-all" />
                            </div>
                        </div>
                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-1.5">Professional Bio</label>
                            <textarea name="bio" defaultValue={profile?.bio || ""} rows={5} placeholder="Tell employers about yourself, your experience, and what you're passionate about..."
                                className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm transition-all resize-none" />
                        </div>
                        <StatusMsg msg={basicMsg} />
                        <button type="submit" disabled={isBasicPending}
                            className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl font-semibold text-sm hover:bg-blue-700 transition-colors shadow-lg shadow-primary/20 disabled:opacity-50">
                            {isBasicPending ? <><Loader2 className="w-4 h-4 animate-spin" /> Saving...</> : <><Save className="w-4 h-4" /> Save Basic Info</>}
                        </button>
                    </form>
                </div>
            )}

            {/* ── SKILLS ─────────────────────────────────────────────────────── */}
            {activeTab === "skills" && (
                <div className="bg-white rounded-2xl border border-slate-100 p-6 shadow-sm space-y-5">
                    <h2 className="font-bold text-slate-900">Skills</h2>
                    <p className="text-sm text-slate-500">Add skills to help match you with relevant job opportunities.</p>

                    <div className="flex gap-2">
                        <input
                            value={newSkill}
                            onChange={(e) => setNewSkill(e.target.value)}
                            onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), addSkill())}
                            placeholder="Type a skill and press Enter (e.g. React, Python)"
                            className="flex-1 px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm transition-all"
                        />
                        <button type="button" onClick={addSkill}
                            className="px-4 py-3 rounded-xl border border-slate-200 text-slate-600 hover:bg-slate-50 transition-colors">
                            <Plus className="w-4 h-4" />
                        </button>
                    </div>

                    <div className="flex flex-wrap gap-2 min-h-[40px]">
                        {skills.map((skill) => (
                            <span key={skill} className="flex items-center gap-1.5 px-3 py-1.5 bg-primary/10 text-primary border border-primary/20 rounded-full text-sm font-medium">
                                {skill}
                                <button type="button" onClick={() => setSkills(skills.filter((s) => s !== skill))} className="hover:text-red-500 transition-colors">
                                    <X className="w-3.5 h-3.5" />
                                </button>
                            </span>
                        ))}
                        {skills.length === 0 && <p className="text-sm text-slate-400 italic">No skills added yet.</p>}
                    </div>

                    <StatusMsg msg={skillMsg} />
                    <button type="button" onClick={handleSaveSkills} disabled={isSkillPending}
                        className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl font-semibold text-sm hover:bg-blue-700 transition-colors shadow-lg shadow-primary/20 disabled:opacity-50">
                        {isSkillPending ? <><Loader2 className="w-4 h-4 animate-spin" /> Saving...</> : <><Save className="w-4 h-4" /> Save Skills</>}
                    </button>
                </div>
            )}

            {/* ── EXPERIENCE ─────────────────────────────────────────────────── */}
            {activeTab === "experience" && (
                <div className="space-y-4">
                    <div className="flex items-center justify-between">
                        <h2 className="font-bold text-slate-900">Work Experience</h2>
                        {!showExpForm && (
                            <button onClick={() => { setShowExpForm(true); setEditingExp(null); }}
                                className="flex items-center gap-1.5 px-4 py-2 bg-primary text-white rounded-xl text-sm font-semibold hover:bg-blue-700 transition-colors">
                                <Plus className="w-4 h-4" /> Add Experience
                            </button>
                        )}
                    </div>

                    <StatusMsg msg={expMsg} />

                    {/* Add / Edit Form */}
                    {showExpForm && (
                        <div className="bg-white rounded-2xl border border-primary/20 p-6 shadow-sm">
                            <h3 className="font-semibold text-slate-900 mb-4">{editingExp ? "Edit Experience" : "Add Work Experience"}</h3>
                            <form onSubmit={handleSaveExp} className="space-y-4">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">Job Title *</label>
                                        <input name="title" required defaultValue={editingExp?.title || ""}
                                            placeholder="e.g. Senior Software Engineer"
                                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm" />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">Company *</label>
                                        <input name="company" required defaultValue={editingExp?.company || ""}
                                            placeholder="e.g. Acme Corp"
                                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm" />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">Location</label>
                                        <input name="location" defaultValue={editingExp?.location || ""} placeholder="e.g. Remote"
                                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm" />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">Start Date *</label>
                                        <input name="start_date" type="date" required defaultValue={fmtDate(editingExp?.start_date)}
                                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm" />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">End Date</label>
                                        <input name="end_date" type="date" defaultValue={fmtDate(editingExp?.end_date)}
                                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm" />
                                    </div>
                                    <div className="flex items-center gap-2 pt-5">
                                        <input name="is_current" type="checkbox" id="is_current" value="true"
                                            defaultChecked={editingExp?.is_current || false}
                                            className="w-4 h-4 rounded border-slate-300 text-primary" />
                                        <label htmlFor="is_current" className="text-sm font-medium text-slate-700">Currently working here</label>
                                    </div>
                                </div>
                                <div>
                                    <label className="block text-sm font-semibold text-slate-700 mb-1.5">Description</label>
                                    <textarea name="description" rows={4} defaultValue={editingExp?.description || ""}
                                        placeholder="Describe your key responsibilities and achievements..."
                                        className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm resize-none" />
                                </div>
                                <div className="flex gap-3">
                                    <button type="submit" disabled={isExpPending}
                                        className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl font-semibold text-sm hover:bg-blue-700 transition-colors disabled:opacity-50">
                                        {isExpPending ? <><Loader2 className="w-4 h-4 animate-spin" /> Saving...</> : <><Save className="w-4 h-4" /> {editingExp ? "Update" : "Add"} Experience</>}
                                    </button>
                                    <button type="button" onClick={() => { setShowExpForm(false); setEditingExp(null); }}
                                        className="px-6 py-3 rounded-xl border border-slate-200 text-slate-600 font-semibold text-sm hover:bg-slate-50 transition-colors">
                                        Cancel
                                    </button>
                                </div>
                            </form>
                        </div>
                    )}

                    {/* Experience List */}
                    <div className="space-y-3">
                        {experiences.map((exp) => (
                            <div key={exp.id} className="bg-white rounded-2xl border border-slate-100 p-5 shadow-sm flex items-start justify-between gap-4">
                                <div className="flex-1 min-w-0">
                                    <p className="font-semibold text-slate-900">{exp.title}</p>
                                    <p className="text-sm text-slate-600">{exp.company}{exp.location ? ` · ${exp.location}` : ""}</p>
                                    <p className="text-xs text-slate-400 mt-1">
                                        {fmtDate(exp.start_date)} — {exp.is_current ? "Present" : fmtDate(exp.end_date) || "—"}
                                    </p>
                                    {exp.description && <p className="text-sm text-slate-500 mt-2 line-clamp-2">{exp.description}</p>}
                                </div>
                                <div className="flex gap-2 shrink-0">
                                    <button onClick={() => { setEditingExp(exp); setShowExpForm(true); }}
                                        className="p-2 rounded-lg border border-slate-200 text-slate-500 hover:text-primary hover:border-primary/30 transition-colors">
                                        <Pencil className="w-4 h-4" />
                                    </button>
                                    <button onClick={() => handleDeleteExp(exp.id)}
                                        className="p-2 rounded-lg border border-slate-200 text-slate-500 hover:text-red-500 hover:border-red-200 transition-colors">
                                        <Trash2 className="w-4 h-4" />
                                    </button>
                                </div>
                            </div>
                        ))}
                        {experiences.length === 0 && !showExpForm && (
                            <div className="text-center py-12 text-slate-400">
                                <Briefcase className="w-10 h-10 mx-auto mb-3 opacity-30" />
                                <p className="text-sm">No work experience added yet.</p>
                            </div>
                        )}
                    </div>
                </div>
            )}

            {/* ── EDUCATION ──────────────────────────────────────────────────── */}
            {activeTab === "education" && (
                <div className="space-y-4">
                    <div className="flex items-center justify-between">
                        <h2 className="font-bold text-slate-900">Education</h2>
                        {!showEduForm && (
                            <button onClick={() => { setShowEduForm(true); setEditingEdu(null); }}
                                className="flex items-center gap-1.5 px-4 py-2 bg-primary text-white rounded-xl text-sm font-semibold hover:bg-blue-700 transition-colors">
                                <Plus className="w-4 h-4" /> Add Education
                            </button>
                        )}
                    </div>

                    <StatusMsg msg={eduMsg} />

                    {showEduForm && (
                        <div className="bg-white rounded-2xl border border-primary/20 p-6 shadow-sm">
                            <h3 className="font-semibold text-slate-900 mb-4">{editingEdu ? "Edit Education" : "Add Education"}</h3>
                            <form onSubmit={handleSaveEdu} className="space-y-4">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">Degree *</label>
                                        <input name="degree" required defaultValue={editingEdu?.degree || ""}
                                            placeholder="e.g. B.Sc. Computer Science"
                                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm" />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">Institution *</label>
                                        <input name="institution" required defaultValue={editingEdu?.institution || ""}
                                            placeholder="e.g. University of Lagos"
                                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm" />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">Field of Study</label>
                                        <input name="field" defaultValue={editingEdu?.field || ""} placeholder="e.g. Software Engineering"
                                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm" />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">Start Year</label>
                                        <input name="start_date" type="date" defaultValue={fmtDate(editingEdu?.start_date)}
                                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm" />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">End Year</label>
                                        <input name="end_date" type="date" defaultValue={fmtDate(editingEdu?.end_date)}
                                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm" />
                                    </div>
                                </div>
                                <div>
                                    <label className="block text-sm font-semibold text-slate-700 mb-1.5">Notes</label>
                                    <textarea name="description" rows={3} defaultValue={editingEdu?.description || ""}
                                        placeholder="Honors, activities, relevant coursework..."
                                        className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm resize-none" />
                                </div>
                                <div className="flex gap-3">
                                    <button type="submit" disabled={isEduPending}
                                        className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl font-semibold text-sm hover:bg-blue-700 transition-colors disabled:opacity-50">
                                        {isEduPending ? <><Loader2 className="w-4 h-4 animate-spin" /> Saving...</> : <><Save className="w-4 h-4" /> {editingEdu ? "Update" : "Add"} Education</>}
                                    </button>
                                    <button type="button" onClick={() => { setShowEduForm(false); setEditingEdu(null); }}
                                        className="px-6 py-3 rounded-xl border border-slate-200 text-slate-600 font-semibold text-sm hover:bg-slate-50 transition-colors">
                                        Cancel
                                    </button>
                                </div>
                            </form>
                        </div>
                    )}

                    <div className="space-y-3">
                        {educationList.map((edu) => (
                            <div key={edu.id} className="bg-white rounded-2xl border border-slate-100 p-5 shadow-sm flex items-start justify-between gap-4">
                                <div className="flex-1 min-w-0">
                                    <p className="font-semibold text-slate-900">{edu.degree}</p>
                                    <p className="text-sm text-slate-600">{edu.institution}{edu.field ? ` · ${edu.field}` : ""}</p>
                                    <p className="text-xs text-slate-400 mt-1">
                                        {fmtDate(edu.start_date) || "?"} — {fmtDate(edu.end_date) || "Present"}
                                    </p>
                                </div>
                                <div className="flex gap-2 shrink-0">
                                    <button onClick={() => { setEditingEdu(edu); setShowEduForm(true); }}
                                        className="p-2 rounded-lg border border-slate-200 text-slate-500 hover:text-primary hover:border-primary/30 transition-colors">
                                        <Pencil className="w-4 h-4" />
                                    </button>
                                    <button onClick={() => handleDeleteEdu(edu.id)}
                                        className="p-2 rounded-lg border border-slate-200 text-slate-500 hover:text-red-500 hover:border-red-200 transition-colors">
                                        <Trash2 className="w-4 h-4" />
                                    </button>
                                </div>
                            </div>
                        ))}
                        {educationList.length === 0 && !showEduForm && (
                            <div className="text-center py-12 text-slate-400">
                                <GraduationCap className="w-10 h-10 mx-auto mb-3 opacity-30" />
                                <p className="text-sm">No education added yet.</p>
                            </div>
                        )}
                    </div>
                </div>
            )}

            {/* ── JOB PREFERENCES ────────────────────────────────────────────── */}
            {activeTab === "preferences" && (
                <div className="bg-white rounded-2xl border border-slate-100 p-6 shadow-sm">
                    <h2 className="font-bold text-slate-900 mb-2">Job Preferences</h2>
                    <p className="text-sm text-slate-500 mb-6">Help us match you with the right opportunities.</p>
                    <form onSubmit={handleSavePrefs} className="space-y-6">
                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-3">Job Types I'm Open To</label>
                            <div className="flex flex-wrap gap-2">
                                {JOB_TYPES.map((jt) => (
                                    <button key={jt} type="button" onClick={() => toggleJobType(jt)}
                                        className={`px-4 py-2 rounded-xl border text-sm font-medium transition-all ${
                                            selectedJobTypes.includes(jt)
                                                ? "bg-primary/10 border-primary/40 text-primary"
                                                : "border-slate-200 text-slate-600 hover:border-slate-300 hover:bg-slate-50"
                                        }`}>
                                        {selectedJobTypes.includes(jt) && <CheckCircle className="w-3.5 h-3.5 inline mr-1.5" />}
                                        {jt}
                                    </button>
                                ))}
                            </div>
                        </div>
                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-1.5">Expected Salary</label>
                            <input name="salary" defaultValue={profile?.salary_expectation || ""}
                                placeholder="e.g. ₦500k–₦800k/month or $80k–$120k/year"
                                className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm transition-all" />
                        </div>
                        <StatusMsg msg={prefMsg} />
                        <button type="submit" disabled={isPrefPending}
                            className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl font-semibold text-sm hover:bg-blue-700 transition-colors shadow-lg shadow-primary/20 disabled:opacity-50">
                            {isPrefPending ? <><Loader2 className="w-4 h-4 animate-spin" /> Saving...</> : <><Save className="w-4 h-4" /> Save Preferences</>}
                        </button>
                    </form>
                </div>
            )}

            {/* ── LINKS ──────────────────────────────────────────────────────── */}
            {activeTab === "links" && (
                <div className="bg-white rounded-2xl border border-slate-100 p-6 shadow-sm">
                    <h2 className="font-bold text-slate-900 mb-5">Links & Documents</h2>
                    <form onSubmit={handleSaveLinks} className="space-y-6">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            {[
                                { name: "linkedin_url", label: "LinkedIn Profile", placeholder: "https://linkedin.com/in/yourname", defaultValue: profile?.linkedin_url },
                                { name: "github_url", label: "GitHub", placeholder: "https://github.com/yourname", defaultValue: profile?.github_url },
                                { name: "portfolio_url", label: "Portfolio / Website", placeholder: "https://yourportfolio.com", defaultValue: profile?.portfolio_url },
                            ].map(({ name, label, placeholder, defaultValue }) => (
                                <div key={name}>
                                    <label className="block text-sm font-semibold text-slate-700 mb-1.5">{label}</label>
                                    <input name={name} type="url" defaultValue={defaultValue || ""} placeholder={placeholder}
                                        className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/15 outline-none text-sm transition-all" />
                                </div>
                            ))}
                        </div>
                        
                        <div className="pt-4 border-t border-slate-100 mt-6">
                            <input type="hidden" name="resume_url" id="resume_url_hidden" defaultValue={profile?.resume_url || ""} />
                            <h3 className="text-sm font-semibold text-slate-700 mb-3">Resume Document</h3>
                            <FileUpload 
                                label="Upload latest Resume (PDF)"
                                accept="application/pdf"
                                maxSizeMB={5}
                                defaultUrl={profile?.resume_url || undefined}
                                onUploadSuccess={(url) => {
                                    const hiddenInput = document.getElementById("resume_url_hidden") as HTMLInputElement;
                                    if(hiddenInput) hiddenInput.value = url;
                                }}
                            />
                        </div>

                        <StatusMsg msg={linkMsg} />
                        <button type="submit" disabled={isLinkPending}
                            className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl font-semibold text-sm hover:bg-blue-700 transition-colors shadow-lg shadow-primary/20 disabled:opacity-50">
                            {isLinkPending ? <><Loader2 className="w-4 h-4 animate-spin" /> Saving...</> : <><Save className="w-4 h-4" /> Save Links & Documents</>}
                        </button>
                    </form>
                </div>
            )}
        </div>
    );
}
