// app/components/admin/menu/MenuForm.tsx
'use client';

import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import toast from 'react-hot-toast';

import {
  DndContext,
  DragEndEvent,
  DragStartEvent,
  DragMoveEvent,
  KeyboardSensor,
  MeasuringStrategy,
  PointerSensor,
  UniqueIdentifier,
  closestCenter,
  useSensor,
  useSensors,
} from '@dnd-kit/core';
import {
  SortableContext,
  arrayMove,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';

// ─── Types ─────────────────────────────────────────────────────────────────────

type MenuItemType = 'page' | 'category' | 'service' | 'product' | 'tag' | 'custom_link';

export interface MenuItemNode {
  _id: string;
  id?: string;
  reference_id?: string | null;
  title?: string | null;
  type: MenuItemType;
  link?: string | null;
  children: MenuItemNode[];
  resolvedTitle?: string;
  resolvedLink?: string;
}

interface FlatItem {
  _id: string;
  id?: string;
  reference_id?: string | null;
  title?: string | null;
  type: MenuItemType;
  link?: string | null;
  resolvedTitle: string;
  resolvedLink: string;
  depth: number;
  isEditing?: boolean;
}

interface SourceItem {
  id: string;
  name: string;
  slug: string;
  type: MenuItemType;
}

interface Sources {
  [key: string]: SourceItem[];
  page: SourceItem[];
  category: SourceItem[];
  service: SourceItem[];
  product: SourceItem[];
  tag: SourceItem[];
}

interface MenuFormProps {
  menuId?: string;
  initialData?: {
    menu: { id: string; name: string; position: string };
    items: MenuItemNode[];
  };
}

// ─── Constants ──────────────────────────────────────────────────────────────────

const POSITION_LABELS: Record<string, string> = {
  top_header:    'Top Header',
  header:        'Header',
  footer_menu_1: 'Footer Menu 1',
  footer_menu_2: 'Footer Menu 2',
  footer_menu_3: 'Footer Menu 3',
};

const TYPE_LABELS: Record<string, string> = {
  page:        'Pages',
  category:    'Categories',
  custom_link: 'Custom Link',
};

const TYPE_COLORS: Record<string, string> = {
  page:        'bg-var-primary-muted text-var-primary-text',
  category:    'bg-var-success-bg text-var-success-text',
  custom_link: 'bg-var-surface-hover text-var-text-muted',
};

const SLUG_PREFIX: Record<string, string> = {
  page:     '',
  category: '/category',
};

const INDENT_PX = 40;
const MAX_DEPTH = 2;
const PX_PER_LVL = 40;

let _idCounter = 0;
function genId() { return `local_${Date.now()}_${++_idCounter}`; }

// ─── Tree ↔ Flat helpers ────────────────────────────────────────────────────────

function flattenTree(nodes: MenuItemNode[], depth = 0): FlatItem[] {
  const result: FlatItem[] = [];
  for (const node of nodes) {
    result.push({
      _id: node._id,
      id: node.id,
      reference_id: node.reference_id,
      title: node.title,
      type: node.type,
      link: node.link,
      resolvedTitle: node.resolvedTitle ?? node.title ?? '(unknown)',
      resolvedLink: node.resolvedLink ?? node.link ?? '#',
      depth,
    });
    if (node.children?.length) result.push(...flattenTree(node.children, depth + 1));
  }
  return result;
}

function buildTree(flat: FlatItem[]): MenuItemNode[] {
  const roots: MenuItemNode[] = [];
  const stack: { node: MenuItemNode; depth: number }[] = [];
  for (const item of flat) {
    const node: MenuItemNode = {
      _id: item._id, id: item.id, reference_id: item.reference_id,
      title: item.title, type: item.type, link: item.link, children: [],
    };
    while (stack.length && stack[stack.length - 1].depth >= item.depth) stack.pop();
    if (!stack.length) roots.push(node);
    else stack[stack.length - 1].node.children.push(node);
    stack.push({ node, depth: item.depth });
  }
  return roots;
}

function serializeItems(nodes: MenuItemNode[]): object[] {
  return nodes.map((node) => ({
    id:           node.id,
    reference_id: node.reference_id,
    title:        node.title,
    type:         node.type,
    link:         node.link,
    children:     serializeItems(node.children),
  }));
}

// ─── SortableItem ───────────────────────────────────────────────────────────────

interface SortableItemProps {
  item: FlatItem;
  activeId: string | null;
  dragOffset: { x: number; y: number } | null;
  onDelete: (id: string) => void;
  onToggleEdit: (id: string) => void;
  onUpdateTitle: (id: string, v: string) => void;
  onUpdateLink: (id: string, v: string) => void;
}

const SortableItem = React.memo(function SortableItem({
  item,
  activeId,
  dragOffset,
  onDelete,
  onToggleEdit,
  onUpdateTitle,
  onUpdateLink,
}: SortableItemProps) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ 
    id: item._id,
    animateLayoutChanges: () => false,
  });

  const isActive = item._id === activeId;
  const visualDepth = item.depth;
  const horizontalOffset = isActive && dragOffset ? dragOffset.x : 0;
  
  const finalTransform = transform ? {
    x: horizontalOffset,
    y: transform.y,
    scaleX: 1,
    scaleY: 1,
  } : null;

  const marginLeft = `${visualDepth * INDENT_PX}px`;

  const style: React.CSSProperties = {
    transform: finalTransform ? CSS.Transform.toString(finalTransform) : undefined,
    transition: isDragging ? 'none' : transition,
    marginLeft: isActive ? '0px' : marginLeft,
    opacity: isDragging ? 0.9 : 1,
    zIndex: isDragging ? 9999 : 'auto',
    position: 'relative' as const,
    pointerEvents: isDragging ? ('none' as const) : ('auto' as const),
    width: '100%',
  };

  return (
    <div ref={setNodeRef} style={style} className="relative">
      {isActive && dragOffset && (
        <div 
          className="absolute left-0 top-0 h-full pointer-events-none"
          style={{ 
            width: marginLeft,
            background: 'linear-gradient(90deg, var(--primary-muted) 0%, transparent 100%)',
            borderLeft: '2px dashed var(--primary)',
          }}
        />
      )}
      
      <div
        className={`
          group relative border rounded-xl select-none
          ${isActive
            ? 'border-var-primary bg-var-primary-muted shadow-var-card ring-2 ring-var-primary'
            : 'border-var-border bg-var-surface hover:border-var-border-strong hover:shadow-var-card'
          }
          ${isDragging ? 'shadow-var-modal cursor-grabbing' : ''}
          transition-shadow duration-150
        `}
      >
        {item.depth > 0 && !isActive && (
          <div
            className="absolute pointer-events-none bg-var-border"
            style={{ left: `-${INDENT_PX - 8}px`, top: '50%', width: `${INDENT_PX - 12}px`, height: '1px' }}
          />
        )}

        <div className="flex items-center px-3 py-2.5 gap-3">
          <div
            {...attributes}
            {...listeners}
            className="text-var-text-muted hover:text-var-text shrink-0 transition-colors cursor-grab active:cursor-grabbing touch-none"
            title="Drag up/down to reorder · drag right to nest · drag left to un-nest"
          >
            <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
              <path d="M7 2a2 2 0 110 4 2 2 0 010-4zm6 0a2 2 0 110 4 2 2 0 010-4zM7 8a2 2 0 110 4 2 2 0 010-4zm6 0a2 2 0 110 4 2 2 0 010-4zM7 14a2 2 0 110 4 2 2 0 010-4zm6 0a2 2 0 110 4 2 2 0 010-4z" />
            </svg>
          </div>

          <span className={`text-xs font-medium px-1.5 py-0.5 rounded shrink-0 ${TYPE_COLORS[item.type]}`}>
            {item.type.replace('_', ' ')}
          </span>

          {isActive && dragOffset && Math.abs(dragOffset.x) > PX_PER_LVL / 2 && (
            <span className="text-xs font-medium text-var-primary bg-var-primary-muted px-1.5 py-0.5 rounded shrink-0">
              {dragOffset.x > 0 ? '↳ Nest' : '↰ Un-nest'}
            </span>
          )}

          {!isActive && visualDepth > 0 && (
            <span className="text-xs text-var-text-muted bg-var-surface-hover px-1.5 py-0.5 rounded shrink-0">
              {visualDepth === 1 ? 'Sub-item' : 'Sub-sub-item'}
            </span>
          )}

          <div className="flex-1 min-w-0">
            {item.isEditing ? (
              <div className="flex flex-col gap-1.5" onClick={(e) => e.stopPropagation()}>
                <input
                  type="text"
                  value={item.title ?? item.resolvedTitle}
                  onChange={(e) => onUpdateTitle(item._id, e.target.value)}
                  className="w-full px-2 py-1 text-sm bg-var-input border border-var-border rounded-lg focus:ring-2 focus:ring-var-primary text-var-text placeholder-var-input"
                  placeholder="Navigation label"
                  autoFocus
                />
                {item.type === 'custom_link' && (
                  <input
                    type="text"
                    value={item.link ?? ''}
                    onChange={(e) => onUpdateLink(item._id, e.target.value)}
                    className="w-full px-2 py-1 text-sm bg-var-input border border-var-border rounded-lg focus:ring-2 focus:ring-var-primary text-var-text placeholder-var-input"
                    placeholder="https://…"
                  />
                )}
              </div>
            ) : (
              <div>
                <span className="text-sm font-medium text-var-text truncate block">
                  {item.type === 'custom_link' ? (item.title || item.resolvedTitle) : item.resolvedTitle}
                </span>
                <span className="text-xs text-var-text-muted truncate block">{item.resolvedLink}</span>
              </div>
            )}
          </div>

          <div className="flex items-center gap-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
            <button
              type="button"
              onClick={() => onToggleEdit(item._id)}
              className={`p-1.5 rounded-lg transition-colors ${
                item.isEditing ? 'text-var-primary bg-var-primary-muted' : 'text-var-text-muted hover:text-var-primary hover:bg-var-primary-muted'
              }`}
              title={item.isEditing ? 'Done' : 'Edit label'}
            >
              {item.isEditing ? (
                <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
                </svg>
              ) : (
                <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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                </svg>
              )}
            </button>
            <button
              type="button"
              onClick={() => onDelete(item._id)}
              className="p-1.5 rounded-lg text-var-text-muted hover:text-var-danger hover:bg-var-danger-bg transition-colors"
              title="Remove"
            >
              <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="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
});

// ─── Main Component ─────────────────────────────────────────────────────────────

export default function MenuForm({ menuId, initialData }: MenuFormProps) {
  const router = useRouter();

  const [loading, setLoading] = useState(false);
  const [sourcesLoading, setSourcesLoading] = useState(true);
  const [activeSourceTab, setActiveSourceTab] = useState<string>('page');
  const [selectedSourceItems, setSelectedSourceItems] = useState<Set<string>>(new Set());
  const [sources, setSources] = useState<Sources>({ page: [], category: [], service: [], product: [], tag: [] });
  const [sourceSearch, setSourceSearch] = useState('');
  const [customLinkUrl, setCustomLinkUrl] = useState('');
  const [customLinkLabel, setCustomLinkLabel] = useState('');
  const [formData, setFormData] = useState({
    name: initialData?.menu?.name ?? '',
    position: initialData?.menu?.position ?? 'header',
  });
  const [flatItems, setFlatItems] = useState<FlatItem[]>([]);

  const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null);
  const [dragOffset, setDragOffset] = useState<{ x: number; y: number } | null>(null);
  const [depthIndicator, setDepthIndicator] = useState<'nest' | 'unnest' | null>(null);
  const depthTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const startDepthRef = useRef<number>(0);
  const startXRef = useRef<number>(0);

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 3 } }),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  );

  useEffect(() => {
    fetch('/api/backend/admin/menus/sources')
      .then((r) => r.json())
      .then((d) => setSources(d.sources as Sources))
      .catch(() => toast.error('Failed to load source items'))
      .finally(() => setSourcesLoading(false));
  }, []);

  useEffect(() => {
    if (initialData?.items) {
      const map = (nodes: MenuItemNode[]): MenuItemNode[] =>
        nodes.map((n) => ({ ...n, _id: genId(), children: map(n.children ?? []) }));
      setFlatItems(flattenTree(map(initialData.items)));
    }
  }, [initialData]);

  const handleDragStart = useCallback((event: DragStartEvent) => {
    const id = event.active.id as string;
    setActiveId(id);
    const item = flatItems.find((i) => i._id === id);
    startDepthRef.current = item?.depth ?? 0;
    startXRef.current = (event.activatorEvent as PointerEvent).clientX;
    setDragOffset({ x: 0, y: 0 });
  }, [flatItems]);

  const handleDragMove = useCallback((event: DragMoveEvent) => {
    const { delta } = event;
    const smoothedX = Math.round(delta.x / 2) * 2;
    setDragOffset({ x: smoothedX, y: delta.y });
    
    if (activeId) {
      const item = flatItems.find((i) => i._id === activeId);
      if (item) {
        const levelsDelta = Math.round(delta.x / PX_PER_LVL);
        const newDepth = Math.max(0, Math.min(MAX_DEPTH, startDepthRef.current + levelsDelta));
        
        if (newDepth > startDepthRef.current) setDepthIndicator('nest');
        else if (newDepth < startDepthRef.current) setDepthIndicator('unnest');
        else setDepthIndicator(null);
        
        if (depthTimer.current) clearTimeout(depthTimer.current);
        depthTimer.current = setTimeout(() => setDepthIndicator(null), 900);
      }
    }
  }, [activeId, flatItems]);

  const handleDragEnd = useCallback((event: DragEndEvent) => {
    const { active, over } = event;
    const finalOffset = dragOffset;
    
    setActiveId(null);
    setDragOffset(null);
    setDepthIndicator(null);
    
    if (!over || active.id === over.id) return;
    
    setFlatItems((prev) => {
      const oldIndex = prev.findIndex((i) => i._id === active.id);
      const newIndex = prev.findIndex((i) => i._id === over.id);
      if (oldIndex === -1 || newIndex === -1) return prev;
      
      const reordered = arrayMove(prev, oldIndex, newIndex);
      let newDepth = startDepthRef.current;
      if (finalOffset) {
        const levelsDelta = Math.round(finalOffset.x / PX_PER_LVL);
        newDepth = Math.max(0, Math.min(MAX_DEPTH, startDepthRef.current + levelsDelta));
      }
      
      if (newIndex > 0) {
        const aboveItem = reordered[newIndex - 1];
        newDepth = Math.min(newDepth, aboveItem.depth + 1);
      } else newDepth = 0;
      
      return reordered.map((item, index) => 
        index === newIndex ? { ...item, depth: newDepth } : item
      );
    });
  }, [dragOffset]);

  const handleDragCancel = useCallback(() => {
    setActiveId(null);
    setDragOffset(null);
    setDepthIndicator(null);
  }, []);

  const currentSourceItems = useCallback((): SourceItem[] => {
    if (activeSourceTab === 'custom_link') return [];
    const items = sources[activeSourceTab] ?? [];
    if (!sourceSearch) return items;
    return items.filter((i) => i.name.toLowerCase().includes(sourceSearch.toLowerCase()));
  }, [activeSourceTab, sources, sourceSearch]);

  const filteredSourceItems = useMemo(() => currentSourceItems(), [currentSourceItems]);
  const allSelected = filteredSourceItems.length > 0 &&
    filteredSourceItems.every((i) => selectedSourceItems.has(i.id));

  const toggleSourceItem = useCallback((id: string) => {
    setSelectedSourceItems((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }, []);

  const toggleSelectAll = useCallback(() => {
    const items = filteredSourceItems;
    const all = items.every((i) => selectedSourceItems.has(i.id));
    setSelectedSourceItems((prev) => {
      const next = new Set(prev);
      if (all) items.forEach((i) => next.delete(i.id));
      else items.forEach((i) => next.add(i.id));
      return next;
    });
  }, [filteredSourceItems, selectedSourceItems]);

  const addSelectedToMenu = useCallback(() => {
    if (activeSourceTab === 'custom_link') {
      if (!customLinkUrl.trim()) { toast.error('Please enter a URL'); return; }
      setFlatItems((prev) => [...prev, {
        _id: genId(), type: 'custom_link',
        title: customLinkLabel || customLinkUrl, link: customLinkUrl,
        resolvedTitle: customLinkLabel || customLinkUrl, resolvedLink: customLinkUrl,
        depth: 0,
      }]);
      setCustomLinkUrl(''); setCustomLinkLabel('');
      toast.success('Custom link added');
      return;
    }
    const items = filteredSourceItems.filter((i) => selectedSourceItems.has(i.id));
    if (!items.length) { toast.error('Select at least one item'); return; }
    const prefix = SLUG_PREFIX[activeSourceTab] ?? '';
    setFlatItems((prev) => [...prev, ...items.map((i) => ({
      _id: genId(), reference_id: i.id,
      type: activeSourceTab as MenuItemType,
      resolvedTitle: i.name, resolvedLink: `${prefix}/${i.slug}`,
      depth: 0,
    }))]);
    setSelectedSourceItems(new Set());
    toast.success(`${items.length} item(s) added`);
  }, [activeSourceTab, customLinkUrl, customLinkLabel, filteredSourceItems, selectedSourceItems]);

  const deleteItem = useCallback((_id: string) => {
    setFlatItems((prev) => {
      const idx = prev.findIndex((i) => i._id === _id);
      if (idx === -1) return prev;
      const depth = prev[idx].depth;
      let end = idx + 1;
      while (end < prev.length && prev[end].depth > depth) end++;
      return [...prev.slice(0, idx), ...prev.slice(end)];
    });
  }, []);

  const toggleEdit = useCallback((_id: string) =>
    setFlatItems((prev) => prev.map((i) => i._id === _id ? { ...i, isEditing: !i.isEditing } : i))
  , []);

  const updateTitle = useCallback((_id: string, value: string) =>
    setFlatItems((prev) => prev.map((i) =>
      i._id === _id ? { ...i, title: value, resolvedTitle: value } : i
    ))
  , []);

  const updateLink = useCallback((_id: string, value: string) =>
    setFlatItems((prev) => prev.map((i) =>
      i._id === _id ? { ...i, link: value, resolvedLink: value } : i
    ))
  , []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.name.trim()) { toast.error('Menu name is required'); return; }
    setLoading(true);
    try {
      const tree = buildTree(flatItems);
      const url = menuId ? `/api/backend/admin/menus/${menuId}` : '/api/backend/admin/menus';
      const res = await fetch(url, {
        method: menuId ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...formData, items: serializeItems(tree) }),
      });
      const data = await res.json();
      if (res.ok) {
        toast.success(menuId ? 'Menu updated!' : 'Menu created!');
        router.push('/admin/dashboard/menus');
        router.refresh();
      } else {
        toast.error(data.error || 'Failed to save menu');
      }
    } catch {
      toast.error('Failed to save menu');
    } finally {
      setLoading(false);
    }
  };

  const itemIds = useMemo(() => flatItems.map((i) => i._id), [flatItems]);
  const subItemCount = flatItems.filter((i) => i.depth > 0).length;

  return (
    <div className="max-w-7xl mx-auto">
      <div className="bg-var-surface rounded-2xl shadow-var-card border border-var-border overflow-hidden">
        {/* Header */}
        <div className="px-6 py-4 border-b border-var-border bg-linear-to-r from-var-surface-hover to-var-surface">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-xl font-semibold text-var-text">
                {menuId ? 'Edit Menu' : 'Create New Menu'}
              </h2>
              <p className="text-sm text-var-text-secondary mt-1">
                Slugs are resolved live — slug changes in source content auto-update here
              </p>
            </div>
            <Link
              href="/admin/dashboard/menus"
              className="inline-flex items-center px-4 py-2 text-sm font-medium text-var-text-secondary bg-var-surface border border-var-border rounded-xl hover:bg-var-surface-hover transition-colors"
            >
              <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
              Back to Menus
            </Link>
          </div>
        </div>

        <form onSubmit={handleSubmit}>
          {/* Settings bar */}
          <div className="px-6 py-4 border-b border-var-border bg-var-surface-hover/40">
            <div className="flex flex-col sm:flex-row gap-4">
              <div className="flex-1">
                <label className="block text-sm font-medium text-var-text mb-1.5">
                  Menu Name <span className="text-var-danger">*</span>
                </label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData((p) => ({ ...p, name: e.target.value }))}
                  className="w-full px-3 py-2 bg-var-input border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary text-var-text placeholder-var-input"
                  placeholder="e.g. Main Navigation"
                  required
                />
              </div>
              <div className="sm:w-56">
                <label className="block text-sm font-medium text-var-text mb-1.5">Position</label>
                <select
                  value={formData.position}
                  onChange={(e) => setFormData((p) => ({ ...p, position: e.target.value }))}
                  className="w-full px-3 py-2 bg-var-input border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary text-var-text"
                >
                  {Object.entries(POSITION_LABELS).map(([val, label]) => (
                    <option key={val} value={val}>{label}</option>
                  ))}
                </select>
              </div>
            </div>
          </div>

          {/* Main editor */}
          <div className="flex divide-x divide-var-border" style={{ minHeight: '580px' }}>
            {/* LEFT: Source sidebar */}
            <div className="w-80 shrink-0 flex flex-col bg-var-surface-hover/30">
              <div className="px-4 pt-4 pb-2">
                <p className="text-xs font-semibold text-var-text-muted uppercase tracking-wider mb-2">Add Menu Items</p>
                <div className="flex flex-wrap gap-1">
                  {Object.entries(TYPE_LABELS).map(([tab, label]) => (
                    <button
                      key={tab} type="button"
                      onClick={() => { setActiveSourceTab(tab); setSelectedSourceItems(new Set()); setSourceSearch(''); }}
                      className={`px-2.5 py-1 text-xs font-medium rounded-lg transition-colors ${
                        activeSourceTab === tab ? 'bg-var-primary text-white' : 'bg-var-surface text-var-text-secondary border border-var-border hover:bg-var-surface-hover'
                      }`}
                    >{label}</button>
                  ))}
                </div>
              </div>

              {activeSourceTab === 'custom_link' ? (
                <div className="flex-1 px-4 py-3 flex flex-col gap-3">
                  <div>
                    <label className="block text-xs font-medium text-var-text mb-1">URL</label>
                    <input type="text" value={customLinkUrl} onChange={(e) => setCustomLinkUrl(e.target.value)}
                      placeholder="https://example.com"
                      className="w-full px-3 py-2 text-sm bg-var-input border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary text-var-text placeholder-var-input" />
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-var-text mb-1">Link Text</label>
                    <input type="text" value={customLinkLabel} onChange={(e) => setCustomLinkLabel(e.target.value)}
                      placeholder="Label (optional)"
                      className="w-full px-3 py-2 text-sm bg-var-input border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary text-var-text placeholder-var-input" />
                  </div>
                  <button type="button" onClick={addSelectedToMenu}
                    className="w-full py-2 text-sm font-medium text-white bg-var-primary rounded-xl hover:bg-var-primary-hover transition-colors shadow-var-button">
                    Add to Menu
                  </button>
                </div>
              ) : (
                <>
                  <div className="px-4 pb-2">
                    <div className="relative">
                      <svg className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                      </svg>
                      <input type="text" value={sourceSearch} onChange={(e) => setSourceSearch(e.target.value)}
                        placeholder={`Search ${TYPE_LABELS[activeSourceTab] ?? ''}…`}
                        className="w-full pl-8 pr-3 py-1.5 text-sm bg-var-input border border-var-border rounded-lg focus:ring-2 focus:ring-var-primary text-var-text placeholder-var-input" />
                    </div>
                  </div>

                  {filteredSourceItems.length > 0 && (
                    <div className="px-4 pb-1 flex items-center justify-between">
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" checked={allSelected} onChange={toggleSelectAll}
                          className="w-3.5 h-3.5 text-var-primary border-var-border rounded focus:ring-var-primary" />
                        <span className="text-xs text-var-text-muted">Select all</span>
                      </label>
                      <span className="text-xs text-var-text-muted">{filteredSourceItems.length} items</span>
                    </div>
                  )}

                  <div className="flex-1 overflow-y-auto px-4 pb-2" style={{ maxHeight: '360px' }}>
                    {sourcesLoading ? (
                      <div className="space-y-2 mt-1">
                        {Array.from({ length: 5 }).map((_, i) => (
                          <div key={i} className="h-8 bg-var-surface-hover rounded-lg animate-pulse" />
                        ))}
                      </div>
                    ) : filteredSourceItems.length === 0 ? (
                      <p className="text-center text-sm text-var-text-muted py-8">No items found</p>
                    ) : (
                      <div className="space-y-1 mt-1">
                        {filteredSourceItems.map((item) => (
                          <label key={item.id}
                            className={`flex items-center gap-2.5 px-2.5 py-2 rounded-lg cursor-pointer transition-colors ${
                              selectedSourceItems.has(item.id) ? 'bg-var-primary-muted border border-var-primary' : 'hover:bg-var-surface border border-transparent'
                            }`}>
                            <input type="checkbox" checked={selectedSourceItems.has(item.id)} onChange={() => toggleSourceItem(item.id)}
                              className="w-3.5 h-3.5 text-var-primary border-var-border rounded focus:ring-var-primary shrink-0" />
                            <div className="min-w-0">
                              <p className="text-sm font-medium text-var-text truncate">{item.name}</p>
                              <p className="text-xs text-var-text-muted truncate">/{item.slug}</p>
                            </div>
                          </label>
                        ))}
                      </div>
                    )}
                  </div>

                  <div className="px-4 pb-4 pt-2 border-t border-var-border">
                    <button type="button" onClick={addSelectedToMenu} disabled={selectedSourceItems.size === 0}
                      className="w-full py-2 text-sm font-medium text-white bg-var-primary rounded-xl hover:bg-var-primary-hover disabled:opacity-40 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2 shadow-var-button">
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                      </svg>
                      Add to Menu
                      {selectedSourceItems.size > 0 && (
                        <span className="bg-white/20 text-xs px-1.5 py-0.5 rounded-full">{selectedSourceItems.size}</span>
                      )}
                    </button>
                  </div>
                </>
              )}
            </div>

            {/* RIGHT: DnD builder */}
            <div className="flex-1 flex flex-col min-w-0">
              {/* Instructions + depth hint */}
              <div className="px-6 pt-4 pb-3 border-b border-var-border">
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <p className="text-sm font-semibold text-var-text">Menu Structure</p>
                    <div className="flex flex-wrap items-center gap-x-4 gap-y-1 mt-1.5">
                      <span className="flex items-center gap-1 text-xs text-var-text-muted">
                        <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="M7 16V4m0 0L3 8m4-4l4 4M17 8v12m0 0l4-4m-4 4l-4-4" />
                        </svg>
                        Drag up/down to reorder
                      </span>
                      <span className="flex items-center gap-1 text-xs text-var-info font-medium">
                        <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="M14 5l7 7m0 0l-7 7m7-7H3" />
                        </svg>
                        Drag RIGHT to nest (max 3 levels)
                      </span>
                      <span className="flex items-center gap-1 text-xs text-var-warning font-medium">
                        <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="M10 19l-7-7m0 0l7-7m-7 7h18" />
                        </svg>
                        Drag LEFT to un-nest
                      </span>
                    </div>
                  </div>
                  {flatItems.length > 0 && (
                    <span className="shrink-0 text-xs text-var-text-muted bg-var-surface-hover px-2 py-1 rounded-full">
                      {flatItems.length} item{flatItems.length !== 1 ? 's' : ''}
                    </span>
                  )}
                </div>

                <div
                  className="overflow-hidden transition-all duration-200"
                  style={{ maxHeight: depthIndicator ? '40px' : '0', marginTop: depthIndicator ? '8px' : '0' }}
                >
                  {depthIndicator === 'nest' && (
                    <div className="flex items-center gap-2 text-xs font-medium text-var-info bg-var-info-bg border border-var-info-border px-3 py-1.5 rounded-lg">
                      <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="M9 5l7 7-7 7" />
                      </svg>
                      Nesting deeper — release to place
                    </div>
                  )}
                  {depthIndicator === 'unnest' && (
                    <div className="flex items-center gap-2 text-xs font-medium text-var-warning bg-var-warning-bg border border-var-warning-border px-3 py-1.5 rounded-lg">
                      <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="M15 19l-7-7 7-7" />
                      </svg>
                      Moving to higher level — release to place
                    </div>
                  )}
                </div>
              </div>

              {/* Item list */}
              <div className="flex-1 px-6 py-4 overflow-y-auto">
                {flatItems.length === 0 ? (
                  <div className="flex flex-col items-center justify-center h-full text-center py-16">
                    <div className="w-16 h-16 bg-var-surface-hover rounded-2xl flex items-center justify-center mb-4">
                      <svg className="w-8 h-8 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 6h16M4 12h16M4 18h7" />
                      </svg>
                    </div>
                    <p className="text-var-text font-medium">Your menu is empty</p>
                    <p className="text-sm text-var-text-muted mt-1">Select items on the left and click Add to Menu</p>
                  </div>
                ) : (
                  <DndContext
                    sensors={sensors}
                    collisionDetection={closestCenter}
                    measuring={{ droppable: { strategy: MeasuringStrategy.Always } }}
                    onDragStart={handleDragStart}
                    onDragMove={handleDragMove}
                    onDragEnd={handleDragEnd}
                    onDragCancel={handleDragCancel}
                  >
                    <SortableContext items={itemIds} strategy={verticalListSortingStrategy}>
                      <div className="space-y-1.5">
                        {flatItems.map((item) => (
                          <SortableItem
                            key={item._id}
                            item={item}
                            activeId={activeId as string}
                            dragOffset={dragOffset}
                            onDelete={deleteItem}
                            onToggleEdit={toggleEdit}
                            onUpdateTitle={updateTitle}
                            onUpdateLink={updateLink}
                          />
                        ))}
                      </div>
                    </SortableContext>
                  </DndContext>
                )}
              </div>
            </div>
          </div>

          {/* Footer */}
          <div className="px-6 py-4 border-t border-var-border bg-var-surface-hover/30 flex items-center justify-between">
            <p className="text-sm text-var-text-muted">
              {flatItems.length > 0
                ? `${flatItems.length} item${flatItems.length !== 1 ? 's' : ''} · ${subItemCount} sub-item${subItemCount !== 1 ? 's' : ''}`
                : 'No items yet'}
            </p>
            <div className="flex items-center gap-3">
              <Link href="/admin/dashboard/menus"
                className="px-5 py-2 text-sm font-medium text-var-text-secondary bg-var-surface border border-var-border rounded-xl hover:bg-var-surface-hover transition-colors">
                Cancel
              </Link>
              <button type="submit" disabled={loading}
                className="inline-flex items-center px-4 py-2 bg-var-primary text-white font-medium rounded-xl hover:bg-var-primary-hover transition-all duration-200 shadow-var-button hover:shadow-var-card">
                {loading ? (
                  <>
                    <svg className="animate-spin h-4 w-4" 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 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                    </svg>
                    {menuId ? 'Updating…' : 'Creating…'}
                  </>
                ) : (menuId ? 'Update Menu' : 'Create Menu')}
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}