"use client";

import React, { useEffect, useRef, useState, ChangeEvent } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useForm, FieldPath } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  fetchProfile,
  updateProfile,
  resetUpdateState,
} from "@/store/slices/profileSlice";
import { firebaseUpdatePassword } from "@/services/firebaseAuthService";
import {
  ArrowLeft,
  Camera,
  Globe,
  Link2,
  MapPin,
  Building2,
  Bell,
  Lock,
  CheckCircle,
  ChevronDown,
  User,
  AtSign,
  ShieldCheck,
  Upload,
  type LucideIcon,
} from "lucide-react";

/* ─── Zod schema ─────────────────────────────────────────────────────────── */
const schema = z.object({
  full_name: z.string().min(1, "Required"),
  channel_name: z.string().min(1, "Required"),
  email: z.string().email("Invalid email"),
  description: z.string().optional(),
  password: z.string().optional(),
  current_password: z.string().optional(),
  website: z.string().optional(),
  facebook_url: z.string().optional(),
  instagram_url: z.string().optional(),
  twitter_url: z.string().optional(),
  address: z.string().optional(),
  city: z.string().optional(),
  state: z.string().optional(),
  country: z.string().optional(),
  pincode: z.string().optional(),
  bank_name: z.string().optional(),
  bank_code: z.string().optional(),
  bank_address: z.string().optional(),
  ifsc_no: z.string().optional(),
  account_no: z.string().optional(),
  push_notification_status: z.string().optional(),
  send_mail_status: z.string().optional(),
  image: z.string().optional(),
  cover_img: z.string().optional(),
}).refine(
  (data) => !data.password || data.password.length >= 6,
  { message: "Minimum 6 characters", path: ["password"] },
).refine(
  (data) => !data.password || !!data.current_password,
  { message: "Enter your current password to set a new one", path: ["current_password"] },
);
type FormValues = z.infer<typeof schema>;

/* ─── Field component ────────────────────────────────────────────────────── */
const Field = React.forwardRef<
  HTMLInputElement | HTMLTextAreaElement,
  {
    label: string;
    icon?: LucideIcon;
    error?: string;
    hint?: string;
    textarea?: boolean;
  } & React.InputHTMLAttributes<HTMLInputElement | HTMLTextAreaElement>
>(({ label, icon: Icon, error, hint, textarea, ...props }, ref) => {
  const base: React.CSSProperties = {
    background: "var(--btn-ghost)",
    border: `1.5px solid ${error ? "#ef4444" : "var(--border)"}`,
    color: "var(--text-primary)",
    caretColor: "var(--accent)",
    borderRadius: 10,
    fontSize: 13,
    width: "100%",
    outline: "none",
    paddingLeft: Icon ? 36 : 12,
    paddingRight: 12,
    paddingTop: textarea ? 10 : 0,
    paddingBottom: textarea ? 10 : 0,
    height: textarea ? "auto" : 42,
    resize: textarea ? "vertical" : undefined,
    minHeight: textarea ? 80 : undefined,
  };

  return (
    <div className="flex flex-col gap-1.5">
      <label
        style={{
          fontSize: 11,
          fontWeight: 600,
          letterSpacing: "0.1em",
          textTransform: "uppercase",
          color: "#888",
        }}
      >
        {label}
      </label>

      <div className="relative">
        {Icon && (
          <span
            className="absolute left-2.5 top-1/2 -translate-y-1/2 pointer-events-none"
            style={{ color: "#555", display: "flex" }}
          >
            <Icon size={14} />
          </span>
        )}

        {textarea ? (
          <textarea
            ref={ref as React.Ref<HTMLTextAreaElement>}
            style={base}
            {...(props as React.TextareaHTMLAttributes<HTMLTextAreaElement>)}
          />
        ) : (
          <input
            ref={ref as React.Ref<HTMLInputElement>}
            style={base}
            {...(props as React.InputHTMLAttributes<HTMLInputElement>)}
          />
        )}
      </div>

      {error && <p style={{ fontSize: 11, color: "#ef4444" }}>{error}</p>}

      {hint && !error && <p style={{ fontSize: 11, color: "#555" }}>{hint}</p>}
    </div>
  );
});

Field.displayName = "Field";
/* ─── Toggle switch ──────────────────────────────────────────────────────── */
function Toggle({
  checked,
  onChange,
  label,
}: {
  checked: boolean;
  onChange: (v: boolean) => void;
  label: string;
}) {
  return (
    <label className="flex items-center justify-between cursor-pointer gap-4 py-2">
      <span style={{ fontSize: 13, color: "#ccc" }}>{label}</span>
      <button
        type="button"
        onClick={() => onChange(!checked)}
        role="switch"
        aria-checked={checked}
        className="relative shrink-0"
        style={{
          width: 44,
          height: 24,
          borderRadius: 99,
          background: checked ? "var(--accent)" : "var(--border)",
          transition: "background 200ms ease",
          border: "none",
        }}
      >
        <span
          style={{
            position: "absolute",
            top: 3,
            left: checked ? 23 : 3,
            width: 18,
            height: 18,
            borderRadius: "50%",
            background: "#fff",
            transition: "left 200ms cubic-bezier(0.4,0,0.2,1)",
            boxShadow: "0 1px 4px rgba(0,0,0,0.3)",
          }}
        />
      </button>
    </label>
  );
}

/* ─── Section accordion ──────────────────────────────────────────────────── */
function Section({
  title,
  icon: Icon,
  defaultOpen = false,
  children,
}: {
  title: string;
  icon: LucideIcon;
  defaultOpen?: boolean;
  children: React.ReactNode;
}) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div
      className="rounded-2xl overflow-hidden"
      style={{
        background: "var(--border-soft)",
        border: "1px solid var(--border)",
      }}
    >
      <button
        type="button"
        onClick={() => setOpen((p) => !p)}
        className="w-full flex items-center justify-between px-5 py-4 transition-colors hover:bg-white/5"
      >
        <span className="flex items-center gap-3">
          <span
            className="w-8 h-8 rounded-lg flex items-center justify-center"
            style={{
              background: "rgba(var(--accent-rgb),0.12)",
              color: "var(--accent)",
            }}
          >
            <Icon size={15} />
          </span>
          <span
            style={{
              fontSize: 14,
              fontWeight: 600,
              color: "var(--text-muted)",
            }}
          >
            {title}
          </span>
        </span>
        <ChevronDown
          size={16}
          style={{
            color: "#666",
            transform: open ? "rotate(180deg)" : "none",
            transition: "transform 200ms ease",
          }}
        />
      </button>
      {open && (
        <div
          className="px-5 pb-5 flex flex-col gap-4"
          style={{ borderTop: "1px solid var(--border-soft)" }}
        >
          <div className="pt-4">{children}</div>
        </div>
      )}
    </div>
  );
}

/* ─── Image upload box ───────────────────────────────────────────────────── */
function ImageUpload({
  label,
  preview,
  onFile,
  shape = "circle",
}: {
  label: string;
  preview: string | null;
  onFile: (f: File) => void;
  shape?: "circle" | "rect";
}) {
  const ref = useRef<HTMLInputElement>(null);
  const [drag, setDrag] = useState(false);

  const handleFile = (file: File) => {
    if (file && file.type.startsWith("image/")) onFile(file);
  };

  return (
    <div className="flex flex-col items-center gap-2">
      <button
        type="button"
        onClick={() => ref.current?.click()}
        onDragOver={(e) => {
          e.preventDefault();
          setDrag(true);
        }}
        onDragLeave={() => setDrag(false)}
        onDrop={(e) => {
          e.preventDefault();
          setDrag(false);
          const f = e.dataTransfer.files[0];
          if (f) handleFile(f);
        }}
        className="relative overflow-hidden flex items-center justify-center transition-all duration-200"
        style={{
          width: shape === "circle" ? 100 : "100%",
          height: shape === "circle" ? 100 : 120,
          borderRadius: shape === "circle" ? "50%" : 12,
          border: `2px dashed ${drag ? "var(--accent)" : "var(--border)"}`,
          background: drag
            ? "rgba(var(--accent-rgb),0.08)"
            : "var(--btn-ghost)",
          boxShadow: drag ? "0 0 0 4px rgba(var(--accent-rgb),0.15)" : "none",
        }}
      >
        {preview ? (
          <Image
            src={preview}
            alt={label}
            fill
            className="object-cover"
            unoptimized
            sizes="200px"
          />
        ) : null}
        <div
          className="absolute inset-0 flex flex-col items-center justify-center gap-1"
          style={{
            background: preview ? "rgba(0,0,0,0.45)" : "transparent",
            opacity: preview ? 0 : 1,
            transition: "opacity 200ms",
          }}
        >
          <Camera size={20} style={{ color: "#777" }} />
        </div>
        {preview && (
          <div
            className="absolute inset-0 flex flex-col items-center justify-center gap-1 opacity-0 hover:opacity-100 transition-opacity duration-200"
            style={{ background: "rgba(0,0,0,0.55)" }}
          >
            <Camera size={18} style={{ color: "var(--text-muted)" }} />
            <span
              style={{
                fontSize: 10,
                color: "var(--text-muted)",
                fontWeight: 600,
              }}
            >
              Change
            </span>
          </div>
        )}
      </button>
      <span style={{ fontSize: 11, color: "#666" }}>{label}</span>
      <input
        ref={ref}
        type="file"
        accept="image/*"
        className="hidden"
        onChange={(e: ChangeEvent<HTMLInputElement>) => {
          const f = e.target.files?.[0];
          if (f) handleFile(f);
        }}
      />
    </div>
  );
}

/* ─── Main EditProfilePage ───────────────────────────────────────────────── */
export default function EditProfilePage() {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { profile, isProfileLoading, isUpdating, updateSuccess, updateError } =
    useAppSelector((s) => s.profile);

  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [coverFile, setCoverFile] = useState<File | null>(null);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
  const [coverPreview, setCoverPreview] = useState<string | null>(null);
  const [showSuccess, setShowSuccess] = useState(false);
  const [frontIdFile, setFrontIdFile] = useState<File | null>(null);
  const [backIdFile, setBackIdFile] = useState<File | null>(null);
  const [frontIdPreview, setFrontIdPreview] = useState<string | null>(null);
  const [backIdPreview, setBackIdPreview] = useState<string | null>(null);
  const frontIdRef = useRef<HTMLInputElement>(null);
  const backIdRef = useRef<HTMLInputElement>(null);
  const [passwordError, setPasswordError] = useState<string | null>(null);
  const [isSyncingPassword, setIsSyncingPassword] = useState(false);

  const {
    register,
    handleSubmit,
    reset,
    watch,
    setValue,
    formState: { errors },
  } = useForm<FormValues>({ resolver: zodResolver(schema) });

  const pushNotif = watch("push_notification_status");
  const sendMail = watch("send_mail_status");

  /* Populate form when profile loads */
  useEffect(() => {
    if (!profile) dispatch(fetchProfile());
  }, [dispatch, profile]);

  useEffect(() => {
    if (profile) {
      const p = profile as unknown as Record<string, unknown>;

      reset({
        full_name: profile.full_name ?? "",
        channel_name: profile.channel_name ?? "",
        email: profile.email ?? "",
        description: profile.description ?? "",

        website: String(p.website ?? ""),
        facebook_url: String(p.facebook_url ?? ""),
        instagram_url: String(p.instagram_url ?? ""),
        twitter_url: String(p.twitter_url ?? ""),

        address: String(p.address ?? ""),
        city: String(p.city ?? ""),
        state: String(p.state ?? ""),
        country: String(p.country ?? ""),
        pincode: String(p.pincode ?? ""),

        bank_name: String(p.bank_name ?? ""),
        bank_code: String(p.bank_code ?? ""),
        bank_address: String(p.bank_address ?? ""),
        ifsc_no: String(p.ifsc_no ?? ""),
        account_no: String(p.account_no ?? ""),

        push_notification_status: String(p.push_notification_status ?? "1"),

        send_mail_status: String(p.send_mail_status ?? "1"),
      });

      setAvatarPreview(profile.image || null);
      setCoverPreview(profile.cover_img || null);
      setFrontIdPreview(String(p.front_id_proof ?? "") || null);
      setBackIdPreview(String(p.back_id_proof ?? "") || null);
    }
  }, [profile, reset]);
  /* Handle image file selection */
  const handleAvatarFile = (f: File) => {
    setAvatarFile(f);
    setAvatarPreview(URL.createObjectURL(f));
  };
  const handleCoverFile = (f: File) => {
    setCoverFile(f);
    setCoverPreview(URL.createObjectURL(f));
  };

  /* Success state */
  useEffect(() => {
    if (updateSuccess) {
      setShowSuccess(true);
      dispatch(resetUpdateState());
      dispatch(fetchProfile());
      const t = setTimeout(() => {
        setShowSuccess(false);
        router.push("/profile");
      }, 1800);
      return () => clearTimeout(t);
    }
  }, [updateSuccess, dispatch, router]);

  const onSubmit = async (data: FormValues) => {
    setPasswordError(null);
    const { current_password, ...rest } = data;

    if (rest.password) {
      setIsSyncingPassword(true);
      try {
        await firebaseUpdatePassword(profile?.email ?? rest.email ?? "", current_password!, rest.password);
      } catch (err: unknown) {
        const code = (err as { code?: string })?.code;
        setPasswordError(
          code === "auth/wrong-password" || code === "auth/invalid-credential"
            ? "Current password is incorrect."
            : "Couldn't verify your current password. Please try again.",
        );
        setIsSyncingPassword(false);
        return;
      }
      setIsSyncingPassword(false);
    }

    dispatch(
      updateProfile({
        ...rest,
        image: avatarFile ?? undefined,
        cover_img: coverFile ?? undefined,
        front_id_proof: frontIdFile ?? undefined,
        back_id_proof: backIdFile ?? undefined,
      }),
    );
  };

  /* Reg helper with proper type */
  const r = (name: FieldPath<FormValues>) => register(name);

  if (isProfileLoading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div
          className="w-8 h-8 rounded-full border-2 animate-spin"
          style={{
            borderColor: "var(--accent)",
            borderTopColor: "transparent",
          }}
        />
      </div>
    );
  }

  return (
    <div
      className="min-h-screen px-4 sm:px-8 py-6    mx-auto"
      style={{ animation: "prof-content-in 350ms ease both" }}
    >
      {/* ── Header ──────────────────────────────────────────────────────── */}
      <div className="flex items-center gap-4 mb-8">
        <button
          type="button"
          onClick={() => router.push("/profile")}
          className="w-9 h-9 rounded-xl flex items-center justify-center transition-colors hover:bg-white/10"
          style={{ border: "1px solid var(--border)" }}
        >
          <ArrowLeft size={16} style={{ color: "#ccc" }} />
        </button>
        <div>
          <h1
            style={{
              fontSize: 22,
              fontWeight: 900,
              color: "var(--text-muted)",
              letterSpacing: "-0.03em",
            }}
          >
            Edit Profile
          </h1>
          <p style={{ fontSize: 12, color: "#666", marginTop: 2 }}>
            Update your public profile and account settings
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="grid grid-cols-1 lg:grid-cols-[280px_1fr] gap-6 items-start">
          {/* ── LEFT: Image preview panel ──────────────────────────────── */}
          <div className="lg:sticky lg:top-20 flex flex-col gap-4">
            {/* Cover image */}
            <div
              className="rounded-2xl overflow-hidden"
              style={{
                background: "var(--border-soft)",
                border: "1px solid var(--border)",
              }}
            >
              <div className="p-4">
                <p
                  style={{
                    fontSize: 11,
                    fontWeight: 600,
                    color: "#888",
                    letterSpacing: "0.1em",
                    textTransform: "uppercase",
                    marginBottom: 12,
                  }}
                >
                  Cover Photo
                </p>
                <ImageUpload
                  label="Click or drag to upload cover"
                  preview={coverPreview}
                  onFile={handleCoverFile}
                  shape="rect"
                />
              </div>

              {/* Avatar overlapping preview */}
              <div
                className="relative flex flex-col items-center pb-5"
                style={{ marginTop: -28 }}
              >
                <div
                  className="relative"
                  style={{
                    width: 88,
                    height: 88,
                    borderRadius: "50%",
                    border: "4px solid var(--bg)",
                    overflow: "hidden",
                    background: "var(--deep)",
                    boxShadow: "0 0 0 2px rgba(var(--accent-rgb),0.4)",
                  }}
                >
                  {avatarPreview ? (
                    <Image
                      src={avatarPreview}
                      alt="Avatar"
                      fill
                      className="object-cover"
                      unoptimized
                      sizes="88px"
                    />
                  ) : (
                    <div
                      className="absolute inset-0 flex items-center justify-center"
                      style={{ fontSize: 28, color: "var(--accent)" }}
                    >
                      {profile?.full_name?.charAt(0).toUpperCase() ?? "U"}
                    </div>
                  )}
                </div>
                <button
                  type="button"
                  onClick={() => {
                    const input = document.createElement("input");
                    input.type = "file";
                    input.accept = "image/*";
                    input.onchange = (e) => {
                      const f = (e.target as HTMLInputElement).files?.[0];
                      if (f) handleAvatarFile(f);
                    };
                    input.click();
                  }}
                  className="mt-3 flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors hover:bg-white/10"
                  style={{
                    border: "1px solid var(--border)",
                    color: "var(--text-muted)",
                  }}
                >
                  <Camera size={12} /> Change Photo
                </button>
              </div>
            </div>

            {/* Quick info card */}
            <div
              className="rounded-2xl p-4 flex flex-col gap-2"
              style={{
                background: "rgba(var(--accent-rgb),0.06)",
                border: "1px solid rgba(var(--accent-rgb),0.15)",
              }}
            >
              <p
                style={{
                  fontSize: 11,
                  fontWeight: 700,
                  color: "var(--accent)",
                  letterSpacing: "0.1em",
                  textTransform: "uppercase",
                }}
              >
                Profile Preview
              </p>
              <p
                style={{
                  fontSize: 13,
                  fontWeight: 700,
                  color: "var(--text-muted)",
                }}
              >
                {watch("full_name") || "—"}
              </p>
              <p style={{ fontSize: 11, color: "#888" }}>
                {watch("channel_name") || "—"}
              </p>
              <p
                style={{ fontSize: 11, color: "#666", lineHeight: 1.5 }}
                className="line-clamp-2"
              >
                {watch("description") || "No description"}
              </p>
            </div>
          </div>

          {/* ── RIGHT: Form sections ───────────────────────────────────── */}
          <div className="flex flex-col gap-4">
            {/* Public Profile */}
            <Section title="Public Profile" icon={User} defaultOpen>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <Field
                  label="Full Name"
                  icon={User}
                  error={errors.full_name?.message}
                  placeholder="Your full name"
                  {...r("full_name")}
                />
                <Field
                  label="Channel Name"
                  icon={AtSign}
                  error={errors.channel_name?.message}
                  placeholder="@your_channel"
                  {...r("channel_name")}
                />
                <Field
                  label="Email"
                  type="email"
                  icon={Globe}
                  error={errors.email?.message}
                  placeholder="you@example.com"
                  {...r("email")}
                  className="sm:col-span-2"
                />
                <div className="sm:col-span-2">
                  <Field
                    label="Bio / Description"
                    textarea
                    placeholder="Tell your audience about yourself…"
                    {...r("description")}
                  />
                </div>
              </div>
            </Section>

            {/* Social Links */}
            <Section title="Social Links" icon={Globe}>
              <div className="flex flex-col gap-4">
                <Field
                  label="Website"
                  icon={Globe}
                  placeholder="https://yoursite.com"
                  {...r("website")}
                />
                <Field
                  label="Facebook"
                  icon={Link2}
                  placeholder="https://facebook.com/you"
                  {...r("facebook_url")}
                />
                <Field
                  label="Instagram"
                  icon={Link2}
                  placeholder="https://instagram.com/you"
                  {...r("instagram_url")}
                />
                <Field
                  label="Twitter / X"
                  icon={Link2}
                  placeholder="https://twitter.com/you"
                  {...r("twitter_url")}
                />
              </div>
            </Section>

            {/* Location */}
            <Section title="Location" icon={MapPin}>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="sm:col-span-2">
                  <Field
                    label="Address"
                    icon={MapPin}
                    placeholder="Street address"
                    {...r("address")}
                  />
                </div>
                <Field label="City" placeholder="City" {...r("city")} />
                <Field
                  label="State"
                  placeholder="State / Province"
                  {...r("state")}
                />
                <Field
                  label="Country"
                  placeholder="Country"
                  {...r("country")}
                />
                <Field
                  label="Pincode"
                  placeholder="Postal code"
                  {...r("pincode")}
                />
              </div>
            </Section>

            {/* Banking */}
            <Section title="Banking Details" icon={Building2}>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <Field
                  label="Bank Name"
                  placeholder="Bank name"
                  {...r("bank_name")}
                />
                <Field
                  label="Bank Code"
                  placeholder="Bank code / SWIFT"
                  {...r("bank_code")}
                />
                <div className="sm:col-span-2">
                  <Field
                    label="Bank Address"
                    placeholder="Bank branch address"
                    {...r("bank_address")}
                  />
                </div>
                <Field
                  label="IFSC / Routing No."
                  placeholder="IFSC code"
                  {...r("ifsc_no")}
                />
                <Field
                  label="Account Number"
                  placeholder="Account number"
                  {...r("account_no")}
                />
              </div>
            </Section>

            {/* Artist Verification */}
            <Section title="Artist Verification" icon={ShieldCheck}>
              <div className="flex flex-col gap-3">
                <p style={{ fontSize: 12, color: "#888", lineHeight: 1.6 }}>
                  Upload a government-issued photo ID to verify your artist account. Both front and back are required.
                </p>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {/* Front ID */}
                  <div className="flex flex-col gap-2">
                    <span
                      style={{
                        fontSize: 11,
                        fontWeight: 600,
                        letterSpacing: "0.1em",
                        textTransform: "uppercase" as const,
                        color: "#888",
                      }}
                    >
                      Front ID Proof
                    </span>
                    <button
                      type="button"
                      onClick={() => frontIdRef.current?.click()}
                      className="relative overflow-hidden flex flex-col items-center justify-center gap-2 transition-all duration-200 hover:border-[var(--accent)]"
                      style={{
                        width: "100%",
                        height: 140,
                        borderRadius: 12,
                        border: "2px dashed var(--border)",
                        background: "var(--btn-ghost)",
                        cursor: "pointer",
                      }}
                    >
                      {frontIdPreview ? (
                        <>
                          <Image
                            src={frontIdPreview}
                            alt="Front ID"
                            fill
                            className="object-cover rounded-xl"
                            unoptimized
                            sizes="300px"
                          />
                          <div
                            className="absolute inset-0 flex flex-col items-center justify-center gap-1 opacity-0 hover:opacity-100 transition-opacity duration-200 rounded-xl"
                            style={{ background: "rgba(0,0,0,0.55)" }}
                          >
                            <Camera size={18} style={{ color: "var(--text-muted)" }} />
                            <span style={{ fontSize: 10, color: "var(--text-muted)", fontWeight: 600 }}>
                              Change
                            </span>
                          </div>
                        </>
                      ) : (
                        <>
                          <Upload size={22} style={{ color: "#555" }} />
                          <span style={{ fontSize: 11, color: "#666" }}>Click to upload</span>
                        </>
                      )}
                    </button>
                    <input
                      ref={frontIdRef}
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={(e: ChangeEvent<HTMLInputElement>) => {
                        const f = e.target.files?.[0];
                        if (f && f.type.startsWith("image/")) {
                          setFrontIdFile(f);
                          setFrontIdPreview(URL.createObjectURL(f));
                        }
                      }}
                    />
                  </div>

                  {/* Back ID */}
                  <div className="flex flex-col gap-2">
                    <span
                      style={{
                        fontSize: 11,
                        fontWeight: 600,
                        letterSpacing: "0.1em",
                        textTransform: "uppercase" as const,
                        color: "#888",
                      }}
                    >
                      Back ID Proof
                    </span>
                    <button
                      type="button"
                      onClick={() => backIdRef.current?.click()}
                      className="relative overflow-hidden flex flex-col items-center justify-center gap-2 transition-all duration-200 hover:border-[var(--accent)]"
                      style={{
                        width: "100%",
                        height: 140,
                        borderRadius: 12,
                        border: "2px dashed var(--border)",
                        background: "var(--btn-ghost)",
                        cursor: "pointer",
                      }}
                    >
                      {backIdPreview ? (
                        <>
                          <Image
                            src={backIdPreview}
                            alt="Back ID"
                            fill
                            className="object-cover rounded-xl"
                            unoptimized
                            sizes="300px"
                          />
                          <div
                            className="absolute inset-0 flex flex-col items-center justify-center gap-1 opacity-0 hover:opacity-100 transition-opacity duration-200 rounded-xl"
                            style={{ background: "rgba(0,0,0,0.55)" }}
                          >
                            <Camera size={18} style={{ color: "var(--text-muted)" }} />
                            <span style={{ fontSize: 10, color: "var(--text-muted)", fontWeight: 600 }}>
                              Change
                            </span>
                          </div>
                        </>
                      ) : (
                        <>
                          <Upload size={22} style={{ color: "#555" }} />
                          <span style={{ fontSize: 11, color: "#666" }}>Click to upload</span>
                        </>
                      )}
                    </button>
                    <input
                      ref={backIdRef}
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={(e: ChangeEvent<HTMLInputElement>) => {
                        const f = e.target.files?.[0];
                        if (f && f.type.startsWith("image/")) {
                          setBackIdFile(f);
                          setBackIdPreview(URL.createObjectURL(f));
                        }
                      }}
                    />
                  </div>
                </div>
              </div>
            </Section>

            {/* Security */}
            <Section title="Change Password" icon={Lock}>
              <Field
                label="Current Password"
                type="password"
                icon={Lock}
                placeholder="Required to set a new password"
                error={errors.current_password?.message}
                {...r("current_password")}
              />
              <Field
                label="New Password"
                type="password"
                icon={Lock}
                placeholder="Leave blank to keep current password"
                hint="Minimum 6 characters"
                error={errors.password?.message ?? passwordError ?? undefined}
                {...r("password")}
              />
            </Section>

            {/* Notifications */}
            <Section title="Notifications" icon={Bell}>
              <div
                className="flex flex-col divide-y"
                style={{ borderColor: "var(--border-soft)" }}
              >
                <Toggle
                  label="Push Notifications"
                  checked={pushNotif === "1"}
                  onChange={(v) =>
                    setValue("push_notification_status", v ? "1" : "0")
                  }
                />
                <Toggle
                  label="Email Notifications"
                  checked={sendMail === "1"}
                  onChange={(v) => setValue("send_mail_status", v ? "1" : "0")}
                />
              </div>
            </Section>

            {/* Error banner */}
            {updateError && (
              <div
                className="px-4 py-3 rounded-xl text-sm"
                style={{
                  background: "rgba(239,68,68,0.1)",
                  border: "1px solid rgba(239,68,68,0.25)",
                  color: "#ef4444",
                }}
              >
                {updateError}
              </div>
            )}

            {/* Save button */}
            <button
              type="submit"
              disabled={isUpdating || isSyncingPassword || showSuccess}
              className="w-full flex items-center justify-center gap-2 py-3.5 rounded-xl text-sm font-bold tracking-wide  transition-all duration-200 active:scale-[0.98] disabled:opacity-60"
              style={{
                background: showSuccess
                  ? "linear-gradient(90deg, #16a34a, #22c55e)"
                  : "linear-gradient(90deg, #c25e10, var(--accent), #f5943a)",
                boxShadow: showSuccess
                  ? "0 0 20px rgba(34,197,94,0.3)"
                  : "0 4px 20px rgba(var(--accent-rgb),0.25)",
                color: "var(--text-muted)",
              }}
            >
              {showSuccess ? (
                <>
                  <CheckCircle size={16} />
                  Profile Updated!
                </>
              ) : isSyncingPassword ? (
                <>
                  <span className="w-4 h-4 rounded-full border-2 border-white/30 border-t-white animate-spin" />
                  Verifying password…
                </>
              ) : isUpdating ? (
                <>
                  <span className="w-4 h-4 rounded-full border-2 border-white/30 border-t-white animate-spin" />
                  Saving…
                </>
              ) : (
                "Save Changes"
              )}
            </button>
          </div>
        </div>
      </form>
    </div>
  );
}
