import React, { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import {
  Plus,
  Trash2,
  GripVertical,
  Layers,
  SplitSquareVertical,
  ChevronDown,
  ChevronRight,
  Zap,
  Loader2,
  Box,
  Settings2,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { screenApi } from "@/lib/api/screen";
import { apiClient } from "@/lib/api/client";
import { toast } from "sonner";
import { ComponentData, ConditionalZone } from "@/types/screen-management";

// DB 레이어 타입
interface DBLayer {
  layer_id: number;
  layer_name: string;
  condition_config: any;
  component_count: number;
  updated_at: string;
}

interface LayerManagerPanelProps {
  screenId: number | null;
  activeLayerId: number; // 현재 활성 레이어 ID (DB layer_id)
  onLayerChange: (layerId: number) => void; // 레이어 전환
  components?: ComponentData[]; // 현재 활성 레이어의 컴포넌트 (폴백용)
  zones?: ConditionalZone[]; // Zone 목록 (ScreenDesigner에서 전달)
  onZonesChange?: (zones: ConditionalZone[]) => void; // Zone 목록 변경 콜백
}

export const LayerManagerPanel: React.FC<LayerManagerPanelProps> = ({
  screenId,
  activeLayerId,
  onLayerChange,
  components = [],
  zones: externalZones,
  onZonesChange,
}) => {
  const [layers, setLayers] = useState<DBLayer[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  // 펼침/접힘 상태: zone_id별
  const [expandedZones, setExpandedZones] = useState<Set<number>>(new Set());
  // Zone에 레이어 추가 시 조건값 입력 상태
  const [addingToZoneId, setAddingToZoneId] = useState<number | null>(null);
  const [newConditionValue, setNewConditionValue] = useState("");
  // Zone 트리거 설정 열기 상태
  const [triggerEditZoneId, setTriggerEditZoneId] = useState<number | null>(null);
  // 기본 레이어 컴포넌트 (트리거 선택용)
  const [baseLayerComponents, setBaseLayerComponents] = useState<ComponentData[]>([]);

  const zones = externalZones || [];

  // 레이어 목록 로드
  const loadLayers = useCallback(async () => {
    if (!screenId) return;
    setIsLoading(true);
    try {
      const data = await screenApi.getScreenLayers(screenId);
      setLayers(data);
    } catch (error) {
      console.error("레이어 목록 로드 실패:", error);
    } finally {
      setIsLoading(false);
    }
  }, [screenId]);

  // 기본 레이어 컴포넌트 로드
  const loadBaseLayerComponents = useCallback(async () => {
    if (!screenId) return;
    // 현재 활성 레이어가 기본 레이어(1)이면 props의 실시간 컴포넌트 사용
    if (activeLayerId === 1 && components.length > 0) {
      setBaseLayerComponents(components);
      return;
    }
    try {
      const data = await screenApi.getLayerLayout(screenId, 1);
      if (data?.components) {
        setBaseLayerComponents(data.components as ComponentData[]);
      }
    } catch {
      setBaseLayerComponents(components);
    }
  }, [screenId, components, activeLayerId]);

  useEffect(() => {
    loadLayers();
    loadBaseLayerComponents();
  }, [loadLayers, loadBaseLayerComponents]);

  // Zone별 레이어 그룹핑
  const getLayersForZone = useCallback((zoneId: number): DBLayer[] => {
    return layers.filter(l => {
      const cc = l.condition_config;
      return cc && cc.zone_id === zoneId;
    });
  }, [layers]);

  // Zone에 속하지 않는 조건부 레이어 (레거시)
  const orphanLayers = layers.filter(l => {
    if (l.layer_id === 1) return false;
    const cc = l.condition_config;
    return !cc || !cc.zone_id;
  });

  // 기본 레이어
  const baseLayer = layers.find(l => l.layer_id === 1);

  // Zone에 레이어 추가
  const handleAddLayerToZone = useCallback(async (zoneId: number) => {
    if (!screenId || !newConditionValue.trim()) return;
    try {
      const result = await screenApi.addLayerToZone(
        screenId, zoneId, newConditionValue.trim(),
        `레이어 (${newConditionValue.trim()})`,
      );
      toast.success(`레이어가 Zone에 추가되었습니다. (ID: ${result.layerId})`);
      setAddingToZoneId(null);
      setNewConditionValue("");
      await loadLayers();
      onLayerChange(result.layerId);
    } catch (error) {
      console.error("Zone 레이어 추가 실패:", error);
      toast.error("레이어 추가에 실패했습니다.");
    }
  }, [screenId, newConditionValue, loadLayers, onLayerChange]);

  // 레이어 삭제
  const handleDeleteLayer = useCallback(async (layerId: number) => {
    if (!screenId || layerId === 1) return;
    try {
      await screenApi.deleteLayer(screenId, layerId);
      toast.success("레이어가 삭제되었습니다.");
      await loadLayers();
      if (activeLayerId === layerId) onLayerChange(1);
    } catch (error) {
      console.error("레이어 삭제 실패:", error);
      toast.error("레이어 삭제에 실패했습니다.");
    }
  }, [screenId, activeLayerId, loadLayers, onLayerChange]);

  // Zone 삭제
  const handleDeleteZone = useCallback(async (zoneId: number) => {
    if (!screenId) return;
    try {
      await screenApi.deleteZone(zoneId);
      toast.success("조건부 영역이 삭제되었습니다.");
      // Zone 목록 새로고침
      const loadedZones = await screenApi.getScreenZones(screenId);
      onZonesChange?.(loadedZones);
      await loadLayers();
      onLayerChange(1);
    } catch (error) {
      console.error("Zone 삭제 실패:", error);
      toast.error("Zone 삭제에 실패했습니다.");
    }
  }, [screenId, loadLayers, onLayerChange, onZonesChange]);

  // 동적 소스 옵션 캐시 (trigger_component_id → 옵션 배열)
  const [dynamicOptionsCache, setDynamicOptionsCache] = useState<Record<string, { value: string; label: string }[]>>({});
  const [loadingDynamicOptions, setLoadingDynamicOptions] = useState<Set<string>>(new Set());
  // 이미 로드 시도한 키를 추적 (중복 요청 방지)
  const loadedKeysRef = useRef<Set<string>>(new Set());

  // 동적 소스 옵션 로드 함수
  const loadDynamicOptions = useCallback(async (triggerCompId: string, comp: ComponentData) => {
    const cacheKey = triggerCompId;
    // 이미 로드 완료 또는 로드 중이면 스킵
    if (loadedKeysRef.current.has(cacheKey)) return;
    loadedKeysRef.current.add(cacheKey);

    setLoadingDynamicOptions(prev => new Set(prev).add(cacheKey));
    try {
      const config = comp.componentConfig || {};
      const isCategory = (comp as any).inputType === "category" || (comp as any).webType === "category";
      const source = isCategory ? "category" : config.source;
      const compTableName = (comp as any).tableName || config.tableName;
      const compColumnName = (comp as any).columnName || config.columnName;
      let fetchedOptions: { value: string; label: string }[] = [];

      if (source === "category" || isCategory) {
        // 카테고리 소스: /table-categories/:tableName/:columnName/values
        const catTable = config.categoryTable || compTableName;
        const catColumn = config.categoryColumn || compColumnName;
        if (catTable && catColumn) {
          const response = await apiClient.get(`/table-categories/${catTable}/${catColumn}/values`);
          const data = response.data;
          if (data.success && data.data) {
            // 트리 구조를 평탄화 (valueCode/valueLabel 사용)
            const flattenTree = (items: any[]): { value: string; label: string }[] => {
              const result: { value: string; label: string }[] = [];
              for (const item of items) {
                result.push({ value: item.valueCode, label: item.valueLabel });
                if (item.children && item.children.length > 0) {
                  result.push(...flattenTree(item.children));
                }
              }
              return result;
            };
            fetchedOptions = flattenTree(data.data);
          }
        }
      } else if (source === "code" && config.codeGroup) {
        // 공통코드 소스
        const response = await apiClient.get(`/common-codes/categories/${config.codeGroup}/options`);
        const data = response.data;
        if (data.success && data.data) {
          fetchedOptions = data.data.map((item: { value: string; label: string }) => ({
            value: item.value,
            label: item.label,
          }));
        }
      } else if (source === "entity" && config.entityTable) {
        // 엔티티 소스
        const valueCol = config.entityValueColumn || "id";
        const labelCol = config.entityLabelColumn || "name";
        const response = await apiClient.get(`/entity/${config.entityTable}/options`, {
          params: { value: valueCol, label: labelCol },
        });
        const data = response.data;
        if (data.success && data.data) {
          fetchedOptions = data.data;
        }
      } else if ((source === "distinct" || source === "select") && compTableName && compColumnName) {
        // DISTINCT 소스
        const isValidCol = compColumnName && !compColumnName.startsWith("comp_");
        if (isValidCol) {
          const response = await apiClient.get(`/entity/${compTableName}/distinct/${compColumnName}`);
          const data = response.data;
          if (data.success && data.data) {
            fetchedOptions = data.data.map((item: { value: string; label: string }) => ({
              value: String(item.value),
              label: String(item.label),
            }));
          }
        }
      }

      setDynamicOptionsCache(prev => ({ ...prev, [cacheKey]: fetchedOptions }));
    } catch (error) {
      console.error("트리거 옵션 동적 로드 실패:", error);
      setDynamicOptionsCache(prev => ({ ...prev, [cacheKey]: [] }));
    } finally {
      setLoadingDynamicOptions(prev => {
        const next = new Set(prev);
        next.delete(cacheKey);
        return next;
      });
    }
  }, []);

  // Zone 트리거 컴포넌트 업데이트
  const handleUpdateZoneTrigger = useCallback(async (zoneId: number, triggerComponentId: string, operator: string = "eq") => {
    try {
      await screenApi.updateZone(zoneId, {
        trigger_component_id: triggerComponentId,
        trigger_operator: operator,
      });
      const loadedZones = await screenApi.getScreenZones(screenId!);
      onZonesChange?.(loadedZones);

      // 트리거 변경 시 해당 컴포넌트의 동적 옵션 캐시 초기화 → 새로 로드
      loadedKeysRef.current.delete(triggerComponentId);
      const triggerComp = baseLayerComponents.find(c => c.id === triggerComponentId);
      if (triggerComp) {
        loadDynamicOptions(triggerComponentId, triggerComp);
      }

      toast.success("트리거가 설정되었습니다.");
    } catch (error) {
      console.error("Zone 트리거 업데이트 실패:", error);
      toast.error("트리거 설정에 실패했습니다.");
    }
  }, [screenId, onZonesChange, baseLayerComponents, loadDynamicOptions]);

  // Zone 접힘/펼침 토글
  const toggleZone = (zoneId: number) => {
    setExpandedZones(prev => {
      const next = new Set(prev);
      next.has(zoneId) ? next.delete(zoneId) : next.add(zoneId);
      return next;
    });
  };

  // 트리거로 사용 가능한 컴포넌트 (select, combobox 등)
  const triggerableComponents = baseLayerComponents.filter(c =>
    ["select", "combobox", "radio-group"].some(t => c.componentType?.includes(t))
  );

  // Zone 트리거가 변경되면 동적 옵션 로드
  useEffect(() => {
    for (const zone of zones) {
      if (!zone.trigger_component_id) continue;
      const triggerComp = baseLayerComponents.find(c => c.id === zone.trigger_component_id);
      if (!triggerComp) continue;

      const config = triggerComp.componentConfig || {};
      const source = config.source;
      const isCategory = (triggerComp as any).inputType === "category" || (triggerComp as any).webType === "category";

      // 정적 옵션이 아닌 경우에만 동적 로드
      const hasStaticOptions = config.options && Array.isArray(config.options) && config.options.length > 0;
      if (!hasStaticOptions && (source === "category" || source === "code" || source === "entity" || source === "distinct" || source === "select" || isCategory)) {
        loadDynamicOptions(zone.trigger_component_id, triggerComp);
      }
    }
  }, [zones, baseLayerComponents, loadDynamicOptions]);

  // Zone의 트리거 컴포넌트에서 옵션 목록 가져오기 (정적 + 동적 지원)
  const getTriggerOptions = useCallback((zone: ConditionalZone): { value: string; label: string }[] => {
    if (!zone.trigger_component_id) return [];
    const triggerComp = baseLayerComponents.find(c => c.id === zone.trigger_component_id);
    if (!triggerComp) return [];

    const config = triggerComp.componentConfig || {};

    // 1. 정적 옵션 우선 확인
    if (config.options && Array.isArray(config.options) && config.options.length > 0) {
      return config.options
        .filter((opt: any) => opt.value)
        .map((opt: any) => ({ value: opt.value, label: opt.label || opt.value }));
    }

    // 2. 동적 소스 옵션 (캐시에서 가져오기)
    const cached = dynamicOptionsCache[zone.trigger_component_id];
    if (cached && cached.length > 0) {
      return cached;
    }

    return [];
  }, [baseLayerComponents, dynamicOptionsCache]);

  return (
    <div className="flex h-full flex-col bg-background">
      {/* 헤더 */}
      <div className="flex items-center justify-between border-b px-3 py-2">
        <div className="flex items-center gap-2">
          <Layers className="h-4 w-4 text-muted-foreground" />
          <h3 className="text-sm font-semibold">레이어</h3>
          <Badge variant="secondary" className="px-1.5 py-0 text-[10px]">
            {layers.length}
          </Badge>
        </div>
      </div>

      {/* 레이어 + Zone 목록 */}
      <ScrollArea className="flex-1">
        <div className="space-y-1 p-2">
          {isLoading ? (
            <div className="flex items-center justify-center py-8 text-muted-foreground">
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              <span className="text-sm">로딩 중...</span>
            </div>
          ) : (
            <>
              {/* 기본 레이어 */}
              {baseLayer && (
                <div
                  className={cn(
                    "flex cursor-pointer items-center gap-2 rounded-md border p-2 text-sm transition-all",
                    activeLayerId === 1
                      ? "border-primary bg-primary/5 shadow-sm"
                      : "border-transparent hover:bg-muted",
                  )}
                  onClick={() => onLayerChange(1)}
                >
                  <span className="shrink-0 rounded bg-blue-100 p-1 text-blue-700 dark:bg-blue-900 dark:text-blue-300">
                    <Layers className="h-3 w-3" />
                  </span>
                  <div className="min-w-0 flex-1">
                    <span className="truncate font-medium">{baseLayer.layer_name}</span>
                    <div className="flex items-center gap-2">
                      <Badge variant="outline" className="h-4 px-1 py-0 text-[10px]">기본</Badge>
                      <span className="text-[10px] text-muted-foreground">{baseLayer.component_count}개 컴포넌트</span>
                    </div>
                  </div>
                </div>
              )}

              {/* 조건부 영역(Zone) 목록 */}
              {zones.map((zone) => {
                const zoneLayers = getLayersForZone(zone.zone_id);
                const isExpanded = expandedZones.has(zone.zone_id);
                const isTriggerEdit = triggerEditZoneId === zone.zone_id;

                return (
                  <div key={`zone-${zone.zone_id}`} className="space-y-0">
                    {/* Zone 헤더 */}
                    <div
                      className={cn(
                        "flex cursor-pointer items-center gap-2 rounded-md border p-2 text-sm transition-all",
                        "border-amber-200 bg-amber-50/50 hover:bg-amber-100/50 dark:border-amber-800 dark:bg-amber-950/20",
                        isExpanded && "rounded-b-none border-b-0",
                      )}
                      onClick={() => toggleZone(zone.zone_id)}
                    >
                      {isExpanded ? (
                        <ChevronDown className="h-3.5 w-3.5 shrink-0 text-amber-600" />
                      ) : (
                        <ChevronRight className="h-3.5 w-3.5 shrink-0 text-amber-600" />
                      )}
                      <Box className="h-3.5 w-3.5 shrink-0 text-amber-600" />
                      <div className="min-w-0 flex-1">
                        <span className="truncate font-medium text-amber-800 dark:text-amber-300">{zone.zone_name}</span>
                        <div className="flex items-center gap-2">
                          <Badge variant="outline" className="h-4 px-1 py-0 text-[10px] border-amber-300 text-amber-700">
                            Zone
                          </Badge>
                          <span className="text-[10px] text-muted-foreground">
                            {zoneLayers.length}개 레이어 | {zone.width}x{zone.height}
                          </span>
                          {zone.trigger_component_id && (
                            <Badge variant="secondary" className="h-4 gap-0.5 px-1 py-0 text-[10px]">
                              <Zap className="h-2.5 w-2.5" /> 트리거
                            </Badge>
                          )}
                        </div>
                      </div>

                      {/* Zone 액션 버튼 */}
                      <div className="flex shrink-0 items-center gap-0.5">
                        <Button
                          variant="ghost" size="icon"
                          className="h-6 w-6 text-amber-600 hover:text-amber-800"
                          title="트리거 설정"
                          onClick={(e) => { e.stopPropagation(); setTriggerEditZoneId(isTriggerEdit ? null : zone.zone_id); }}
                        >
                          <Settings2 className="h-3.5 w-3.5" />
                        </Button>
                        <Button
                          variant="ghost" size="icon"
                          className="h-6 w-6 hover:text-destructive"
                          title="Zone 삭제"
                          onClick={(e) => { e.stopPropagation(); handleDeleteZone(zone.zone_id); }}
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </Button>
                      </div>
                    </div>

                    {/* 펼쳐진 Zone 내용 */}
                    {isExpanded && (
                      <div className={cn(
                        "rounded-b-md border border-t-0 border-amber-200 bg-amber-50/20 p-2 space-y-1",
                        "dark:border-amber-800 dark:bg-amber-950/10",
                      )}>
                        {/* 트리거 설정 패널 */}
                        {isTriggerEdit && (
                          <div className="mb-2 rounded border bg-background p-2 space-y-2">
                            <p className="text-[10px] font-medium text-muted-foreground">트리거 컴포넌트 선택</p>
                            {triggerableComponents.length === 0 ? (
                              <p className="text-[10px] text-muted-foreground">기본 레이어에 Select/Combobox/Radio 컴포넌트가 없습니다.</p>
                            ) : (
                              <div className="space-y-1">
                                {triggerableComponents.map(c => (
                                  <button
                                    key={c.id}
                                    className={cn(
                                      "w-full text-left rounded px-2 py-1 text-[11px] transition-colors",
                                      zone.trigger_component_id === c.id
                                        ? "bg-primary/10 text-primary font-medium"
                                        : "hover:bg-muted",
                                    )}
                                    onClick={() => handleUpdateZoneTrigger(zone.zone_id, c.id!)}
                                  >
                                    {c.componentConfig?.label || c.id} ({c.componentType})
                                  </button>
                                ))}
                              </div>
                            )}
                          </div>
                        )}

                        {/* Zone 소속 레이어 목록 */}
                        {zoneLayers.map((layer) => {
                          const isActive = activeLayerId === layer.layer_id;
                          const triggerOpts = getTriggerOptions(zone);
                          const currentCondValue = layer.condition_config?.condition_value || "";
                          return (
                            <div
                              key={layer.layer_id}
                              className={cn(
                                "flex cursor-pointer items-center gap-2 rounded-md border p-1.5 text-sm transition-all",
                                isActive
                                  ? "border-primary bg-primary/5 shadow-sm"
                                  : "border-transparent hover:bg-background",
                              )}
                              onClick={() => onLayerChange(layer.layer_id)}
                            >
                              <SplitSquareVertical className="h-3 w-3 shrink-0 text-amber-600" />
                              <div className="min-w-0 flex-1">
                                <span className="text-xs font-medium truncate">{layer.layer_name}</span>
                                <div className="flex items-center gap-1 mt-0.5">
                                  {triggerOpts.length > 0 ? (
                                    <Select
                                      value={currentCondValue || "_none_"}
                                      onValueChange={async (val) => {
                                        if (!screenId) return;
                                        const newVal = val === "_none_" ? "" : val;
                                        try {
                                          await screenApi.updateLayerCondition(
                                            screenId,
                                            layer.layer_id,
                                            { ...layer.condition_config, condition_value: newVal },
                                            layer.layer_name,
                                          );
                                          await loadLayers();
                                          toast.success("조건값이 변경되었습니다.");
                                        } catch {
                                          toast.error("조건값 변경에 실패했습니다.");
                                        }
                                      }}
                                    >
                                      <SelectTrigger
                                        className="h-5 text-[10px] w-auto min-w-[80px] max-w-[140px] px-1.5"
                                        onClick={(e) => e.stopPropagation()}
                                      >
                                        <SelectValue placeholder="조건값 선택" />
                                      </SelectTrigger>
                                      <SelectContent>
                                        <SelectItem value="_none_" className="text-xs text-muted-foreground">미설정</SelectItem>
                                        {triggerOpts.map(opt => (
                                          <SelectItem key={opt.value} value={opt.value} className="text-xs">
                                            {opt.label}
                                          </SelectItem>
                                        ))}
                                      </SelectContent>
                                    </Select>
                                  ) : (
                                    <span className="text-[10px] text-muted-foreground">
                                      조건값: {currentCondValue || "미설정"}
                                    </span>
                                  )}
                                  <span className="text-[10px] text-muted-foreground">
                                    | {layer.component_count}개
                                  </span>
                                </div>
                              </div>
                              <Button
                                variant="ghost" size="icon"
                                className="h-5 w-5 hover:text-destructive"
                                title="레이어 삭제"
                                onClick={(e) => { e.stopPropagation(); handleDeleteLayer(layer.layer_id); }}
                              >
                                <Trash2 className="h-3 w-3" />
                              </Button>
                            </div>
                          );
                        })}

                        {/* 레이어 추가 */}
                        {addingToZoneId === zone.zone_id ? (
                          <div className="flex items-center gap-1 rounded border bg-background p-1.5">
                            {(() => {
                              // 동적 옵션 로딩 중 표시
                              const isLoadingOpts = zone.trigger_component_id ? loadingDynamicOptions.has(zone.trigger_component_id) : false;
                              if (isLoadingOpts) {
                                return (
                                  <div className="flex items-center gap-1 flex-1 text-[11px] text-muted-foreground">
                                    <Loader2 className="h-3 w-3 animate-spin" />
                                    옵션 로딩 중...
                                  </div>
                                );
                              }

                              const triggerOpts = getTriggerOptions(zone);
                              // 이미 사용된 조건값 제외
                              const usedValues = new Set(
                                zoneLayers.map(l => l.condition_config?.condition_value).filter(Boolean)
                              );
                              const availableOpts = triggerOpts.filter(o => !usedValues.has(o.value));

                              if (availableOpts.length > 0) {
                                return (
                                  <Select value={newConditionValue} onValueChange={setNewConditionValue}>
                                    <SelectTrigger className="h-6 text-[11px] flex-1">
                                      <SelectValue placeholder="조건값 선택" />
                                    </SelectTrigger>
                                    <SelectContent>
                                      {availableOpts.map(opt => (
                                        <SelectItem key={opt.value} value={opt.value} className="text-xs">
                                          {opt.label}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                );
                              }
                              return (
                                <Input
                                  value={newConditionValue}
                                  onChange={(e) => setNewConditionValue(e.target.value)}
                                  placeholder="조건값 입력"
                                  className="h-6 text-[11px] flex-1"
                                  autoFocus
                                  onKeyDown={(e) => { if (e.key === "Enter") handleAddLayerToZone(zone.zone_id); }}
                                />
                              );
                            })()}
                            <Button
                              variant="default" size="sm"
                              className="h-6 px-2 text-[10px]"
                              onClick={() => handleAddLayerToZone(zone.zone_id)}
                              disabled={!newConditionValue.trim()}
                            >
                              추가
                            </Button>
                            <Button
                              variant="ghost" size="sm"
                              className="h-6 px-1 text-[10px]"
                              onClick={() => { setAddingToZoneId(null); setNewConditionValue(""); }}
                            >
                              취소
                            </Button>
                          </div>
                        ) : (
                          <Button
                            variant="outline" size="sm"
                            className="h-6 w-full gap-1 text-[10px] border-dashed"
                            onClick={() => setAddingToZoneId(zone.zone_id)}
                          >
                            <Plus className="h-3 w-3" />
                            레이어 추가
                          </Button>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}

              {/* 고아 레이어 (Zone에 소속되지 않은 조건부 레이어) */}
              {orphanLayers.length > 0 && (
                <div className="mt-2 space-y-1">
                  <p className="text-[10px] font-medium text-muted-foreground px-1">Zone 미할당 레이어</p>
                  {orphanLayers.map((layer) => {
                    const isActive = activeLayerId === layer.layer_id;
                    return (
                      <div
                        key={layer.layer_id}
                        className={cn(
                          "flex cursor-pointer items-center gap-2 rounded-md border p-2 text-sm transition-all",
                          isActive
                            ? "border-primary bg-primary/5 shadow-sm"
                            : "border-transparent hover:bg-muted",
                        )}
                        onClick={() => onLayerChange(layer.layer_id)}
                      >
                        <GripVertical className="h-4 w-4 shrink-0 cursor-grab text-muted-foreground" />
                        <div className="min-w-0 flex-1">
                          <span className="truncate font-medium">{layer.layer_name}</span>
                          <div className="flex items-center gap-2">
                            <Badge variant="outline" className="h-4 px-1 py-0 text-[10px]">조건부</Badge>
                            <span className="text-[10px] text-muted-foreground">{layer.component_count}개</span>
                          </div>
                        </div>
                        <Button
                          variant="ghost" size="icon"
                          className="h-6 w-6 hover:text-destructive"
                          onClick={(e) => { e.stopPropagation(); handleDeleteLayer(layer.layer_id); }}
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </Button>
                      </div>
                    );
                  })}
                </div>
              )}
            </>
          )}
        </div>
      </ScrollArea>

      {/* Zone 생성 드래그 영역 */}
      <div className="border-t px-3 py-2 space-y-1">
        <div
          className="flex cursor-grab items-center gap-2 rounded border border-dashed border-amber-300 bg-amber-50/50 px-2 py-1.5 text-xs text-amber-700 dark:border-amber-700 dark:bg-amber-950/20 dark:text-amber-400"
          draggable
          onDragStart={(e) => {
            e.dataTransfer.setData("application/json", JSON.stringify({ type: "create-zone" }));
            e.dataTransfer.effectAllowed = "copy";
          }}
        >
          <GripVertical className="h-3.5 w-3.5" />
          <Box className="h-3.5 w-3.5" />
          <span>조건부 영역 추가 (캔버스로 드래그)</span>
        </div>
        <p className="text-[10px] text-muted-foreground">
          기본 레이어에서 Zone을 배치한 후, Zone 내에 레이어를 추가하세요
        </p>
      </div>
    </div>
  );
};
