import { Controller, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { Button } from "@/shared/common/ui/button";
import { Label } from "@/shared/common/ui/label";
import { ImageIcon, Loader2, ArrowLeft } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { FormFeild } from "../components/FormFeild";
import { useBranding } from "../hooks/useBranding";
import Loader from "@/record-management/components/Loader/loader";
import { toast } from "sonner";
import { Textarea } from "@/shared/common/ui/textarea";
import {
  BrandingParam,
  BrandingParamAPI,
  BrandingResponseItems,
} from "../types/brandTypes";
import {
  uploadSingle,
  uploadSingleBranding,
} from "@/record-management/services/api/newFileService";
import {
  FaFacebook,
  FaTwitter,
  FaLinkedin,
  FaInstagram,
  FaYoutube,
  FaTiktok,
  FaGlobe,
} from "react-icons/fa";
import { Send } from "lucide-react";
import { useParams, useNavigate } from "react-router-dom";

interface BrandingFormData {
  siteId: string;
  organizationNameAm: string;
  organizationNameEn: string;
  logo: FileList;
  primaryColor: string;
  secondaryColor: string;
  footerText: string;
  footerAddress: string;
  footerPhone: string;
  footerEmail: string;
  facebook: string;
  twitter: string;
  linkedin: string;
  instagram: string;
  youtube: string;
  telegram: string;
  tiktok: string;
  website: string;
  welcomeMessage: string;
  loginImage: FileList;
  favicon: FileList;
  moduleConfig: {
    dms: boolean;
    performance: boolean;
    objective: boolean;
    complaint: boolean;
  };
}
import { ReactNode } from "react";
import { Switch } from "@/shared/common/ui/switch";

type SocialInputProps = {
  id: string;
  label: string;
  placeholder: string;
  icon?: ReactNode;
  register: any;
};

const updateChangedItems = async (
  payload: BrandingParamAPI[],
  data: any,
  updateItem: any,
) => {
  if (!data?.items?.length) return;

  const itemMap = new Map<string, BrandingParamAPI>(
    data.items.map((item: BrandingParamAPI) => [item.key, item]),
  );

  const updates = payload.reduce<Promise<any>[]>((acc, item) => {
    const existing = itemMap.get(item.key);

    if (!existing) return acc;
    const isFile =
      item.key === "favicon" ||
      item.key === "logo" ||
      item.key === "loginImage";
    const valueChanged = isFile ? false : existing.value !== item.value;

    // Deep compare fileInfo because files live there
    const fileInfoChanged =
      JSON.stringify(existing.metadata ?? {}) !==
      JSON.stringify(item.fileInfo ?? {});
    const filechanged = fileInfoChanged && !!item.fileInfo?.fileName;

    if (valueChanged || filechanged) {
      acc.push(
        updateItem({
          id: existing.id,
          payload: {
            ...item,
          },
        }),
      );
    }

    return acc;
  }, []);

  await Promise.all(updates);
};
function SocialInput({
  id,
  label,
  placeholder,
  icon,
  register,
}: SocialInputProps) {
  const inputClass =
    "w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm text-slate-900 " +
    "placeholder:text-slate-400 shadow-sm transition-all " +
    "focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20 " +
    "dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100 dark:placeholder:text-slate-500";
  return (
    <div className="space-y-2">
      <Label
        htmlFor={id}
        className="text-sm font-medium text-slate-700 dark:text-slate-300">
        {label}
      </Label>

      <div className="relative">
        {icon && (
          <div className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400">
            {icon}
          </div>
        )}

        <FormFeild
          id={id}
          {...register(id)}
          placeholder={placeholder}
          className={`${inputClass} ${icon ? "pl-10" : ""}`}
        />
      </div>
    </div>
  );
}
const CustomImageUpload = ({
  label,
  preview,
  existingName,
  register,
  error,
  id,
  isRequired = false,
}: {
  label: string;
  preview: string | null;
  existingName?: string;
  register: any;
  error?: string;
  id: string;
  isRequired?: boolean;
}) => {
  const { t } = useTranslation();
  return (
    <div className="space-y-3">
      <Label
        htmlFor={id}
        className="text-sm font-medium text-slate-700 dark:text-slate-300">
        {label} {isRequired && <span className="text-red-500">*</span>}
      </Label>

      {preview ? (
        <div className="relative group overflow-hidden rounded-lg border border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900 flex items-center justify-center p-2 h-40">
          <img
            src={preview}
            alt={label}
            className="max-h-full max-w-full object-contain rounded transition-transform duration-200 group-hover:scale-105"
          />
          <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
            <Button
              type="button"
              variant="secondary"
              size="sm"
              onClick={() => window.open(preview, "_blank")}
              className="text-xs">
              {t("branding.brandAssets.viewFull")}
            </Button>
          </div>
        </div>
      ) : (
        <div className="border border-dashed border-slate-300 dark:border-slate-700 rounded-lg p-6 flex flex-col items-center justify-center bg-slate-50/50 dark:bg-slate-900/50 h-40">
          <ImageIcon className="h-8 w-8 text-slate-400 mb-2" />
          <span className="text-xs text-slate-500 dark:text-slate-400">
            {t("branding.brandAssets.noImageUploaded")}
          </span>
        </div>
      )}

      {preview && existingName && (
        <p className="text-xs text-slate-500 dark:text-slate-400 truncate text-center">
          {existingName}
        </p>
      )}

      <div className="mt-1">
        <FormFeild
          id={id}
          type="file"
          accept="image/*"
          {...register}
          error={error}
          className="cursor-pointer file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-violet-50 file:text-violet-700 hover:file:bg-violet-100 dark:file:bg-slate-800 dark:file:text-slate-200"
        />
      </div>
    </div>
  );
};
const mapFileInfo = (file: any) => ({
  fileInfo: file.fileInfo,
});

const flattenFormData = (formData: Record<string, any>): [string, any][] => {
  const entries: [string, any][] = [];
  for (const [key, value] of Object.entries(formData)) {
    if (key === "siteId" || key === "key") continue;
    if (
      value &&
      typeof value === "object" &&
      !Array.isArray(value) &&
      !(value instanceof FileList) &&
      !("fileInfo" in value)
    ) {
      for (const [subKey, subValue] of Object.entries(value)) {
        entries.push([`${key}.${subKey}`, subValue]);
      }
    } else {
      entries.push([key, value]);
    }
  }
  return entries;
};

const buildSettingsPayload = (
  formData: Record<string, any>,
  siteId: string,
  logoData?: any,
  ImgData?: any,
  faviconData?: any,
): BrandingParamAPI[] => {
  return flattenFormData(formData).map(([key, value]) => {
    const isFile = value && typeof value === "object" && "fileInfo" in value;
    const isMeta = key === "logo" || key === "loginImage" || key === "favicon";

    const fileData =
      key === "logo"
        ? logoData
        : key === "favicon"
          ? faviconData
          : key === "loginImage"
            ? ImgData
            : undefined;
    return {
      siteId,
      key,
      displayName: key,
      type: isMeta ? "file" : "value",
      value: isFile ? "" : isMeta ? key : String(value ?? ""),
      ...(fileData?.fileInfo && {
        fileInfo: fileData.fileInfo,
      }),
    };
  });
};
const Branding = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { siteId } = useParams<{ siteId: string }>();
  // Image preview states
  const [logoPreview, setLogoPreview] = useState<string | undefined>(undefined);
  const [loginImagePreview, setLoginImagePreview] = useState<
    string | undefined
  >(undefined);
  const [faviconPreview, setFaviconPreview] = useState<string | undefined>(
    undefined,
  );
  // Refs to imperatively clear the file inputs
  const logoInputRef = useRef<HTMLInputElement | null>(null);
  const loginImageInputRef = useRef<HTMLInputElement | null>(null);
  const faviconInputRef = useRef<HTMLInputElement | null>(null);
  const { data, isLoading, updateItem, createItem } = useBranding(siteId || "");
  const brandingMap = useMemo(
    () =>
      new Map<string, BrandingResponseItems>(
        data?.items?.map((item) => [item.key!, item]) ?? [],
      ),
    [data],
  );
  const defaultValues = useMemo(
    () => ({
      organizationNameAm: brandingMap.get("organizationNameAm")?.value ?? "",
      organizationNameEn: brandingMap.get("organizationNameEn")?.value ?? "",
      primaryColor: brandingMap.get("primaryColor")?.value || "#000000",
      secondaryColor: brandingMap.get("secondaryColor")?.value || "#000000",
      footerText: brandingMap.get("footerText")?.value || "",
      footerAddress: brandingMap.get("footerAddress")?.value || "",
      footerPhone: brandingMap.get("footerPhone")?.value || "",
      footerEmail: brandingMap.get("footerEmail")?.value || "",
      facebook: brandingMap.get("facebook")?.value || "",
      twitter: brandingMap.get("twitter")?.value || "",
      linkedin: brandingMap.get("linkedin")?.value || "",
      instagram: brandingMap.get("instagram")?.value || "",
      youtube: brandingMap.get("youtube")?.value || "",
      telegram: brandingMap.get("telegram")?.value || "",
      tiktok: brandingMap.get("tiktok")?.value || "",
      website: brandingMap.get("website")?.value || "",
      welcomeMessage: brandingMap.get("welcomeMessage")?.value || "",
      logo: undefined,
      loginImage: undefined,
      favicon: undefined,
      moduleConfig: {
        dms: brandingMap.get("moduleConfig.dms")?.value === "true",
        performance:
          brandingMap.get("moduleConfig.performance")?.value === "true",
        objective: brandingMap.get("moduleConfig.objective")?.value === "true",
        complaint: brandingMap.get("moduleConfig.complaint")?.value === "true",
      },
    }),
    [brandingMap],
  );

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    getValues,
    reset,
    control,
    formState: { errors },
  } = useForm<BrandingFormData>({
    defaultValues,
  });
  const clearFileInputs = () => {
    if (logoInputRef.current) logoInputRef.current.value = "";
    if (loginImageInputRef.current) loginImageInputRef.current.value = "";
    if (faviconInputRef.current) faviconInputRef.current.value = "";
    setValue("logo", undefined as any);
    setValue("loginImage", undefined as any);
    setValue("favicon", undefined as any);
  };

  useEffect(() => {
    if (!data) return;
    reset(defaultValues);
    clearFileInputs();
  }, [data, defaultValues, reset]);

  // Logo preview
  const logoFile = watch("logo")?.[0];
  useEffect(() => {
    if (logoFile) {
      const url = URL.createObjectURL(logoFile);
      setLogoPreview(url);
      return () => URL.revokeObjectURL(url);
    }
    setLogoPreview(brandingMap.get("logo")?.presigned);
  }, [logoFile, brandingMap]);

  // Login image preview
  const loginImageFile = watch("loginImage")?.[0];
  useEffect(() => {
    if (loginImageFile) {
      const url = URL.createObjectURL(loginImageFile);
      setLoginImagePreview(url);
      return () => URL.revokeObjectURL(url);
    }
    setLoginImagePreview(brandingMap.get("loginImage")?.presigned || "");
  }, [loginImageFile, brandingMap]);

  // Favicon preview
  const faviconFile = watch("favicon")?.[0];
  useEffect(() => {
    if (faviconFile) {
      const url = URL.createObjectURL(faviconFile);
      setFaviconPreview(url);
      return () => URL.revokeObjectURL(url);
    }
    setFaviconPreview(brandingMap.get("favicon")?.presigned || "");
  }, [faviconFile, brandingMap]);

  const onSubmit = async (formData: BrandingFormData) => {
    setIsSubmitting(true);
    try {
      const logoFile = formData.logo?.[0];
      const loginImgFile = formData.loginImage?.[0];
      const faviconImgFile = formData.favicon?.[0];
      let logoData = null;
      let ImgData = null;
      let faviconData = null;

      // -------------------- LOGO --------------------
      if (logoFile) {
        const uploaded = await uploadSingleBranding(logoFile);
        logoData = mapFileInfo(uploaded);
      } else {
        // Keep existing fileInfo intact — do NOT overwrite with empty
        const existingItem = brandingMap.get("logo");
        if (!existingItem?.metadata || !existingItem.presigned) {
          throw new Error("Logo is required but missing");
        }
        logoData = existingItem.metadata ?? {};
      }

      // -------------------- FAVICON --------------------
      if (faviconImgFile) {
        const uploaded = await uploadSingleBranding(faviconImgFile);

        faviconData = mapFileInfo(uploaded);
      } else {
        const existingItem = brandingMap.get("favicon");
        if (!existingItem?.metadata || !existingItem.presigned) {
          throw new Error("favicon is required but missing");
        }
        faviconData = existingItem.metadata ?? {};
      }

      // -------------------- LOGIN IMAGE --------------------
      if (loginImgFile) {
        const uploaded = await uploadSingleBranding(loginImgFile);
        ImgData = mapFileInfo(uploaded);
      } else {
        const existingItem = brandingMap.get("loginImage");
        if (!existingItem?.metadata || !existingItem.presigned) {
          throw new Error("Login image is required but missing");
        }
        ImgData = existingItem.metadata ?? {};
      }

      const payload: BrandingParamAPI[] = buildSettingsPayload(
        formData,
        siteId || "",
        logoData,
        ImgData,
        faviconData,
      );

      if (data?.count === 0) {
        await createItem(payload);
      } else {
        await updateChangedItems(payload, data, updateItem);
      }

      // Clear file inputs so stale filenames are removed
      clearFileInputs();
      toast.success(t("branding.success"));
    } catch (error) {
      toast.error(t("branding.error"));
    } finally {
      setIsSubmitting(false);
    }
  };

  if (isLoading) {
    return <Loader />;
  }

  return (
    <div className="mx-auto max-w-7xl p-6 lg:p-8">
      <div className="mb-8">
        <Button
          type="button"
          variant="ghost"
          size="sm"
          onClick={() => navigate(-1)}
          className="mb-4">
          <ArrowLeft className="h-4 w-4 mr-2" />
          {t("common.back")}
        </Button>
        <h1 className="text-3xl font-bold text-slate-900 dark:text-white">
          {t("branding.title")}
        </h1>
        <p className="mt-2 text-sm text-slate-500 dark:text-slate-400">
          {t("branding.description")}
        </p>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-8">
        {/* Organization */}
        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-800 dark:bg-slate-950">
          <h2 className="mb-6 text-lg font-semibold text-slate-900 dark:text-white">
            {t("branding.organizationInfo.title")}
          </h2>

          <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
            <div className="space-y-2">
              <Label
                htmlFor="organizationNameAm"
                className="text-sm font-medium text-slate-700 dark:text-slate-300">
                {t("branding.organizationInfo.nameAm")}
              </Label>
              <FormFeild
                id="organizationNameAm"
                {...register("organizationNameAm", {
                  required: t("branding.validation.nameAmRequired"),
                })}
                error={errors.organizationNameAm?.message}
                placeholder={t("branding.organizationInfo.nameAmPlaceholder")}
                className="rounded-xl border-slate-300 dark:border-slate-700 dark:bg-slate-900 focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20"
              />
            </div>

            <div className="space-y-2">
              <Label
                htmlFor="organizationNameEn"
                className="text-sm font-medium text-slate-700 dark:text-slate-300">
                {t("branding.organizationInfo.nameEn")}
              </Label>
              <FormFeild
                id="organizationNameEn"
                {...register("organizationNameEn", {
                  required: t("branding.validation.nameEnRequired"),
                })}
                error={errors.organizationNameEn?.message}
                placeholder={t("branding.organizationInfo.nameEnPlaceholder")}
                className="rounded-xl border-slate-300 dark:border-slate-700 dark:bg-slate-900 focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20"
              />
            </div>
          </div>
        </div>

        {/* Brand Assets */}
        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-800 dark:bg-slate-950">
          <h2 className="mb-6 text-lg font-semibold text-slate-900 dark:text-white">
            {t("branding.brandAssets.title")}
          </h2>

          <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
            <div className="rounded-xl border border-dashed border-slate-300 p-4 dark:border-slate-700">
              <CustomImageUpload
                label={t("branding.brandAssets.logo")}
                preview={logoPreview ? logoPreview : null}
                existingName={brandingMap.get("logo")?.metadata?.originalname}
                register={{
                  ...register("logo"),
                  ref: (el: HTMLInputElement | null) => {
                    register("logo").ref(el);
                    logoInputRef.current = el;
                  },
                }}
                error={errors.logo?.message}
                id="logo"
                isRequired={!brandingMap.get("logo")?.metadata?.originalname}
              />
            </div>

            <div className="rounded-xl border border-dashed border-slate-300 p-4 dark:border-slate-700">
              <CustomImageUpload
                label={t("branding.brandAssets.loginImage")}
                preview={loginImagePreview ? loginImagePreview : null}
                existingName={
                  brandingMap.get("loginImage")?.metadata?.originalname
                }
                register={{
                  ...register("loginImage"),
                  ref: (el: HTMLInputElement | null) => {
                    register("loginImage").ref(el);
                    loginImageInputRef.current = el;
                  },
                }}
                error={errors.loginImage?.message}
                id="loginImage"
                isRequired={false}
              />
            </div>

            <div className="rounded-xl border border-dashed border-slate-300 p-4 dark:border-slate-700">
              <CustomImageUpload
                label={t("branding.brandAssets.favicon")}
                preview={faviconPreview ? faviconPreview : null}
                existingName={
                  brandingMap.get("favicon")?.metadata?.originalname
                }
                register={{
                  ...register("favicon"),
                  ref: (el: HTMLInputElement | null) => {
                    register("favicon").ref(el);
                    faviconInputRef.current = el;
                  },
                }}
                error={errors.favicon?.message}
                id="favicon"
                isRequired={false}
              />
            </div>
          </div>
        </div>

        {/* Brand Colors */}
        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-800 dark:bg-slate-950">
          <h2 className="mb-6 text-lg font-semibold text-slate-900 dark:text-white">
            {t("branding.brandColors.title")}
          </h2>

          <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
            <div className="rounded-xl border border-slate-200 p-4 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-900/50">
              <Label
                htmlFor="primaryColor"
                className="text-sm font-medium text-slate-700 dark:text-slate-300">
                {t("branding.brandColors.primary")}
              </Label>

              <div className="mt-3 flex items-center gap-4">
                <input
                  id="primaryColor"
                  type="color"
                  {...register("primaryColor", {
                    required: t("branding.validation.primaryColorRequired"),
                  })}
                  className="h-14 w-14 cursor-pointer rounded-lg border border-slate-200 dark:border-slate-700"
                />

                <div>
                  <p className="text-xs text-slate-500">
                    {t("branding.brandColors.brandPrimary")}
                  </p>
                  <p className="font-mono font-medium text-slate-900 dark:text-white">
                    {watch("primaryColor") || "#000000"}
                  </p>
                </div>
              </div>
              {errors.primaryColor && (
                <p className="text-xs text-red-500 mt-1">
                  {errors.primaryColor.message}
                </p>
              )}
            </div>

            <div className="rounded-xl border border-slate-200 p-4 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-900/50">
              <Label
                htmlFor="secondaryColor"
                className="text-sm font-medium text-slate-700 dark:text-slate-300">
                {t("branding.brandColors.secondary")}
              </Label>

              <div className="mt-3 flex items-center gap-4">
                <input
                  id="secondaryColor"
                  type="color"
                  {...register("secondaryColor")}
                  className="h-14 w-14 cursor-pointer rounded-lg border border-slate-200 dark:border-slate-700"
                />

                <div>
                  <p className="text-xs text-slate-500">
                    {t("branding.brandColors.brandSecondary")}
                  </p>
                  <p className="font-mono font-medium text-slate-900 dark:text-white">
                    {watch("secondaryColor") || "#000000"}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="grid grid-cols-1 gap-8 xl:grid-cols-2">
          <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-800 dark:bg-slate-950">
            <h2 className="mb-6 text-lg font-semibold text-slate-900 dark:text-white">
              {t("branding.welcomeMessage.title")}
            </h2>
            <div className="space-y-2">
              <Label
                htmlFor="welcomeMessage"
                className="text-sm font-medium text-slate-700 dark:text-slate-300">
                {t("branding.welcomeMessage.label")}
              </Label>
              <Textarea
                id="welcomeMessage"
                {...register("welcomeMessage", {
                  required: t("branding.validation.welcomeMessageRequired"),
                })}
                rows={4}
                placeholder={t("branding.welcomeMessage.placeholder")}
                className="w-full rounded-xl border-slate-300 dark:border-slate-700 dark:bg-slate-900 text-slate-900 dark:text-white min-h-[120px] focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20"
              />
              {errors.welcomeMessage && (
                <p className="text-xs text-red-500 mt-1">
                  {errors.welcomeMessage.message}
                </p>
              )}
            </div>
          </div>

          <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-800 dark:bg-slate-950">
            <h2 className="mb-6 text-lg font-semibold text-slate-900 dark:text-white">
              {t("branding.footerText.title")}
            </h2>
            <div className="space-y-2">
              <Label
                htmlFor="footerText"
                className="text-sm font-medium text-slate-700 dark:text-slate-300">
                {t("branding.footerText.label")}
              </Label>
              <Textarea
                id="footerText"
                {...register("footerText", {
                  required: t("branding.validation.footerTextRequired"),
                })}
                rows={4}
                placeholder={t("branding.footerText.placeholder")}
                className="w-full rounded-xl border-slate-300 dark:border-slate-700 dark:bg-slate-900 text-slate-900 dark:text-white min-h-[120px] focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20"
              />
              {errors.footerText && (
                <p className="text-xs text-red-500 mt-1">
                  {errors.footerText.message}
                </p>
              )}
            </div>
          </div>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-800 dark:bg-slate-950">
          <h2 className="mb-6 text-lg font-semibold text-slate-900 dark:text-white">
            {t("branding.landingPage.title")}
          </h2>

          <div className="flex items-center justify-between rounded-xl border border-slate-200 p-4 dark:border-slate-800">
            <div>
              <Label
                htmlFor="moduleConfig.complaint"
                className="text-sm font-medium text-slate-900 dark:text-slate-100">
                {t("branding.landingPage.complaint")}
              </Label>
              <p className="text-sm text-slate-500 dark:text-slate-400">
                {t("branding.landingPage.complaintDescription")}
              </p>
            </div>

            <Controller
              control={control}
              name="moduleConfig.complaint"
              render={({ field }) => (
                <Switch
                  id="moduleConfig.complaint"
                  checked={field.value}
                  onCheckedChange={field.onChange}
                />
              )}
            />
          </div>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-800 dark:bg-slate-950">
          <h2 className="mb-6 text-lg font-semibold text-slate-900 dark:text-white">
            {t("branding.modules.title")}
          </h2>

          <div className="space-y-4">
            <div className="flex items-center justify-between rounded-xl border border-slate-200 p-4 dark:border-slate-800">
              <div>
                <Label
                  htmlFor="moduleConfig.dms"
                  className="text-sm font-medium text-slate-900 dark:text-slate-100">
                  {t("branding.modules.dms")}
                </Label>
                <p className="text-sm text-slate-500 dark:text-slate-400">
                  {t("branding.modules.dmsDescription")}
                </p>
              </div>

              <Controller
                control={control}
                name="moduleConfig.dms"
                render={({ field }) => (
                  <Switch
                    id="moduleConfig.dms"
                    checked={field.value}
                    onCheckedChange={field.onChange}
                  />
                )}
              />
            </div>

            <div className="flex items-center justify-between rounded-xl border border-slate-200 p-4 dark:border-slate-800">
              <div>
                <Label
                  htmlFor="moduleConfig.performance"
                  className="text-sm font-medium text-slate-900 dark:text-slate-100">
                  {t("branding.modules.performance")}
                </Label>
                <p className="text-sm text-slate-500 dark:text-slate-400">
                  {t("branding.modules.performanceDescription")}
                </p>
              </div>

              <Controller
                control={control}
                name="moduleConfig.performance"
                render={({ field }) => (
                  <Switch
                    id="moduleConfig.performance"
                    checked={field.value}
                    onCheckedChange={field.onChange}
                  />
                )}
              />
            </div>

            <div className="flex items-center justify-between rounded-xl border border-slate-200 p-4 dark:border-slate-800">
              <div>
                <Label
                  htmlFor="moduleConfig.objective"
                  className="text-sm font-medium text-slate-900 dark:text-slate-100">
                  {t("branding.modules.objective")}
                </Label>
                <p className="text-sm text-slate-500 dark:text-slate-400">
                  {t("branding.modules.objectiveDescription")}
                </p>
              </div>

              <Controller
                control={control}
                name="moduleConfig.objective"
                render={({ field }) => (
                  <Switch
                    id="moduleConfig.objective"
                    checked={field.value}
                    onCheckedChange={field.onChange}
                  />
                )}
              />
            </div>
          </div>
        </div>
        {/* Contact Information */}
        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-800 dark:bg-slate-950">
          <h2 className="mb-6 text-lg font-semibold text-slate-900 dark:text-white">
            {t("branding.contactInfo.title")}
          </h2>

          <div className="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3">
            <div className="space-y-2">
              <Label
                htmlFor="footerAddress"
                className="text-sm font-medium text-slate-700 dark:text-slate-300">
                {t("branding.contactInfo.address")}
              </Label>
              <FormFeild
                id="footerAddress"
                {...register("footerAddress", {
                  required: t("branding.validation.addressRequired"),
                })}
                error={errors.footerAddress?.message}
                placeholder={t("branding.contactInfo.addressPlaceholder")}
                className="rounded-xl border-slate-300 dark:border-slate-700 dark:bg-slate-900 focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20"
              />
            </div>
            <div className="space-y-2">
              <Label
                htmlFor="footerPhone"
                className="text-sm font-medium text-slate-700 dark:text-slate-300">
                {t("branding.contactInfo.phone")}
              </Label>
              <FormFeild
                id="footerPhone"
                {...register("footerPhone", {
                  required: t("branding.validation.phoneRequired"),
                })}
                error={errors.footerPhone?.message}
                placeholder={t("branding.contactInfo.phonePlaceholder")}
                className="rounded-xl border-slate-300 dark:border-slate-700 dark:bg-slate-900 focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20"
              />
            </div>
            <div className="space-y-2">
              <Label
                htmlFor="footerEmail"
                className="text-sm font-medium text-slate-700 dark:text-slate-300">
                {t("branding.contactInfo.email")}
              </Label>
              <FormFeild
                id="footerEmail"
                type="email"
                {...register("footerEmail", {
                  required: t("branding.validation.emailRequired"),
                  pattern: {
                    value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                    message: t("branding.validation.invalidEmail"),
                  },
                })}
                error={errors.footerEmail?.message}
                placeholder={t("branding.contactInfo.emailPlaceholder")}
                className="rounded-xl border-slate-300 dark:border-slate-700 dark:bg-slate-900 focus:border-violet-500 focus:ring-2 focus:ring-violet-500/20"
              />
            </div>
          </div>
        </div>

        {/* Social Media */}
        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-800 dark:bg-slate-950">
          <h2 className="mb-6 text-lg font-semibold text-slate-900 dark:text-white">
            {t("branding.socialMedia.title")}
          </h2>

          <div className="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-4">
            <SocialInput
              id="facebook"
              label={t("branding.socialMedia.facebook")}
              placeholder={t("branding.socialMedia.facebookPlaceholder")}
              register={register}
              icon={<FaFacebook className="h-4 w-4 text-primary-600" />}
            />

            <SocialInput
              id="twitter"
              label={t("branding.socialMedia.twitter")}
              placeholder={t("branding.socialMedia.twitterPlaceholder")}
              register={register}
              icon={<FaTwitter className="h-4 w-4 text-primary-500" />}
            />

            <SocialInput
              id="linkedin"
              label={t("branding.socialMedia.linkedin")}
              placeholder={t("branding.socialMedia.linkedinPlaceholder")}
              register={register}
              icon={<FaLinkedin className="h-4 w-4 text-primary-700" />}
            />

            <SocialInput
              id="instagram"
              label={t("branding.socialMedia.instagram")}
              placeholder={t("branding.socialMedia.instagramPlaceholder")}
              register={register}
              icon={<FaInstagram className="h-4 w-4 text-pink-500" />}
            />

            <SocialInput
              id="youtube"
              label={t("branding.socialMedia.youtube")}
              placeholder={t("branding.socialMedia.youtubePlaceholder")}
              register={register}
              icon={<FaYoutube className="h-4 w-4 text-red-600" />}
            />

            <SocialInput
              id="telegram"
              label={t("branding.socialMedia.telegram")}
              placeholder={t("branding.socialMedia.telegramPlaceholder")}
              register={register}
              icon={<Send className="h-4 w-4 text-primary-500" />}
            />

            <SocialInput
              id="tiktok"
              label={t("branding.socialMedia.tiktok")}
              placeholder={t("branding.socialMedia.tiktokPlaceholder")}
              register={register}
              icon={<FaTiktok className="h-4 w-4 text-black dark:text-white" />}
            />

            <SocialInput
              id="website"
              label={t("branding.socialMedia.website")}
              placeholder={t("branding.socialMedia.websitePlaceholder")}
              register={register}
              icon={<FaGlobe className="h-4 w-4 text-slate-500" />}
            />
          </div>
        </div>

        {/* Sticky Save */}
        <div className="sticky bottom-0 z-20 pb-4">
          <div className="flex justify-between rounded-2xl border border-slate-200 bg-white/80 p-4 backdrop-blur dark:border-slate-700 dark:bg-slate-950/80">
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate(-1)}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              {t("common.back")}
            </Button>
            <Button
              type="submit"
              disabled={isSubmitting}
              className="
              min-w-[180px]
              rounded-xl
              bg-gradient-to-r
              from-violet-600
              to-purple-600
              text-white
              shadow-lg
              hover:from-violet-700
              hover:to-purple-700
            ">
              {isSubmitting ? (
                <span className="flex items-center gap-2">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  {t("branding.savingButton")}
                </span>
              ) : (
                t("branding.saveButton")
              )}
            </Button>
          </div>
        </div>
      </form>
    </div>
  );
};
export default Branding;
