import React, { useMemo, useCallback, useState, useEffect, useRef } from "react";
import { CSSBuilder } from "react-css-nocode-editor";
import { TemplateSampleSetting } from "@/user-management/services/TemplateConfiguration/types/templateTypes";
import { useTranslation } from "react-i18next";
import { ChevronDown } from "lucide-react";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { useListBulletResources } from "../hooks/useListBulletResources";
import {
  isCustomListStyleImage,
  isResourceListStyle,
  ListBulletResource,
  toResourceListStyleValue,
} from "../utils/templateResourceConstants";
import { extractListStyleResourceId } from "../utils/templateSamplePayloadUtils";
import {
  mergeCssProperties,
  omitCssProperties,
} from "../utils/cssConversion";
import {
  getDefaultLetterFontFamily,
  getDefaultLetterFontSize,
  settingSupportsListFormatting,
} from "../utils/templateSettingConstants";
import { ListStyleImageField } from "./ListStyleImageField";
import { cn } from "@/shared/lib/utils";
import {
  StyleSettingSelect,
  StyleSettingToggle,
  STYLE_INPUT_CLASS,
  STYLE_SELECT_CONTENT_CLASS,
  STYLE_SELECT_TRIGGER_CLASS,
} from "./styleSettingsUi";

const FONT_WEIGHT_OPTIONS = [
  { value: "normal", label: "Normal (400)" },
  { value: "500", label: "Medium (500)" },
  { value: "600", label: "Semi-bold (600)" },
  { value: "bold", label: "Bold (700)" },
  { value: "800", label: "Extra Bold (800)" },
  { value: "900", label: "Black (900)" },
];

const FONT_FAMILY_OPTIONS = [
  { value: "serif", label: "Serif" },
  { value: "sans-serif", label: "Sans-serif" },
  { value: "monospace", label: "Monospace" },
  { value: "cursive", label: "Cursive" },
  { value: "fantasy", label: "Fantasy" },
  { value: "Georgia, serif", label: "Georgia" },
  {
    value: "'Visual Geez Unicode', 'Visual Geez', serif",
    label: "Visual Geez",
  },
  {
    value: "'Times New Roman', Times, serif",
    label: "Times New Roman",
  },
  { value: "Arial, sans-serif", label: "Arial" },
  { value: "Verdana, sans-serif", label: "Verdana" },
  { value: "'Courier New', monospace", label: "Courier New" },
];

const TEXT_DECORATION_OPTIONS = [
  { value: "none", label: "None" },
  { value: "underline", label: "Underline" },
  { value: "overline", label: "Overline" },
  { value: "line-through", label: "Line Through" },
  { value: "underline overline", label: "Underline & Overline" },
];

const TEXT_ALIGN_OPTIONS = [
  { value: "Empty", label: "Empty" },
  { value: "left", label: "Left" },
  { value: "center", label: "Center" },
  { value: "right", label: "Right" },
  { value: "justify", label: "Justify" },
];

interface StyleSettingsEditorProps {
  setting: TemplateSampleSetting;
  index: number;
  onChange: (index: number, cssString: string) => void;
  isDefault: boolean;
  onToggleDefault: (settingId: string) => void;
  storedResourceId?: string | null;
  onListStyleResourceChange?: (resourceId: string | null) => void;
  previewLanguage?: "am" | "en";
}

const parseFontSizeParts = (
  value: string | undefined,
  fallback: string,
): { amount: string; unit: "px" | "pt" } => {
  const resolved = value || fallback;
  const match = resolved.match(/^([\d.]+)(px|pt)$/);
  return {
    amount: match?.[1] ?? "12",
    unit: match?.[2] === "px" ? "px" : "pt",
  };
};

const formatSettingTitle = (code: string) =>
  code
    .replace(/^letter-/, "")
    .replace(/-style$/, "")
    .replace(/-/g, " ")
    .replace(/\b\w/g, (char) => char.toUpperCase());

// Generate SVG data URI for disclosure-closed
const getDisclosureSVG = () => {
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><polygon points="6,4 12,8 6,12" fill="currentColor"/></svg>`;
  return `url('data:image/svg+xml;base64,${btoa(svg)}')`;
};

// CSS parser (handles data URIs)
const parseCSSString = (cssString: string): Record<string, string> => {
  const styles: Record<string, string> = {};
  let depth = 0;
  let current = '';

  const processDeclaration = (decl: string) => {
    decl = decl.trim();
    if (!decl) return;
    const colonIdx = decl.indexOf(':');
    if (colonIdx <= 0) return;
    const property = decl.slice(0, colonIdx).trim();
    const value = decl.slice(colonIdx + 1).trim();
    if (property && value) styles[property] = value;
  };

  for (let i = 0; i < cssString.length; i++) {
    const ch = cssString[i];
    if (ch === '(') depth++;
    else if (ch === ')') depth--;
    if (ch === ';' && depth === 0) {
      processDeclaration(current);
      current = '';
    } else {
      current += ch;
    }
  }
  processDeclaration(current);
  return styles;
};

// Build CSS string from object
const buildCSSString = (styles: Record<string, string>): string => {
  return Object.entries(styles)
    .map(([key, value]) => `${key}: ${value};`)
    .join(' ');
};

const normalizeStyles = (
  styles: Record<string, string>,
  bulletResources: ListBulletResource[] = [],
): Record<string, string> => {
  const normalized = { ...styles };
  const listStyle = normalized["list-style"]?.split(" ")[0];

  if (listStyle === "disclosure-closed") {
    normalized["list-style-image"] = getDisclosureSVG();
    delete normalized["list-style-type"];
    return normalized;
  }

  if (listStyle && isResourceListStyle(listStyle)) {
    const resourceId = listStyle.slice("resource:".length);
    const resource = bulletResources.find((item) => item.id === resourceId);
    normalized["list-style"] = "none";
    delete normalized["list-style-type"];
    if (resource) {
      normalized["list-style-image"] = `url('${resource.presigned}')`;
    }
    return normalized;
  }

  if (isCustomListStyleImage(normalized["list-style-image"])) {
    normalized["list-style"] = normalized["list-style"] || "none";
    delete normalized["list-style-type"];
    return normalized;
  }

  delete normalized["list-style-image"];
  return normalized;
};

const resolveListStyleSelectValue = (
  styles: Record<string, string>,
  bulletResources: ListBulletResource[],
): string => {
  const listStyle = styles["list-style"]?.split(" ")[0];
  if (listStyle && isResourceListStyle(listStyle)) {
    return listStyle;
  }

  const imageValue = styles["list-style-image"];
  if (imageValue) {
    const matchedResource = bulletResources.find(
      (resource) =>
        imageValue.includes(resource.presigned) ||
        imageValue.includes(resource.id),
    );
    if (matchedResource) {
      return toResourceListStyleValue(matchedResource.id);
    }
  }

  return listStyle || styles["list-style-type"] || "disc";
};

const STANDARD_LIST_STYLE_OPTIONS = [
  { value: "disc", label: "Bullet" },
  { value: "circle", label: "Circle" },
  { value: "square", label: "Square" },
  { value: "disclosure-closed", label: "Black Right Triangle (▶)" },
  { value: "decimal", label: "Numbers (1, 2, 3)" },
  { value: "lower-alpha", label: "Lowercase Letters (a, b, c)" },
  { value: "upper-alpha", label: "Uppercase Letters (A, B, C)" },
  { value: "lower-roman", label: "Lowercase Roman (i, ii, iii)" },
  { value: "upper-roman", label: "Uppercase Roman (I, II, III)" },
  { value: "none", label: "None" },
] as const;

const getResourceLabel = (
  resource: ListBulletResource,
  locale: "am" | "en",
) => resource.name?.[locale] || resource.name?.en || resource.id;

const ListStyleResourcePreview = ({
  resource,
  locale,
}: {
  resource: ListBulletResource;
  locale: "am" | "en";
}) => (
  <span className="flex min-w-0 items-center gap-2">
    <img
      src={resource.presigned}
      alt=""
      className="h-4 w-4 shrink-0 object-contain"
    />
    <span className="truncate">{getResourceLabel(resource, locale)}</span>
  </span>
);

export const StyleSettingsEditor: React.FC<StyleSettingsEditorProps> = ({
  setting,
  index,
  onChange,
  isDefault,
  onToggleDefault,
  storedResourceId,
  onListStyleResourceChange,
  previewLanguage = "am",
}) => {
  const { t, i18n } = useTranslation();
  const defaultFontFamily = getDefaultLetterFontFamily(previewLanguage);
  const defaultFontSize = getDefaultLetterFontSize();
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [isExpanded, setIsExpanded] = useState(() => !isDefault);
  const { resources: bulletResources, loading: bulletResourcesLoading, refetch: refetchBulletResources } =
    useListBulletResources();
  const locale = i18n.language?.startsWith("am") ? "am" : "en";
  const syncedResourceIdRef = useRef<string | null | undefined>(undefined);
  const hasInitialNormalizedRef = useRef(false);
  const hydratedResourceRef = useRef<string | null>(null);

  useEffect(() => {
    if (!isDefault) {
      setIsExpanded(true);
    }
  }, [isDefault]);

  // Get the CSS string
  const cssString = useMemo(() => {
    return typeof setting.value === "string" ? setting.value : "";
  }, [setting.value]);

  // Parse CSS string to object
  const parsedStyles = useMemo(() => {
    return parseCSSString(cssString);
  }, [cssString]);

  const fontSizeParts = useMemo(
    () => parseFontSizeParts(parsedStyles["font-size"], defaultFontSize),
    [parsedStyles, defaultFontSize],
  );

  const supportsListFormatting = useMemo(
    () => settingSupportsListFormatting(setting),
    [setting],
  );

  const advancedCssString = useMemo(
    () => omitCssProperties(cssString, ["list-style-image"]),
    [cssString],
  );

  // Detect if this is a header/footer style
  const isHeaderFooterStyle = useMemo(() => {
    const code = setting.code.toLowerCase();
    return code.includes("header") || code.includes("footer");
  }, [setting.code]);

  // Normalization helper
  const listStyleSelectValue = useMemo(
    () => resolveListStyleSelectValue(parsedStyles, bulletResources),
    [parsedStyles, bulletResources],
  );

  const selectedBulletResource = useMemo(() => {
    if (!isResourceListStyle(listStyleSelectValue)) return null;
    const resourceId = listStyleSelectValue.slice("resource:".length);
    return bulletResources.find((resource) => resource.id === resourceId) ?? null;
  }, [listStyleSelectValue, bulletResources]);

  const selectedStandardListStyle = useMemo(
    () =>
      STANDARD_LIST_STYLE_OPTIONS.find(
        (option) => option.value === listStyleSelectValue,
      ) ?? null,
    [listStyleSelectValue],
  );

  // Handle property change with special list-style-image logic
  const handlePropertyChange = useCallback(
    (property: string, value: string) => {
      let updated = { ...parsedStyles, [property]: value };

      if (property === "list-style") {
        const specialListStyles = [
          "disclosure-closed",
          "disclosure-open",
          "none",
        ];

        if (isResourceListStyle(value)) {
          const resourceId = value.slice("resource:".length);
          const resource = bulletResources.find((item) => item.id === resourceId);
          updated["list-style"] = "none";
          delete updated["list-style-type"];
          if (resource) {
            updated["list-style-image"] = `url('${resource.presigned}')`;
          }
          if (syncedResourceIdRef.current !== resourceId) {
            syncedResourceIdRef.current = resourceId;
            onListStyleResourceChange?.(resourceId);
          }
        } else if (specialListStyles.includes(value)) {
          delete updated["list-style-type"];
          if (value !== "disclosure-closed") {
            delete updated["list-style-image"];
          }
          if (syncedResourceIdRef.current !== null) {
            syncedResourceIdRef.current = null;
            onListStyleResourceChange?.(null);
          }
        } else {
          delete updated["list-style-image"];
          if (syncedResourceIdRef.current !== null) {
            syncedResourceIdRef.current = null;
            onListStyleResourceChange?.(null);
          }
        }
      }

      updated = normalizeStyles(updated, bulletResources);
      const newCssString = buildCSSString(updated);
      onChange(index, newCssString);
    },
    [parsedStyles, index, onChange, bulletResources, onListStyleResourceChange],
  );

  // Sync resourceId from existing CSS once bullet resources are available.
  // Do not call onChange here — that caused infinite update loops when presigned URLs changed.
  useEffect(() => {
    if (bulletResourcesLoading) return;

    const resourceId = extractListStyleResourceId(
      normalizeStyles(parseCSSString(cssString), bulletResources),
      bulletResources,
    );

    if (syncedResourceIdRef.current === resourceId) return;
    syncedResourceIdRef.current = resourceId;
    onListStyleResourceChange?.(resourceId);
  }, [
    bulletResourcesLoading,
    bulletResources,
    cssString,
    onListStyleResourceChange,
  ]);

  // Hydrate custom-image from stored resourceId when API returns type only.
  useEffect(() => {
    if (bulletResourcesLoading || !storedResourceId) return;
    if (hydratedResourceRef.current === storedResourceId) return;

    const current = parseCSSString(cssString);
    if (isCustomListStyleImage(current["list-style-image"])) {
      hydratedResourceRef.current = storedResourceId;
      return;
    }

    const resource = bulletResources.find(
      (item) => item.id === storedResourceId,
    );
    if (!resource) return;

    hydratedResourceRef.current = storedResourceId;
    const hydrated = normalizeStyles(
      {
        ...current,
        "list-style": "none",
        "list-style-image": `url('${resource.presigned}')`,
      },
      bulletResources,
    );
    const hydratedCss = buildCSSString(hydrated);
    if (hydratedCss !== cssString) {
      onChange(index, hydratedCss);
    }
  }, [
    bulletResourcesLoading,
    storedResourceId,
    bulletResources,
    cssString,
    index,
    onChange,
  ]);

  // One-time normalization on mount (e.g. disclosure-closed SVG).
  useEffect(() => {
    if (hasInitialNormalizedRef.current) return;
    hasInitialNormalizedRef.current = true;

    const current = parseCSSString(cssString);
    const normalized = normalizeStyles(current, bulletResources);
    const normalizedCss = buildCSSString(normalized);

    if (normalizedCss !== cssString) {
      onChange(index, normalizedCss);
    }
  }, []);

  const handleAdvancedChange = useCallback(
    (newCssString: string) => {
      const preservedListStyleImage = parsedStyles["list-style-image"];
      const mergedCssString = preservedListStyleImage
        ? mergeCssProperties(newCssString, {
            "list-style-image": preservedListStyleImage,
          })
        : newCssString;

      const normalized = normalizeStyles(
        parseCSSString(mergedCssString),
        bulletResources,
      );
      const normalizedCss = buildCSSString(normalized);

      if (normalizedCss === cssString) return;

      const resourceId = extractListStyleResourceId(normalized, bulletResources);
      if (syncedResourceIdRef.current !== resourceId) {
        syncedResourceIdRef.current = resourceId;
        onListStyleResourceChange?.(resourceId);
      }

      onChange(index, normalizedCss);
    },
    [
      index,
      onChange,
      cssString,
      parsedStyles,
      bulletResources,
      onListStyleResourceChange,
    ],
  );

  const handleReplaceListStyleImage = useCallback(
    (resourceId: string) => {
      handlePropertyChange("list-style", toResourceListStyleValue(resourceId));
    },
    [handlePropertyChange],
  );

  const handleRemoveListStyleImage = useCallback(() => {
    const updated = { ...parsedStyles };
    delete updated["list-style-image"];

    const currentListStyle = updated["list-style"]?.split(" ")[0];
    if (!currentListStyle || currentListStyle === "none") {
      updated["list-style"] = "disc";
    }

    if (syncedResourceIdRef.current !== null) {
      syncedResourceIdRef.current = null;
      onListStyleResourceChange?.(null);
    }

    const normalized = normalizeStyles(updated, bulletResources);
    onChange(index, buildCSSString(normalized));
  }, [
    parsedStyles,
    bulletResources,
    index,
    onChange,
    onListStyleResourceChange,
  ]);

  if (!setting || !setting.code || !setting.id) {
    return null;
  }

  return (
    <div
      className={cn(
        "mt-4 overflow-hidden rounded-xl border bg-white shadow-sm transition-shadow dark:bg-gray-800",
        isDefault
          ? "border-gray-200 dark:border-gray-700"
          : "border-purple-200 ring-1 ring-purple-100 dark:border-purple-800 dark:ring-purple-900/40",
      )}
    >
      <button
        type="button"
        onClick={() => setIsExpanded((current) => !current)}
        className="flex w-full items-center justify-between gap-3 px-4 py-3 text-left hover:bg-gray-50 dark:hover:bg-gray-750"
      >
        <div className="min-w-0 flex-1">
          <div className="flex flex-wrap items-center gap-2">
            <h4 className="truncate text-sm font-semibold text-gray-900 dark:text-gray-100">
              {formatSettingTitle(setting.code)}
            </h4>
            <span className="rounded-md bg-gray-100 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-gray-500 dark:bg-gray-700 dark:text-gray-400">
              {setting.code}
            </span>
            {!isDefault && (
              <span className="rounded-full bg-purple-100 px-2 py-0.5 text-[10px] font-semibold uppercase text-purple-700 dark:bg-purple-900/50 dark:text-purple-300">
                {t("template.customized", "Customized")}
              </span>
            )}
          </div>
        </div>
        <div className="flex items-center gap-3">
          <span
            onClick={(event) => event.stopPropagation()}
            onKeyDown={(event) => event.stopPropagation()}
            role="presentation"
          >
            <StyleSettingToggle
              isDefault={isDefault}
              onToggle={() => onToggleDefault(setting.id)}
            />
          </span>
          <ChevronDown
            className={cn(
              "h-4 w-4 shrink-0 text-gray-400 transition-transform",
              isExpanded && "rotate-180",
            )}
          />
        </div>
      </button>

      {isExpanded && (
        <div className="space-y-4 border-t border-gray-100 px-4 py-4 dark:border-gray-700">
          {/* Common Properties */}
          <div className="space-y-3">
            <p className="text-xs font-medium text-gray-600 dark:text-gray-300">
              {t("template.commonProperties", "Common Properties")}
            </p>

        {isHeaderFooterStyle ? (
          <>
            {/* Header/Footer Style Properties */}
            <div>
              <label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
                {t("template.width", "Width")}
              </label>
              <input
                type="text"
                value={parsedStyles["width"] || "100%"}
                onChange={(e) => handlePropertyChange("width", e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 text-sm"
              />
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
                {t("template.height", "Height")}
              </label>
              <input
                type="text"
                value={parsedStyles["height"] || "auto"}
                onChange={(e) => handlePropertyChange("height", e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 text-sm"
              />
            </div>

            {/* Margin */}
            <div>
              <label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
                {t("template.margin", "Margin")}
              </label>
              <div className="grid grid-cols-2 gap-2">
                <div>
                  <label className="text-xs text-gray-500 dark:text-gray-400">Top</label>
                  <input
                    type="text"
                    value={parsedStyles["margin-top"] || "0"}
                    onChange={(e) => handlePropertyChange("margin-top", e.target.value)}
                    className="w-full px-2 py-1 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-gray-500 dark:text-gray-400">Right</label>
                  <input
                    type="text"
                    value={parsedStyles["margin-right"] || "0"}
                    onChange={(e) => handlePropertyChange("margin-right", e.target.value)}
                    className="w-full px-2 py-1 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-gray-500 dark:text-gray-400">Bottom</label>
                  <input
                    type="text"
                    value={parsedStyles["margin-bottom"] || "0"}
                    onChange={(e) => handlePropertyChange("margin-bottom", e.target.value)}
                    className="w-full px-2 py-1 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-gray-500 dark:text-gray-400">Left</label>
                  <input
                    type="text"
                    value={parsedStyles["margin-left"] || "0"}
                    onChange={(e) => handlePropertyChange("margin-left", e.target.value)}
                    className="w-full px-2 py-1 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded text-sm"
                  />
                </div>
              </div>
            </div>

            {/* Padding */}
            <div>
              <label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
                {t("template.padding", "Padding")}
              </label>
              <div className="grid grid-cols-2 gap-2">
                <div>
                  <label className="text-xs text-gray-500 dark:text-gray-400">Top</label>
                  <input
                    type="text"
                    value={parsedStyles["padding-top"] || "0"}
                    onChange={(e) => handlePropertyChange("padding-top", e.target.value)}
                    className="w-full px-2 py-1 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-gray-500 dark:text-gray-400">Right</label>
                  <input
                    type="text"
                    value={parsedStyles["padding-right"] || "0"}
                    onChange={(e) => handlePropertyChange("padding-right", e.target.value)}
                    className="w-full px-2 py-1 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-gray-500 dark:text-gray-400">Bottom</label>
                  <input
                    type="text"
                    value={parsedStyles["padding-bottom"] || "0"}
                    onChange={(e) => handlePropertyChange("padding-bottom", e.target.value)}
                    className="w-full px-2 py-1 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-gray-500 dark:text-gray-400">Left</label>
                  <input
                    type="text"
                    value={parsedStyles["padding-left"] || "0"}
                    onChange={(e) => handlePropertyChange("padding-left", e.target.value)}
                    className="w-full px-2 py-1 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded text-sm"
                  />
                </div>
              </div>
            </div>
          </>
        ) : (
          <>
            {/* Text Style Properties (with text-align) */}
            
            {/* Font Size */}
            <div>
              <label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
                {t("template.fontSize", "Font Size")}
              </label>
              <div className="flex gap-2">
                <input
                  type="number"
                  value={fontSizeParts.amount}
                  onChange={(e) =>
                    handlePropertyChange(
                      "font-size",
                      `${e.target.value}${fontSizeParts.unit}`,
                    )
                  }
                  placeholder="12"
                  className="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 text-sm"
                />
                <span className="flex items-center text-gray-600 dark:text-gray-400 text-sm">
                  {fontSizeParts.unit}
                </span>
              </div>
            </div>

            {/* Font Weight */}
            <StyleSettingSelect
              label={t("template.fontWeight", "Font Weight")}
              value={parsedStyles["font-weight"] || "normal"}
              onValueChange={(value) => handlePropertyChange("font-weight", value)}
              options={FONT_WEIGHT_OPTIONS}
            />

            {/* Font Family */}
            <StyleSettingSelect
              label={t("template.fontFamily", "Font Family")}
              value={parsedStyles["font-family"] || defaultFontFamily}
              onValueChange={(value) => handlePropertyChange("font-family", value)}
              options={FONT_FAMILY_OPTIONS}
            />

            {/* Text Decoration */}
            <StyleSettingSelect
              label={t("template.textDecoration", "Text Decoration")}
              value={parsedStyles["text-decoration"] || "none"}
              onValueChange={(value) =>
                handlePropertyChange("text-decoration", value)
              }
              options={TEXT_DECORATION_OPTIONS}
            />

            {/* Text Align */}
            <StyleSettingSelect
              label={t("template.textAlign", "Text Align")}
              value={parsedStyles["text-align"] || "left"}
              onValueChange={(value) => handlePropertyChange("text-align", value)}
              options={TEXT_ALIGN_OPTIONS}
            />

            {/* List Style */}
            {supportsListFormatting && (
            <div>
              <label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
                {t("template.listStyle", "List Style")}
              </label>
              <Select
                value={listStyleSelectValue}
                onValueChange={(value) => handlePropertyChange("list-style", value)}
              >
                <SelectTrigger className={STYLE_SELECT_TRIGGER_CLASS}>
                  <SelectValue
                    placeholder={t("template.listStyle", "List Style")}
                  >
                    {selectedBulletResource ? (
                      <ListStyleResourcePreview
                        resource={selectedBulletResource}
                        locale={locale}
                      />
                    ) : (
                      selectedStandardListStyle?.label ?? listStyleSelectValue
                    )}
                  </SelectValue>
                </SelectTrigger>
                <SelectContent className={STYLE_SELECT_CONTENT_CLASS}>
                  {STANDARD_LIST_STYLE_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                  {bulletResources.length > 0 && (
                    <SelectGroup>
                      <SelectLabel>
                        {t(
                          "template.customListBullets",
                          "Custom bullets (Resource Configuration)",
                        )}
                      </SelectLabel>
                      {bulletResources.map((resource) => (
                        <SelectItem
                          key={resource.id}
                          value={toResourceListStyleValue(resource.id)}
                        >
                          <ListStyleResourcePreview
                            resource={resource}
                            locale={locale}
                          />
                        </SelectItem>
                      ))}
                    </SelectGroup>
                  )}
                </SelectContent>
              </Select>
            </div>
            )}
          </>
        )}
      </div>

      {/* Advanced CSS Editor Toggle */}
      <button
        type="button"
        onClick={() => setShowAdvanced(!showAdvanced)}
        className="flex w-full items-center justify-between rounded-lg border border-gray-200 px-3 py-2 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-50 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700/60"
      >
        <span>{t("template.advancedCSS", "Advanced CSS Editor")}</span>
        <ChevronDown
          className={cn(
            "h-4 w-4 transition-transform",
            showAdvanced && "rotate-180",
          )}
        />
      </button>

      {showAdvanced && (
        <div className="space-y-2 border-t border-gray-100 pt-3 dark:border-gray-700">
          {supportsListFormatting && (
            <ListStyleImageField
              listStyleImage={parsedStyles["list-style-image"]}
              listStyle={parsedStyles["list-style"]}
              resourceId={storedResourceId}
              bulletResources={bulletResources}
              bulletResourcesLoading={bulletResourcesLoading}
              locale={locale}
              onReplace={handleReplaceListStyleImage}
              onRemove={handleRemoveListStyleImage}
              onRefreshResources={refetchBulletResources}
            />
          )}
          <p className="text-xs font-medium text-gray-600 dark:text-gray-300">
            {t("template.customCSS", "Custom CSS")}
          </p>
          <CSSBuilder
            key={`${setting.id}-${showAdvanced ? "open" : "closed"}`}
            style={advancedCssString}
            onChange={handleAdvancedChange}
            reactive
          />
        </div>
      )}
        </div>
      )}
    </div>
  );
};