// app/components/admin/editors/ContainerEditor.tsx
'use client';

import { useEffect, useState, useCallback } from 'react';
import {
  ContainerComponentProps,
  ContainerLayout,
  LAYOUT_DEFINITIONS,
  migrateToColumns,
} from '@/lib/page-builder/types';
import { SavedSidebar } from '@/lib/page-builder/container-types';
import { EditorProps } from '@/lib/page-builder/types';
import { sidebarWidgetRegistry } from '@/lib/page-builder/sidebar-widget-registry';

// ── Constants ─────────────────────────────────────────────────────────────────

const MAX_WIDTH_PRESETS = [
  { label: 'SM',   value: 640  },
  { label: 'MD',   value: 768  },
  { label: 'LG',   value: 1024 },
  { label: 'XL',   value: 1280 },
  { label: '2XL',  value: 1536 },
  { label: 'Full', value: 9999 },
];

const BACKGROUND_PRESETS = [
  { label: 'Transparent', value: 'transparent' },
  { label: 'White',       value: '#ffffff'      },
  { label: 'Light Gray',  value: '#f9fafb'      },
  { label: 'Gray',        value: '#f3f4f6'      },
  { label: 'Dark',        value: '#111827'      },
  { label: 'Custom',      value: 'custom'       },
];

// ── Layout groups ─────────────────────────────────────────────────────────────

const LAYOUT_GROUPS: {
  heading: string;
  cols: 1 | 2 | 3;
  layouts: ContainerLayout[];
}[] = [
  { heading: 'Single',          cols: 1, layouts: ['full-width']                      },
  { heading: 'Two Columns',     cols: 2, layouts: ['1-1', '2-1', '1-2', '3-1', '1-3'] },
  { heading: 'Multi Column',    cols: 2, layouts: ['1-1-1', '1-1-1-1']                },
  { heading: 'Sidebar',         cols: 2, layouts: ['left-sidebar', 'right-sidebar']   },
];

type PaddingMode = 'all' | 'axes' | 'individual';

// ── Helpers ───────────────────────────────────────────────────────────────────

function SectionLabel({ children }: { children: React.ReactNode }) {
  return (
    <label className="block text-sm font-semibold text-var-text mb-3">
      {children}
    </label>
  );
}

function Divider() {
  return <hr className="border-var-border" />;
}

// ── Layout wireframe preview ──────────────────────────────────────────────────

function LayoutWireframe({
  layout,
  active,
}: {
  layout: ContainerLayout;
  active: boolean;
}) {
  const def       = LAYOUT_DEFINITIONS[layout];
  const colCount  = def.fractions.length;

  const weights = def.fractions.map(f => {
    if (f.endsWith('fr'))  return parseFloat(f);
    if (f.endsWith('%'))   return parseFloat(f) / 100;
    return 1;
  });

  const isSidebarCol = (i: number) =>
    def.isSidebar && (
      (layout === 'left-sidebar'  && i === 0) ||
      (layout === 'right-sidebar' && i === colCount - 1)
    );

  return (
    <div className="w-full h-16 flex gap-1 p-1.5">
      {weights.map((w, i) => {
        const sidebar = isSidebarCol(i);
        const colBg    = active
          ? (sidebar ? 'bg-var-warning-bg'  : 'bg-var-primary-muted')
          : (sidebar ? 'bg-var-warning-bg/40'   : 'bg-var-surface-hover');
        const lineBg   = active
          ? (sidebar ? 'bg-var-warning'  : 'bg-var-primary')
          : (sidebar ? 'bg-var-warning/40'  : 'bg-var-primary/40');
        const lineShort = active
          ? (sidebar ? 'bg-var-warning/60'  : 'bg-var-primary/60')
          : (sidebar ? 'bg-var-warning/20'  : 'bg-var-primary/20');

        const lines = sidebar
          ? [
              { w: '100%', h: 'h-1.5', color: lineBg },
              { w: '80%',  h: 'h-1.5', color: lineShort },
              { w: '90%',  h: 'h-1.5', color: lineBg },
            ]
          : [
              { w: '85%',  h: 'h-1',   color: lineBg },
              { w: '100%', h: 'h-1',   color: lineShort },
              { w: '60%',  h: 'h-1',   color: lineBg },
            ];

        return (
          <div
            key={i}
            className={`${colBg} rounded flex flex-col justify-center gap-1.5 px-1.5`}
            style={{ flex: w }}
          >
            {lines.map((line, li) => (
              <div
                key={li}
                className={`${line.color} ${line.h} rounded-full`}
                style={{ width: line.w }}
              />
            ))}
          </div>
        );
      })}
    </div>
  );
}

// ── Layout card ───────────────────────────────────────────────────────────────

function LayoutCard({
  layout,
  active,
  onClick,
}: {
  layout: ContainerLayout;
  active: boolean;
  onClick: () => void;
}) {
  const def = LAYOUT_DEFINITIONS[layout];

  return (
    <button
      type="button"
      onClick={onClick}
      className={`
        relative flex flex-col rounded-xl border-2 overflow-hidden transition-all text-left w-full
        ${active
          ? 'border-var-primary shadow-var-card'
          : 'border-var-border hover:border-var-primary/60 hover:shadow-var-card'}
      `}
    >
      <div className={`${active ? 'bg-var-primary-muted' : 'bg-var-surface-hover'} transition-colors`}>
        <LayoutWireframe layout={layout} active={active} />
      </div>

      <div className={`
        flex items-center justify-between px-2 py-1.5 border-t
        ${active ? 'bg-var-primary border-var-primary' : 'bg-var-surface border-var-border'}
      `}>
        <span className={`text-xs font-semibold truncate ${active ? 'text-white' : 'text-var-text'}`}>
          {def.label}
        </span>
        <span className={`flex gap-0.5 shrink-0 ml-1 ${active ? 'opacity-80' : ''}`}>
          {def.percentages.map((p, i) => (
            <span
              key={i}
              className={`
                text-[10px] font-mono px-1 py-0 rounded leading-5
                ${active ? 'bg-var-primary/40 text-white' : 'bg-var-surface-hover text-var-text-muted'}
              `}
            >
              {p}
            </span>
          ))}
        </span>
      </div>

      {active && (
        <div className="absolute top-1.5 right-1.5 w-4 h-4 bg-var-primary rounded-full flex items-center justify-center shadow-var-card">
          <svg className="w-2.5 h-2.5 text-white" fill="currentColor" viewBox="0 0 20 20">
            <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" />
          </svg>
        </div>
      )}
    </button>
  );
}

// ── PxInput ───────────────────────────────────────────────────────────────────

function PxInput({
  label, value, min = 0, max = 200, onChange, className = '',
}: {
  label: string; value: number; min?: number; max?: number;
  onChange: (v: number) => void; className?: string;
}) {
  return (
    <div className={`flex flex-col items-center gap-1 ${className}`}>
      <div className="flex items-stretch border border-var-border rounded-lg overflow-hidden bg-var-surface-hover w-full focus-within:ring-2 focus-within:ring-var-primary">
        <input
          type="number" min={min} max={max} value={value}
          onChange={e => onChange(Math.min(max, Math.max(min, Number(e.target.value))))}
          className="flex-1 min-w-0 text-sm font-mono text-var-text text-center py-1.5 px-1 bg-transparent focus:outline-none"
        />
        <span className="flex items-center px-1.5 text-xs font-medium text-var-text-muted bg-var-surface-hover border-l border-var-border select-none">px</span>
      </div>
      <span className="text-xs text-var-text-muted leading-none">{label}</span>
    </div>
  );
}

// ── LinkIcon ──────────────────────────────────────────────────────────────────

function LinkIcon({ mode, onClick }: { mode: PaddingMode; onClick: () => void }) {
  return (
    <button
      type="button" onClick={onClick}
      title={mode === 'all' ? 'All sides linked' : mode === 'axes' ? 'H/V axes' : 'Individual sides'}
      className={`w-7 h-7 flex items-center justify-center rounded-md border transition-colors ${
        mode === 'all'    ? 'bg-var-primary-muted border-var-primary text-var-primary'
        : mode === 'axes' ? 'bg-var-warning-bg border-var-warning-border text-var-warning'
        : 'bg-var-surface-hover border-var-border text-var-text-muted hover:border-var-border-strong'
      }`}
    >
      {mode === 'all' ? (
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
          <path d="M6.5 9.5a3.5 3.5 0 0 0 4.95 0l1.5-1.5a3.5 3.5 0 0 0-4.95-4.95l-.86.86" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          <path d="M9.5 6.5a3.5 3.5 0 0 0-4.95 0L3.05 8a3.5 3.5 0 0 0 4.95 4.95l.86-.86" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
        </svg>
      ) : mode === 'axes' ? (
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
          <path d="M3 8h10M8 3v10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          <path d="M5 6L3 8l2 2M11 6l2 2-2 2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      ) : (
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
          <path d="M6.5 9.5a3.5 3.5 0 0 0 4.95 0l1.5-1.5a3.5 3.5 0 0 0-4.95-4.95" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          <path d="M9.5 6.5a3.5 3.5 0 0 0-4.95 0L3.05 8a3.5 3.5 0 0 0 4.95 4.95" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          <line x1="10" y1="3" x2="10" y2="5.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          <line x1="13" y1="6" x2="10.5" y2="6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          <line x1="6" y1="13" x2="6" y2="10.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          <line x1="3" y1="10" x2="5.5" y2="10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
        </svg>
      )}
    </button>
  );
}

// ── PaddingControl ────────────────────────────────────────────────────────────

interface PaddingValues { top: number; right: number; bottom: number; left: number; }

function PaddingControl({ values, onChange }: { values: PaddingValues; onChange: (v: PaddingValues) => void }) {
  const [mode, setMode] = useState<PaddingMode>(() => {
    const { top, right, bottom, left } = values;
    if (top === right && right === bottom && bottom === left) return 'all';
    if (top === bottom && left === right) return 'axes';
    return 'individual';
  });

  const cycleMode   = () => setMode(p => p === 'all' ? 'axes' : p === 'axes' ? 'individual' : 'all');
  const setAll      = (v: number) => onChange({ top: v, right: v, bottom: v, left: v });
  const setH        = (v: number) => onChange({ ...values, left: v, right: v });
  const setV        = (v: number) => onChange({ ...values, top: v, bottom: v });
  const setSide     = (side: keyof PaddingValues, v: number) => onChange({ ...values, [side]: v });

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <label className="text-sm font-semibold text-var-text">Padding</label>
        <div className="flex items-center gap-1.5">
          <span className="text-xs text-var-text-muted">
            {mode === 'all' ? 'All sides' : mode === 'axes' ? 'H / V axes' : 'Individual'}
          </span>
          <LinkIcon mode={mode} onClick={cycleMode} />
        </div>
      </div>

      {mode === 'all' && (
        <div className="flex items-center gap-3">
          <input type="range" min={0} max={120} step={4} value={values.top}
            onChange={e => setAll(Number(e.target.value))} className="flex-1 accent-var-primary" />
          <div className="flex items-stretch border border-var-border rounded-lg overflow-hidden bg-var-surface-hover focus-within:ring-2 focus-within:ring-var-primary">
            <input type="number" min={0} max={120} value={values.top}
              onChange={e => setAll(Math.min(120, Math.max(0, Number(e.target.value))))}
              className="w-14 text-sm font-mono text-var-text text-center py-1 px-2 bg-transparent focus:outline-none" />
            <span className="flex items-center px-2 text-xs font-medium text-var-text-muted bg-var-surface-hover border-l border-var-border select-none">px</span>
          </div>
        </div>
      )}

      {mode === 'axes' && (
        <div className="grid grid-cols-2 gap-3">
          {[
            { label: 'Horizontal', icon: 'H', value: values.left, set: setH },
            { label: 'Vertical',   icon: 'V', value: values.top,  set: setV },
          ].map(({ label, icon, value, set }) => (
            <div key={label} className="space-y-1.5">
              <span className="text-xs text-var-text-muted font-medium flex items-center gap-1">
                <span className="w-4 h-4 rounded bg-var-surface-hover text-var-text-muted text-xs flex items-center justify-center font-bold">{icon}</span>
                {label}
              </span>
              <div className="flex items-center gap-2">
                <input type="range" min={0} max={120} step={4} value={value}
                  onChange={e => set(Number(e.target.value))} className="flex-1 accent-var-primary" />
                <div className="flex items-stretch border border-var-border rounded-lg overflow-hidden bg-var-surface-hover focus-within:ring-2 focus-within:ring-var-primary">
                  <input type="number" min={0} max={120} value={value}
                    onChange={e => set(Math.min(120, Math.max(0, Number(e.target.value))))}
                    className="w-12 text-sm font-mono text-var-text text-center py-1 px-1 bg-transparent focus:outline-none" />
                  <span className="flex items-center px-1.5 text-xs font-medium text-var-text-muted bg-var-surface-hover border-l border-var-border select-none">px</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {mode === 'individual' && (
        <div className="bg-var-surface-hover border border-var-border rounded-xl p-3 space-y-2">
          <div className="flex justify-center">
            <PxInput label="Top" value={values.top} onChange={v => setSide('top', v)} className="w-20" />
          </div>
          <div className="flex items-center gap-2">
            <PxInput label="Left"  value={values.left}  onChange={v => setSide('left', v)}  className="w-20 shrink-0" />
            <div className="flex-1 min-h-12 border-2 border-dashed border-var-primary/40 rounded-lg bg-var-primary-muted/20 flex items-center justify-center">
              <span className="text-xs text-var-primary/60 font-medium select-none">Content</span>
            </div>
            <PxInput label="Right" value={values.right} onChange={v => setSide('right', v)} className="w-20 shrink-0" />
          </div>
          <div className="flex justify-center">
            <PxInput label="Bottom" value={values.bottom} onChange={v => setSide('bottom', v)} className="w-20" />
          </div>
        </div>
      )}

      <div className="flex items-center gap-1 flex-wrap">
        {(['top','right','bottom','left'] as const).map(side => (
          <span key={side} className="inline-flex items-center gap-1 px-2 py-0.5 bg-var-surface-hover rounded text-xs font-mono text-var-text-muted">
            <span className="text-var-text-muted">{side[0].toUpperCase()}</span>{values[side]}px
          </span>
        ))}
      </div>
    </div>
  );
}

// ── SliderWithInput ───────────────────────────────────────────────────────────

function SliderWithInput({ label, hint, value, min, max, step, unit = 'px', onChange }: {
  label: string; hint?: string; value: number; min: number; max: number;
  step: number; unit?: string; onChange: (v: number) => void;
}) {
  return (
    <div>
      <label className="block text-sm font-semibold text-var-text mb-1">{label}</label>
      <div className="flex items-center gap-3">
        <input type="range" min={min} max={max} step={step} value={value}
          onChange={e => onChange(Number(e.target.value))} className="flex-1 accent-var-primary" />
        <div className="flex items-stretch border border-var-border rounded-lg overflow-hidden bg-var-surface-hover focus-within:ring-2 focus-within:ring-var-primary">
          <input type="number" min={min} max={max} step={step} value={value}
            onChange={e => onChange(Math.min(max, Math.max(min, Number(e.target.value))))}
            className="w-14 text-sm font-mono text-var-text text-center py-1 px-2 bg-transparent focus:outline-none" />
          <span className="flex items-center px-2 text-xs font-medium text-var-text-muted bg-var-surface-hover border-l border-var-border select-none">{unit}</span>
        </div>
      </div>
      {hint && <p className="text-xs text-var-text-muted mt-1">{hint}</p>}
    </div>
  );
}

// ── Main editor ───────────────────────────────────────────────────────────────

export default function ContainerEditor({ props, onUpdate }: EditorProps<ContainerComponentProps>) {
  const resolvedColumns = migrateToColumns(props);
  const isSidebarLayout = props.layout === 'left-sidebar' || props.layout === 'right-sidebar';

  const [savedSidebars, setSavedSidebars]     = useState<SavedSidebar[]>([]);
  const [loadingSidebars, setLoadingSidebars] = useState(false);

  const isCustomBg = !BACKGROUND_PRESETS.slice(0, -1).some(p => p.value === props.containerBackground);
  const [customBgColor, setCustomBgColor] = useState(
    isCustomBg && props.containerBackground !== 'transparent'
      ? (props.containerBackground ?? '#ffffff') : '#ffffff'
  );

  const selectedSidebar = savedSidebars.find(s => s.id === props.savedSidebarId) ?? null;

  const paddingValues: PaddingValues = {
    top:    props.paddingTop    ?? props.paddingY ?? 16,
    right:  props.paddingRight  ?? props.paddingX ?? 16,
    bottom: props.paddingBottom ?? props.paddingY ?? 16,
    left:   props.paddingLeft   ?? props.paddingX ?? 16,
  };

  const fetchSidebars = useCallback(async () => {
    setLoadingSidebars(true);
    try {
      const res = await fetch('/api/backend/admin/sidebars?all=true&status=active');
      if (res.ok) setSavedSidebars((await res.json()).sidebars || []);
    } catch (e) { console.error('Failed to load sidebars', e); }
    finally     { setLoadingSidebars(false); }
  }, []);

  useEffect(() => {
    if (isSidebarLayout) fetchSidebars();
  }, [isSidebarLayout, fetchSidebars]);

  const set = useCallback(
    (patch: Partial<ContainerComponentProps>) => onUpdate({ ...props, ...patch }),
    [props, onUpdate]
  );

  const handleLayoutChange = (layout: ContainerLayout) => {
    const newDef      = LAYOUT_DEFINITIONS[layout];
    const existingIds = resolvedColumns.flatMap(c => c.childIds);

    const newColumns = newDef.fractions.map((_, i) => ({
      id:       resolvedColumns[i]?.id ?? `col-${layout}-${i}-${Date.now()}`,
      childIds: i === 0 ? existingIds : [],
    }));

    set({
      layout,
      columns: newColumns,
      ...(layout !== 'left-sidebar' && layout !== 'right-sidebar'
        ? { savedSidebarId: null } : {}),
    });
  };

  const handlePaddingChange = (v: PaddingValues) => {
    set({ paddingTop: v.top, paddingRight: v.right, paddingBottom: v.bottom, paddingLeft: v.left });
  };

  const handleBgPreset = (value: string) => {
    set({ containerBackground: value === 'custom' ? customBgColor : value });
  };

  const handleCustomBgChange = (hex: string) => {
    setCustomBgColor(hex);
    set({ containerBackground: hex });
  };

  const activeBgPreset = isCustomBg ? 'custom' : (props.containerBackground ?? 'transparent');
  const currentDef     = LAYOUT_DEFINITIONS[props.layout ?? 'full-width'];

  return (
    <div className="space-y-6">

      {/* ── 1. Layout picker ─────────────────────────────────────────────── */}
      <div>
        <SectionLabel>Layout</SectionLabel>

        <div className="space-y-5">
          {LAYOUT_GROUPS.map(group => (
            <div key={group.heading}>
              <div className="flex items-center gap-2 mb-2">
                <span className="text-xs font-semibold text-var-text-muted uppercase tracking-wider">
                  {group.heading}
                </span>
                <div className="flex-1 h-px bg-var-border" />
              </div>

              <div
                className={`grid gap-2 ${
                  group.cols === 1 ? 'grid-cols-1'
                  : group.cols === 3 ? 'grid-cols-3'
                  : 'grid-cols-2'
                }`}
              >
                {group.layouts.map(layoutKey => (
                  <LayoutCard
                    key={layoutKey}
                    layout={layoutKey}
                    active={props.layout === layoutKey}
                    onClick={() => handleLayoutChange(layoutKey)}
                  />
                ))}
              </div>
            </div>
          ))}
        </div>

        <div className="mt-4 flex items-center gap-3 px-3 py-2.5 bg-var-primary-muted border border-var-primary/30 rounded-xl">
          <div className="w-16 shrink-0 rounded overflow-hidden border border-var-primary/30">
            <LayoutWireframe layout={props.layout ?? 'full-width'} active={true} />
          </div>
          <div className="min-w-0 flex-1">
            <p className="text-xs font-semibold text-var-primary-text">{currentDef.label}</p>
            <p className="text-xs text-var-primary-text/70 mt-0.5">
              {currentDef.fractions.length} column{currentDef.fractions.length > 1 ? 's' : ''}
              {' · '}
              {currentDef.percentages.join(' / ')}
            </p>
          </div>
          <span className="shrink-0 text-xs font-bold text-var-primary-text bg-var-primary-muted px-2 py-0.5 rounded-full">
            {currentDef.fractions.length}col
          </span>
        </div>
      </div>

      <Divider />

      {/* ── 2. Info banner for non-sidebar layouts ───────────────────────── */}
      {!isSidebarLayout && (
        <div className="flex items-start gap-2 px-3 py-2.5 bg-var-surface-hover border border-var-border rounded-xl text-xs text-var-text-muted">
          <svg className="w-3.5 h-3.5 mt-0.5 shrink-0 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <span>
            Click <strong className="font-semibold text-var-text">+ Add Component</strong> inside each column
            on the canvas to populate it.
          </span>
        </div>
      )}

      <Divider />

      {/* ── 3. Container padding ─────────────────────────────────────────── */}
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <SectionLabel>Container Padding</SectionLabel>
            <p className="text-xs text-var-text-muted -mt-2">Constrain content width and add padding</p>
          </div>
          <button
            type="button"
            onClick={() => set({ containerPadding: !props.containerPadding })}
            className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none ${
              props.containerPadding ? 'bg-var-primary' : 'bg-var-surface-hover'
            }`}
          >
            <span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${
              props.containerPadding ? 'translate-x-6' : 'translate-x-1'
            }`} />
          </button>
        </div>

        {props.containerPadding && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-semibold text-var-text mb-2">Max Width</label>
              <div className="flex flex-wrap gap-1.5 mb-3">
                {MAX_WIDTH_PRESETS.map(preset => (
                  <button key={preset.value} type="button" onClick={() => set({ maxWidth: preset.value })}
                    className={`px-3 py-1 text-xs font-medium rounded-lg border transition-colors ${
                      (props.maxWidth ?? 1280) === preset.value
                        ? 'bg-var-primary text-white border-var-primary'
                        : 'bg-var-surface text-var-text border-var-border hover:border-var-primary/60 hover:text-var-primary'
                    }`}
                  >
                    {preset.label}
                    {preset.value !== 9999 && <span className="ml-1 opacity-60">{preset.value}</span>}
                  </button>
                ))}
              </div>
              {(props.maxWidth ?? 1280) !== 9999 && (
                <div className="flex items-center gap-3">
                  <input type="range" min={320} max={1920} step={16} value={props.maxWidth ?? 1280}
                    onChange={e => set({ maxWidth: Number(e.target.value) })} className="flex-1 accent-var-primary" />
                  <div className="flex items-stretch border border-var-border rounded-lg overflow-hidden bg-var-surface-hover focus-within:ring-2 focus-within:ring-var-primary">
                    <input type="number" min={320} max={1920} step={16} value={props.maxWidth ?? 1280}
                      onChange={e => set({ maxWidth: Math.min(1920, Math.max(320, Number(e.target.value))) })}
                      className="w-16 text-sm font-mono text-var-text text-center py-1 px-2 bg-transparent focus:outline-none" />
                    <span className="flex items-center px-2 text-xs font-medium text-var-text-muted bg-var-surface-hover border-l border-var-border select-none">px</span>
                  </div>
                </div>
              )}
              <p className="text-xs text-var-text-muted mt-1">Range: 320–1920px · Full removes max-width</p>
            </div>

            <PaddingControl values={paddingValues} onChange={handlePaddingChange} />
          </div>
        )}
      </div>

      <Divider />

      {/* ── 4. Background ────────────────────────────────────────────────── */}
      <div>
        <SectionLabel>Background</SectionLabel>
        <div className="w-full h-10 rounded-xl border border-var-border mb-3 flex items-center justify-center"
          style={{
            background: props.containerBackground === 'transparent'
              ? 'repeating-conic-gradient(#e5e7eb 0% 25%, white 0% 50%) 0 0 / 16px 16px'
              : props.containerBackground,
          }}
        >
          {props.containerBackground === 'transparent' && (
            <span className="text-xs text-var-text-muted bg-var-surface/80 px-2 py-0.5 rounded">Transparent</span>
          )}
        </div>
        <div className="flex flex-wrap gap-2 mb-3">
          {BACKGROUND_PRESETS.map(preset => (
            <button key={preset.value} type="button" onClick={() => handleBgPreset(preset.value)}
              className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg border transition-colors ${
                activeBgPreset === preset.value
                  ? 'border-var-primary bg-var-primary-muted text-var-primary'
                  : 'border-var-border bg-var-surface text-var-text hover:border-var-border-strong'
              }`}
            >
              {preset.value !== 'transparent' && preset.value !== 'custom' && (
                <span className="w-3 h-3 rounded-sm border border-var-border shrink-0" style={{ background: preset.value }} />
              )}
              {preset.value === 'transparent' && (
                <span className="w-3 h-3 rounded-sm border border-var-border shrink-0"
                  style={{ background: 'repeating-conic-gradient(#ccc 0% 25%, white 0% 50%) 0 0 / 8px 8px' }} />
              )}
              {preset.value === 'custom' && <span className="text-base leading-none">🎨</span>}
              {preset.label}
            </button>
          ))}
        </div>
        {activeBgPreset === 'custom' && (
          <div className="flex items-center gap-3 p-3 bg-var-surface-hover rounded-xl border border-var-border">
            <input type="color" value={customBgColor}
              onChange={e => handleCustomBgChange(e.target.value)}
              className="w-10 h-10 rounded-lg border border-var-border cursor-pointer bg-transparent" />
            <div className="flex-1">
              <p className="text-xs font-semibold text-var-text mb-1">Custom Color</p>
              <input type="text" value={customBgColor}
                onChange={e => { if (/^#[0-9a-fA-F]{0,6}$/.test(e.target.value)) handleCustomBgChange(e.target.value); }}
                placeholder="#000000"
                className="w-full text-xs font-mono border border-var-border rounded-lg px-2 py-1.5 bg-var-surface focus:outline-none focus:ring-2 focus:ring-var-primary" />
            </div>
          </div>
        )}
      </div>

      <Divider />

      {/* ── 5. Gap ───────────────────────────────────────────────────────── */}
      <SliderWithInput
        label="Column Gap"
        hint="Gap between columns · value in px"
        value={props.gap ?? 32}
        min={0} max={80} step={4}
        onChange={v => set({ gap: v })}
      />

      {/* ── 6. Sidebar-specific controls ──────────────────────────────────── */}
      {isSidebarLayout && (
        <>
          <Divider />

          <SliderWithInput
            label="Sidebar Width"
            hint="Fixed width on desktop · value in px · Range: 200–480px"
            value={props.sidebarWidth ?? 300}
            min={200} max={480} step={10}
            onChange={v => set({ sidebarWidth: v })}
          />

          <div>
            <SectionLabel>Mobile Visibility</SectionLabel>
            <div className="flex rounded-xl border border-var-border overflow-hidden">
              <button type="button" onClick={() => set({ sidebarHideOnMobile: false })}
                className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium transition-colors ${
                  !props.sidebarHideOnMobile ? 'bg-var-success text-white' : 'bg-var-surface text-var-text hover:bg-var-surface-hover'
                }`}
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z" />
                </svg>
                Show on Mobile
              </button>
              <button type="button" onClick={() => set({ sidebarHideOnMobile: true })}
                className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium transition-colors border-l border-var-border ${
                  props.sidebarHideOnMobile ? 'bg-var-warning text-white' : 'bg-var-surface text-var-text hover:bg-var-surface-hover'
                }`}
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
                </svg>
                Hide on Mobile
              </button>
            </div>
            <p className="text-xs text-var-text-muted mt-2">
              {props.sidebarHideOnMobile
                ? '📵 Sidebar hidden on mobile (below 1024px). Content will be full width.'
                : '📱 Sidebar visible on all screen sizes including mobile.'}
            </p>
          </div>

          {/* Sidebar library */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <SectionLabel>Sidebar</SectionLabel>
              <a href="/admin/dashboard/sidebars" target="_blank" rel="noreferrer"
                className="text-xs text-var-primary hover:underline">
                Manage Sidebar Library ↗
              </a>
            </div>

            {loadingSidebars ? (
              <div className="flex items-center gap-2 text-sm text-var-text-muted p-3 border border-var-border rounded-xl bg-var-surface-hover">
                <svg className="animate-spin w-4 h-4 text-var-primary" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                </svg>
                Loading sidebar library...
              </div>
            ) : savedSidebars.length === 0 ? (
              <div className="text-center py-8 border-2 border-dashed border-var-border rounded-xl bg-var-surface-hover">
                <div className="text-3xl mb-2">📐</div>
                <p className="text-sm font-medium text-var-text">No sidebars in the library yet</p>
                <p className="text-xs text-var-text-muted mt-1">Create a sidebar first, then assign it here.</p>
                <a href="/admin/dashboard/sidebars/new" target="_blank" rel="noreferrer"
                  className="inline-block mt-3 px-4 py-2 bg-var-primary text-white text-xs font-medium rounded-lg hover:bg-var-primary-hover transition-colors">
                  + Create Sidebar
                </a>
              </div>
            ) : (
              <div className="space-y-3">
                <div className="relative">
                  <select value={props.savedSidebarId || ''}
                    onChange={e => set({ savedSidebarId: e.target.value || null })}
                    className="w-full px-3 py-2.5 bg-var-input border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary text-var-text appearance-none pr-10">
                    <option value="">— No sidebar —</option>
                    {savedSidebars.map(s => (
                      <option key={s.id} value={s.id}>
                        {s.name} · {s.widgets?.length ?? 0} widget{(s.widgets?.length ?? 0) !== 1 ? 's' : ''}
                      </option>
                    ))}
                  </select>
                  <div className="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                    <svg className="w-4 h-4 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </div>
                </div>

                {selectedSidebar && (
                  <div className="border border-var-primary/40 bg-var-primary-muted rounded-xl overflow-hidden">
                    <div className="flex items-center justify-between px-4 py-3 bg-var-primary-muted/60 border-b border-var-primary/30">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="text-base">📐</span>
                        <span className="text-sm font-semibold text-var-primary-text">{selectedSidebar.name}</span>
                        <span className="text-xs bg-var-primary-muted text-var-primary-text px-2 py-0.5 rounded-full">
                          {selectedSidebar.widgets?.length ?? 0} widget{(selectedSidebar.widgets?.length ?? 0) !== 1 ? 's' : ''}
                        </span>
                      </div>
                      <a href={`/admin/dashboard/sidebars/edit/${selectedSidebar.id}`}
                        target="_blank" rel="noreferrer"
                        className="text-xs text-var-primary hover:underline font-medium shrink-0">
                        Edit ↗
                      </a>
                    </div>
                    <div className="px-4 py-3 space-y-2">
                      {selectedSidebar.widgets?.map((w, i) => {
                        const cfg = sidebarWidgetRegistry[w.type];
                        return (
                          <div key={w.id ?? i} className="flex items-center gap-2 px-3 py-2 bg-var-surface rounded-lg border border-var-primary/30 shadow-var-card">
                            <span className="text-base shrink-0">{cfg?.icon ?? '🔲'}</span>
                            <div className="min-w-0">
                              <p className="text-xs font-semibold text-var-text truncate">{cfg?.label ?? w.type}</p>
                              <p className="text-xs text-var-text-muted truncate">{cfg?.description}</p>
                            </div>
                            <span className="ml-auto text-xs text-var-text-muted shrink-0">#{i + 1}</span>
                          </div>
                        );
                      })}
                    </div>
                    <div className="px-4 py-2.5 bg-var-primary-muted/40 border-t border-var-primary/30">
                      <p className="text-xs text-var-primary-text flex items-center gap-1.5">
                        <svg className="w-3.5 h-3.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        Editing this sidebar updates it everywhere it is used.
                      </p>
                    </div>
                  </div>
                )}

                <button type="button" onClick={fetchSidebars}
                  className="w-full flex items-center justify-center gap-2 py-2 text-xs text-var-text-muted hover:text-var-primary border border-var-border rounded-lg hover:border-var-primary hover:bg-var-primary-muted transition-colors">
                  <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                  Refresh sidebar list
                </button>
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}