import { Plus, Trash2 } from "lucide-react";
import Button from "@/components/ui/Button";
import MenuBoardBackgroundSettings from "@/components/business/menu-boards/MenuBoardBackgroundSettings";
import MenuBoardBrandLogoControl from "@/components/business/menu-boards/MenuBoardBrandLogoControl";
import MenuBoardProductImageControl from "@/components/business/menu-boards/MenuBoardProductImageControl";
import MenuBoardTypographyControl from "@/components/business/MenuBoardTypographyControl";
import type { MenuBoard, MenuBoardFontSizes, MenuBoardSettings } from "@/components/business/menu-boards/types";
import type { MenuBoardEditorTool } from "@/components/business/menu-boards/MenuBoardModuleSidebar";
import { useMenuBoardText } from "@/components/business/menu-boards/menuBoardI18n";
import { MENU_BOARD_DEFAULT_FONT_SIZES, menuBoardSettingsWithDefaults } from "@/components/business/menu-boards/menuBoardDefaults";

type Props = {
  businessId: string;
  board: MenuBoard;
  activeTool: MenuBoardEditorTool;
  disabled: boolean;
  onChange: (board: MenuBoard) => void;
};

const inputClass =
  "w-full rounded-lg border border-[var(--border)] bg-[var(--bg)] px-3 py-2 text-sm text-[var(--text)] outline-none transition focus:border-[var(--accent)] focus:ring-2 focus:ring-[var(--accent)]/30 disabled:cursor-not-allowed disabled:opacity-60";

const fontSizeFields: Array<{ key: keyof MenuBoardFontSizes; labelKey: "displayTitle" | "sectionHeading" | "productName" | "productPrice" | "productDescription" | "locationLabel" | "tickerMessage"; min: number; max: number }> = [
  { key: "title", labelKey: "displayTitle", min: 18, max: 96 },
  { key: "section", labelKey: "sectionHeading", min: 14, max: 56 },
  { key: "item", labelKey: "productName", min: 12, max: 48 },
  { key: "price", labelKey: "productPrice", min: 12, max: 48 },
  { key: "description", labelKey: "productDescription", min: 10, max: 36 },
  { key: "location", labelKey: "locationLabel", min: 10, max: 40 },
  { key: "ticker", labelKey: "tickerMessage", min: 12, max: 44 },
];

const templatePresets: Array<{
  name: string;
  mood: string;
  theme: "dark" | "light" | "classic";
  accentColor: string;
  font: NonNullable<MenuBoardSettings["font"]>;
  swatches: string[];
}> = [
  {
    name: "Signature quick serve",
    mood: "Bold red, bright pricing, fast ordering.",
    theme: "dark",
    accentColor: "#ef3b2d",
    font: { preset: "modern" },
    swatches: ["#ef3b2d", "#ffffff", "#111111"],
  },
  {
    name: "Golden combo board",
    mood: "Warm yellow calls out value meals and sets.",
    theme: "light",
    accentColor: "#f5b800",
    font: { preset: "modern" },
    swatches: ["#f5b800", "#ef4444", "#ffffff"],
  },
  {
    name: "Coffee house calm",
    mood: "Green cafe tone, premium readable layout.",
    theme: "dark",
    accentColor: "#1f9d68",
    font: { preset: "editorial" },
    swatches: ["#1f9d68", "#f4efe6", "#1f2933"],
  },
  {
    name: "Taproom chalk",
    mood: "Pub board texture, craft sections, strong contrast.",
    theme: "classic",
    accentColor: "#f59e0b",
    font: { preset: "rounded" },
    swatches: ["#f59e0b", "#e5e7eb", "#18181b"],
  },
  {
    name: "Modern black menu",
    mood: "Minimal premium board with quiet hierarchy.",
    theme: "dark",
    accentColor: "#38bdf8",
    font: { preset: "modern" },
    swatches: ["#38bdf8", "#f8fafc", "#020617"],
  },
];

export default function MenuBoardEditorSettingsPanel({ businessId, board, activeTool, disabled, onChange }: Props) {
  const t = useMenuBoardText();
  const settings = menuBoardSettingsWithDefaults(board.settings);

  function updateSettings(next: MenuBoardSettings) {
    onChange({ ...board, settings: { ...settings, ...next } });
  }

  return (
    <aside className="min-w-0 self-start overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--bg-elevated)]">
      <div className="border-b border-[var(--border)] p-4">
        <p className="text-xs font-medium uppercase tracking-wide text-[var(--text-faint)]">{t("settings")}</p>
        <h2 className="mt-1 text-lg font-semibold text-[var(--text)]">{panelTitle(activeTool, t)}</h2>
      </div>

      <div className="min-w-0 space-y-6 p-5 pb-10 sm:pb-12">
        {activeTool === "general" && (
          <div className="space-y-4">
            <label className="block text-sm font-medium text-[var(--text-muted)]">
              {t("boardName")}
              <input
                className={`${inputClass} mt-2`}
                value={board.name}
                disabled={disabled}
                onChange={(event) => onChange({ ...board, name: event.target.value })}
              />
            </label>

            <label className="block text-sm font-medium text-[var(--text-muted)]">
              {t("displayTitle")}
              <input
                className={`${inputClass} mt-2`}
                maxLength={120}
                placeholder={t("breakfastMenu")}
                value={settings.displayTitle ?? ""}
                disabled={disabled}
                onChange={(event) => updateSettings({ displayTitle: event.target.value })}
              />
              <span className="mt-1 block text-xs font-normal text-[var(--text-faint)]">{t("displayTitleHint")}</span>
            </label>

            <div>
              <p className="text-sm font-medium text-[var(--text-muted)]">{t("orientation")}</p>
              <div className="mt-2 grid grid-cols-2 gap-2">
                {(["LANDSCAPE", "PORTRAIT"] as const).map((orientation) => (
                  <button
                    key={orientation}
                    type="button"
                    disabled={disabled}
                    onClick={() => onChange({ ...board, orientation })}
                    className={`rounded-lg border px-3 py-3 text-sm font-medium transition ${
                      board.orientation === orientation
                        ? "border-[var(--accent)] bg-[var(--accent-muted)] text-[var(--accent)]"
                        : "border-[var(--border)] bg-[var(--bg)] text-[var(--text-muted)] hover:bg-[var(--bg-hover)]"
                    }`}
                  >
                    {orientation === "LANDSCAPE" ? t("landscapeRatio") : t("portraitRatio")}
                  </button>
                ))}
              </div>
            </div>

            <label className="block text-sm font-medium text-[var(--text-muted)]">
              {t("tickerMessage")}
              <input
                className={`${inputClass} mt-2`}
                maxLength={180}
                value={settings.ticker}
                disabled={disabled}
                onChange={(event) => updateSettings({ ticker: event.target.value })}
              />
            </label>
          </div>
        )}

        {activeTool === "design" && (
          <div className="space-y-4">
            <label className="block text-sm font-medium text-[var(--text-muted)]">
              {t("theme")}
              <select
                className={`${inputClass} mt-2`}
                value={settings.theme}
                disabled={disabled}
                onChange={(event) => updateSettings({ theme: event.target.value })}
              >
                <option value="dark">{t("dark")}</option>
                <option value="light">{t("light")}</option>
                <option value="classic">{t("classic")}</option>
              </select>
            </label>
            <section className="rounded-xl border border-[var(--border)] bg-[var(--bg)] p-4">
              <h3 className="text-sm font-semibold text-[var(--text)]">{t("boardColours")}</h3>
              <p className="mt-1 text-xs leading-5 text-[var(--text-faint)]">{t("boardColourDescription")}</p>
              <div className="mt-4 grid gap-3 sm:grid-cols-2">
                <ColorField label={t("accent")} value={settings.accentColor} disabled={disabled} onChange={(accentColor) => updateSettings({ accentColor })} />
                <ColorField label={t("boardSurface")} value={settings.surfaceColor ?? (settings.theme === "light" ? "#ffffff" : "#09090b")} disabled={disabled} onChange={(surfaceColor) => updateSettings({ surfaceColor })} />
                <ColorField label={t("primaryText")} value={settings.textColor ?? (settings.theme === "light" ? "#111827" : "#f8fafc")} disabled={disabled} onChange={(textColor) => updateSettings({ textColor })} />
                <ColorField label={t("secondaryText")} value={settings.mutedColor ?? (settings.theme === "light" ? "#4b5563" : "#a1a1aa")} disabled={disabled} onChange={(mutedColor) => updateSettings({ mutedColor })} />
                <ColorField label={t("sectionSurface")} value={settings.sectionSurfaceColor ?? (settings.theme === "light" ? "#ffffff" : "#18181b")} disabled={disabled} onChange={(sectionSurfaceColor) => updateSettings({ sectionSurfaceColor })} />
                <ColorField label={t("displayTitle")} value={settings.displayTitleColor ?? (settings.textColor ?? (settings.theme === "light" ? "#111827" : "#f8fafc"))} disabled={disabled} onChange={(displayTitleColor) => updateSettings({ displayTitleColor })} />
                <ColorField label={t("sectionHeading")} value={settings.sectionTextColor ?? settings.accentColor} disabled={disabled} onChange={(sectionTextColor) => updateSettings({ sectionTextColor })} />
                <ColorField label={t("tickerText")} value={settings.tickerTextColor ?? "#0f172a"} disabled={disabled} onChange={(tickerTextColor) => updateSettings({ tickerTextColor })} />
              </div>
            </section>
            <MenuBoardBrandLogoControl
              businessId={businessId}
              logo={settings.brandLogo}
              disabled={disabled}
              onChange={(brandLogo) => updateSettings({ brandLogo })}
            />
            <section className="rounded-xl border border-[var(--border)] bg-[var(--bg)] p-4">
              <h3 className="text-sm font-semibold text-[var(--text)]">{t("brandLayout")}</h3>
              <p className="mt-1 text-xs leading-5 text-[var(--text-faint)]">{t("brandLayoutDescription")}</p>
              <div className="mt-4 space-y-4">
                <SegmentedField
                  label={t("headerAlignment")}
                  value={settings.headerAlignment ?? "center"}
                  disabled={disabled}
                  options={[{ value: "left", label: t("left") }, { value: "center", label: t("centre") }, { value: "right", label: t("right") }]}
                  onChange={(headerAlignment) => updateSettings({ headerAlignment: headerAlignment as NonNullable<MenuBoardSettings["headerAlignment"]> })}
                />
                <SegmentedField
                  label={t("logoPosition")}
                  value={settings.logoPosition ?? "center"}
                  disabled={disabled}
                  options={[{ value: "left", label: t("left") }, { value: "center", label: t("centre") }, { value: "right", label: t("right")}]}
                  onChange={(logoPosition) => updateSettings({ logoPosition: logoPosition as NonNullable<MenuBoardSettings["logoPosition"]> })}
                />
                <SegmentedField
                  label={t("sectionTreatment")}
                  value={settings.contentStyle ?? "lined"}
                  disabled={disabled}
                  options={[{ value: "minimal", label: t("minimal") }, { value: "lined", label: t("lined") }, { value: "cards", label: t("cards") }]}
                  onChange={(contentStyle) => updateSettings({ contentStyle: contentStyle as NonNullable<MenuBoardSettings["contentStyle"]> })}
                />
                <SegmentedField
                  label={t("contentDensity")}
                  value={settings.contentDensity ?? "comfortable"}
                  disabled={disabled}
                  options={[{ value: "comfortable", label: t("comfortable") }, { value: "compact", label: t("compact") }]}
                  onChange={(contentDensity) => updateSettings({ contentDensity: contentDensity as NonNullable<MenuBoardSettings["contentDensity"]> })}
                />
              </div>
            </section>
            <div className="space-y-3 border-t border-[var(--border)] pt-4">
              <Toggle
                label={t("showDescriptions")}
                checked={settings.showDescriptions}
                disabled={disabled}
                onChange={(checked) => updateSettings({ showDescriptions: checked })}
              />
              <Toggle
                label={t("showUnavailable")}
                checked={settings.showUnavailable}
                disabled={disabled}
                onChange={(checked) => updateSettings({ showUnavailable: checked })}
              />
            </div>
          </div>
        )}

        {(activeTool === "design" || activeTool === "templates") && (
          <div className="space-y-3 pt-1">
            {templatePresets.map((template) => (
              <button
                key={template.name}
                type="button"
                disabled={disabled}
                onClick={() => updateSettings({
                  theme: template.theme,
                  accentColor: template.accentColor,
                  template: template.name,
                  font: template.font,
                  // Selecting a template intentionally starts from that template's
                  // complete visual baseline instead of retaining prior custom swatches.
                  surfaceColor: undefined,
                  textColor: undefined,
                  mutedColor: undefined,
                  sectionSurfaceColor: undefined,
                  displayTitleColor: undefined,
                  sectionTextColor: template.accentColor,
                  tickerTextColor: "#0f172a",
                })}
                className={`w-full rounded-lg border p-3 text-left transition hover:border-[var(--accent)] hover:bg-[var(--bg-hover)] ${
                  settings.template === template.name ? "border-[var(--accent)] bg-[var(--accent-muted)]" : "border-[var(--border)] bg-[var(--bg)]"
                }`}
              >
                <span className="flex items-start justify-between gap-3">
                  <span>
                    <span className="block text-sm font-semibold text-[var(--text)]">{templateLabel(template.name, t)}</span>
                    <span className="mt-1 block text-xs text-[var(--text-faint)]">{templateMood(template.name, t)}</span>
                  </span>
                  <span className="flex shrink-0 overflow-hidden rounded-full border border-[var(--border)]">
                    {template.swatches.map((color) => <span key={color} className="h-5 w-5" style={{ backgroundColor: color }} />)}
                  </span>
                </span>
              </button>
            ))}
          </div>
        )}

        {(activeTool === "design" || activeTool === "typography") && (
          <div className="space-y-4">
            <MenuBoardTypographyControl
              businessId={businessId}
              font={settings.font}
              disabled={disabled}
              onChange={(font) => updateSettings({ font })}
            />
            <section className="rounded-xl border border-[var(--border)] bg-[var(--bg)] p-4">
              <div>
                <h3 className="text-sm font-semibold text-[var(--text)]">{t("textSizes")}</h3>
                <p className="mt-1 text-xs text-[var(--text-faint)]">{t("textSizeDescription")}</p>
              </div>
              <div className="mt-4 space-y-4">
                {fontSizeFields.map(({ key, labelKey, ...field }) => (
                  <FontSizeField
                    key={key}
                    {...field}
                    label={t(labelKey)}
                    disabled={disabled}
                    value={settings.fontSizes?.[key] ?? MENU_BOARD_DEFAULT_FONT_SIZES[key]}
                    onChange={(value) => updateSettings({ fontSizes: { ...MENU_BOARD_DEFAULT_FONT_SIZES, ...settings.fontSizes, [key]: value } })}
                  />
                ))}
              </div>
            </section>
          </div>
        )}

        {(activeTool === "design" || activeTool === "background") && (
          <MenuBoardBackgroundSettings
            businessId={businessId}
            background={settings.background}
            disabled={disabled}
            onChange={(background) => updateSettings({ background })}
          />
        )}

        {activeTool === "content" && (
          <div className="space-y-4">
            {board.sections.length === 0 && (
              <div className="rounded-lg border border-dashed border-[var(--border)] bg-[var(--bg)] p-4 text-sm text-[var(--text-muted)]">
                {t("blankBoard")}
              </div>
            )}
            {board.sections.map((section, sectionIndex) => (
              <div key={section.id ?? sectionIndex} className="rounded-lg border border-[var(--border)] bg-[var(--bg)] p-3">
                <div className="flex gap-2">
                  <input
                    className={inputClass}
                    value={section.title}
                    disabled={disabled}
                    onChange={(event) => {
                      const sections = structuredClone(board.sections);
                      sections[sectionIndex].title = event.target.value;
                      onChange({ ...board, sections });
                    }}
                  />
                  <IconButton
                    label={t("removeSection")}
                    disabled={disabled}
                    onClick={() => onChange({ ...board, sections: board.sections.filter((_, index) => index !== sectionIndex) })}
                  >
                    <Trash2 className="h-4 w-4" />
                  </IconButton>
                </div>
                <label className="mt-3 flex items-center justify-between gap-3 rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] px-3 py-2 text-xs font-medium text-[var(--text-muted)]">
                  <span>{t("showSection")}</span>
                  <input
                    type="checkbox"
                    className="h-4 w-4 accent-[var(--accent)]"
                    checked={section.isVisible !== false}
                    disabled={disabled}
                    onChange={(event) => {
                      const sections = structuredClone(board.sections);
                      sections[sectionIndex].isVisible = event.target.checked;
                      onChange({ ...board, sections });
                    }}
                  />
                </label>
                <div className="mt-3 space-y-2">
                  {section.items.map((item, itemIndex) => (
                    <div key={item.id ?? itemIndex} className="rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] p-2.5">
                      <div className="grid gap-2 sm:grid-cols-[auto_minmax(0,1fr)_88px_auto]">
                        <MenuBoardProductImageControl
                          businessId={businessId}
                          imageUrl={item.imageUrl}
                          disabled={disabled}
                          onChange={(imageUrl) => {
                            const sections = structuredClone(board.sections);
                            sections[sectionIndex].items[itemIndex].imageUrl = imageUrl;
                            onChange({ ...board, sections });
                          }}
                        />
                        <input
                          className={inputClass}
                          value={item.name}
                          disabled={disabled}
                          placeholder={t("productName")}
                          onChange={(event) => {
                            const sections = structuredClone(board.sections);
                            sections[sectionIndex].items[itemIndex].name = event.target.value;
                            onChange({ ...board, sections });
                          }}
                        />
                        <input
                          className={inputClass}
                          value={item.price ?? ""}
                          disabled={disabled}
                          placeholder={t("price")}
                          inputMode="decimal"
                          onChange={(event) => {
                            const sections = structuredClone(board.sections);
                            sections[sectionIndex].items[itemIndex].price = event.target.value;
                            onChange({ ...board, sections });
                          }}
                        />
                        <IconButton
                          label={t("removeItem")}
                          disabled={disabled}
                          onClick={() => {
                            const sections = structuredClone(board.sections);
                            sections[sectionIndex].items.splice(itemIndex, 1);
                            onChange({ ...board, sections });
                          }}
                        >
                          <Trash2 className="h-4 w-4" />
                        </IconButton>
                      </div>
                      <div className="mt-2 grid gap-2 sm:grid-cols-[1fr_auto] sm:items-center">
                        <input
                          className={inputClass}
                          value={item.description ?? ""}
                          disabled={disabled}
                          placeholder={t("productDescription")}
                          onChange={(event) => {
                            const sections = structuredClone(board.sections);
                            sections[sectionIndex].items[itemIndex].description = event.target.value || null;
                            onChange({ ...board, sections });
                          }}
                        />
                        <Toggle
                          label={t("available")}
                          checked={item.isAvailable}
                          disabled={disabled}
                          onChange={(isAvailable) => {
                            const sections = structuredClone(board.sections);
                            sections[sectionIndex].items[itemIndex].isAvailable = isAvailable;
                            onChange({ ...board, sections });
                          }}
                        />
                      </div>
                    </div>
                  ))}
                  <Button
                    type="button"
                    variant="secondary"
                    size="sm"
                    disabled={disabled}
                    onClick={() => {
                      const sections = structuredClone(board.sections);
                      sections[sectionIndex].items.push({ name: t("newItem"), price: null, description: null, isAvailable: true });
                      onChange({ ...board, sections });
                    }}
                  >
                    <Plus className="h-4 w-4" />
                    {t("addItem")}
                  </Button>
                </div>
              </div>
            ))}
            <Button
              type="button"
              variant="secondary"
              disabled={disabled}
              onClick={() => onChange({ ...board, sections: [...board.sections, { title: t("newSection"), isVisible: true, items: [] }] })}
            >
              <Plus className="h-4 w-4" />
              {t("addSection")}
            </Button>
          </div>
        )}

        {activeTool === "schedule" && (
          <div className="rounded-lg border border-dashed border-[var(--border)] bg-[var(--bg)] p-5 text-sm text-[var(--text-muted)]">
            {t("schedulePlaceholder")}
          </div>
        )}
      </div>
    </aside>
  );
}

function panelTitle(tool: MenuBoardEditorTool, t: ReturnType<typeof useMenuBoardText>) {
  const titles: Record<MenuBoardEditorTool, ReturnType<typeof t>> = {
    general: t("general"),
    design: t("design"),
    templates: t("templates"),
    typography: t("typography"),
    background: t("backgroundMedia"),
    content: t("menuContent"),
    schedule: t("schedule"),
  };
  return titles[tool];
}

function templateLabel(name: string, t: ReturnType<typeof useMenuBoardText>) {
  const labels: Record<string, ReturnType<typeof t>> = {
    "Signature quick serve": t("signatureQuickServe"),
    "Golden combo board": t("goldenComboBoard"),
    "Coffee house calm": t("coffeeHouseCalm"),
    "Taproom chalk": t("taproomChalk"),
    "Modern black menu": t("modernBlackMenu"),
  };
  return labels[name] ?? name;
}

function templateMood(name: string, t: ReturnType<typeof useMenuBoardText>) {
  const moods: Record<string, ReturnType<typeof t>> = {
    "Signature quick serve": t("signatureQuickServeMood"),
    "Golden combo board": t("goldenComboBoardMood"),
    "Coffee house calm": t("coffeeHouseCalmMood"),
    "Taproom chalk": t("taproomChalkMood"),
    "Modern black menu": t("modernBlackMenuMood"),
  };
  return moods[name] ?? name;
}

function Toggle({ label, checked, disabled, onChange }: { label: string; checked: boolean; disabled?: boolean; onChange: (checked: boolean) => void }) {
  return (
    <label className="flex items-center justify-between gap-3 rounded-lg border border-[var(--border)] bg-[var(--bg)] p-3 text-sm font-medium text-[var(--text-muted)]">
      <span>{label}</span>
      <input
        type="checkbox"
        className="h-4 w-4 accent-[var(--accent)]"
        checked={checked}
        disabled={disabled}
        onChange={(event) => onChange(event.target.checked)}
      />
    </label>
  );
}

function ColorField({ label, value, disabled, onChange }: { label: string; value: string; disabled?: boolean; onChange: (value: string) => void }) {
  return (
    <label className="flex items-center justify-between gap-3 rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] p-2.5 text-sm font-medium text-[var(--text-muted)]">
      <span>{label}</span>
      <span className="flex items-center gap-2">
        <span className="font-mono text-xs text-[var(--text-faint)]">{value.toUpperCase()}</span>
        <input
          type="color"
          value={value}
          disabled={disabled}
          aria-label={`${label} colour`}
          onChange={(event) => onChange(event.target.value)}
          className="h-7 w-7 cursor-pointer rounded border border-[var(--border)] bg-transparent p-0 disabled:cursor-not-allowed"
        />
      </span>
    </label>
  );
}

function SegmentedField({ label, value, options, disabled, onChange }: { label: string; value: string; options: Array<{ value: string; label: string }>; disabled?: boolean; onChange: (value: string) => void }) {
  return (
    <div>
      <p className="text-xs font-medium text-[var(--text-muted)]">{label}</p>
      <div className="mt-2 grid gap-1 rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] p-1" style={{ gridTemplateColumns: `repeat(${options.length}, minmax(0, 1fr))` }}>
        {options.map((option) => (
          <button key={option.value} type="button" disabled={disabled} onClick={() => onChange(option.value)} className={`min-w-0 rounded-md px-2 py-2 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-50 ${value === option.value ? "bg-[var(--accent-muted)] text-[var(--accent)]" : "text-[var(--text-muted)] hover:bg-[var(--bg-hover)]"}`}>
            {option.label}
          </button>
        ))}
      </div>
    </div>
  );
}

function IconButton({ label, disabled, onClick, children }: { label: string; disabled?: boolean; onClick: () => void; children: React.ReactNode }) {
  return (
    <button
      type="button"
      title={label}
      aria-label={label}
      disabled={disabled}
      onClick={onClick}
      className="grid h-10 w-10 shrink-0 place-items-center rounded-lg text-[var(--text-muted)] transition hover:bg-red-500/10 hover:text-red-400 disabled:cursor-not-allowed disabled:opacity-40"
    >
      {children}
    </button>
  );
}

function FontSizeField({ label, min, max, value, disabled, onChange }: { label: string; min: number; max: number; value: number; disabled?: boolean; onChange: (value: number) => void }) {
  const setValue = (next: number) => {
    if (Number.isFinite(next)) onChange(Math.min(max, Math.max(min, Math.round(next))));
  };

  return (
    <label className="block">
      <span className="flex items-center justify-between gap-3 text-sm font-medium text-[var(--text-muted)]">
        {label}
        <span className="flex items-center gap-1 rounded-md border border-[var(--border)] bg-[var(--bg-elevated)] px-2 py-1 text-xs text-[var(--text)]">
          <input
            type="number"
            min={min}
            max={max}
            value={value}
            disabled={disabled}
            aria-label={`${label} font size`}
            onChange={(event) => setValue(Number(event.target.value))}
            className="w-9 bg-transparent text-right outline-none disabled:cursor-not-allowed"
          />
          px
        </span>
      </span>
      <input
        type="range"
        min={min}
        max={max}
        value={value}
        disabled={disabled}
        onChange={(event) => setValue(Number(event.target.value))}
        className="mt-2 h-1.5 w-full cursor-pointer accent-[var(--accent)] disabled:cursor-not-allowed"
      />
    </label>
  );
}
