/**
 * CMS Editor Components
 * Core editing interface components with enhanced functionality
 */

"use client";

import React, { useState, useCallback, useEffect, useMemo } from "react";
import { useEditor } from "./context";
import {
  BaseSection,
  SectionType,
  EditorToolbarProps,
  SectionListProps,
  PreviewPanelProps,
  PropertyPanelProps,
  SectionTemplateProps,
  SectionEditorProps,
} from "./types";
import { EnhancedSectionList } from "./drag-drop";
import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd";
import {
  ChevronDownIcon,
  ChevronUpIcon,
  EyeIcon,
  EyeSlashIcon,
  ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import {
  CogIcon,
  DocumentDuplicateIcon,
  TrashIcon,
  DevicePhoneMobileIcon,
  DeviceTabletIcon,
  ComputerDesktopIcon,
  PlusIcon,
  PaintBrushIcon,
  AdjustmentsHorizontalIcon,
} from "@heroicons/react/24/outline";
import { useCMSEditor, useEditorSelectors } from "./store";
import {
  TextField,
  NumberField,
  SelectField,
  ColorField,
  ToggleField,
  RangeField,
  OptimisticForm,
  ValidationIndicator,
} from "./form-components";
import { heroSectionContentSchema, sectionSchema } from "./validation";

// Icon mapping for consistent UI
const iconMap: Record<string, string> = {
  undo: "↶",
  redo: "↷",
  save: "💾",
  desktop: "🖥️",
  tablet: "📱",
  mobile: "📱",
  preview: "👁️",
  settings: "⚙️",
  add: "➕",
  hero: "🎯",
  features: "⭐",
  cta: "🔔",
  pricing: "💰",
  testimonials: "💬",
  contact: "📞",
  gallery: "🖼️",
  text: "📝",
  custom: "🔧",
};

// Enhanced Editor Toolbar with more controls
export function EditorToolbar({ className = "" }: { className?: string } = {}) {
  const { state, config, updateConfig, undo, redo, canUndo, canRedo } =
    useEditor();

  const handlePreviewModeChange = useCallback(
    (mode: "desktop" | "tablet" | "mobile") => {
      updateConfig({ previewMode: mode });
    },
    [updateConfig]
  );

  const handleSave = useCallback(() => {
    // Implement save functionality
    console.log("Saving sections...", state.sections);
  }, [state.sections]);

  return (
    <div className={`bg-white border-b border-gray-200 px-4 py-3 ${className}`}>
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          {/* History Controls */}
          <div className="flex items-center space-x-1">
            <button
              onClick={undo}
              disabled={!canUndo}
              className={`
                px-3 py-2 text-sm font-medium rounded-md transition-colors
                ${
                  canUndo
                    ? "text-gray-700 hover:bg-gray-100"
                    : "text-gray-400 cursor-not-allowed"
                }
              `}
              title="실행 취소"
            >
              {iconMap.undo}
            </button>
            <button
              onClick={redo}
              disabled={!canRedo}
              className={`
                px-3 py-2 text-sm font-medium rounded-md transition-colors
                ${
                  canRedo
                    ? "text-gray-700 hover:bg-gray-100"
                    : "text-gray-400 cursor-not-allowed"
                }
              `}
              title="다시 실행"
            >
              {iconMap.redo}
            </button>
          </div>

          {/* Save Button */}
          <button
            onClick={handleSave}
            className={`
              px-4 py-2 text-sm font-medium rounded-md transition-colors
              ${
                state.isDirty
                  ? "bg-blue-600 text-white hover:bg-blue-700"
                  : "bg-gray-100 text-gray-400 cursor-not-allowed"
              }
            `}
            disabled={!state.isDirty}
            title="저장"
          >
            {iconMap.save} 저장
          </button>

          {/* Status Indicator */}
          <div className="flex items-center space-x-2 text-sm text-gray-500">
            {state.isLoading && (
              <span className="flex items-center">
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"></div>
                저장 중...
              </span>
            )}
            {state.isDirty && !state.isLoading && (
              <span className="text-orange-600">• 저장되지 않은 변경사항</span>
            )}
            {!state.isDirty && !state.isLoading && (
              <span className="text-green-600">• 모든 변경사항 저장됨</span>
            )}
          </div>
        </div>

        {/* Preview Mode Controls */}
        <div className="flex items-center space-x-2">
          <span className="text-sm text-gray-500 mr-2">미리보기:</span>
          <div className="flex rounded-lg border border-gray-300 overflow-hidden">
            {(["desktop", "tablet", "mobile"] as const).map((mode) => (
              <button
                key={mode}
                onClick={() => handlePreviewModeChange(mode)}
                className={`
                  px-3 py-1 text-sm font-medium transition-colors
                  ${
                    config.previewMode === mode
                      ? "bg-blue-600 text-white"
                      : "bg-white text-gray-700 hover:bg-gray-50"
                  }
                `}
                title={
                  mode === "desktop"
                    ? "데스크톱"
                    : mode === "tablet"
                    ? "태블릿"
                    : "모바일"
                }
              >
                {iconMap[mode]}{" "}
                {mode === "desktop"
                  ? "데스크톱"
                  : mode === "tablet"
                  ? "태블릿"
                  : "모바일"}
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// Updated Section List using Enhanced Drag-and-Drop
export function SectionList({ className = "" }: SectionListProps = {}) {
  return <EnhancedSectionList className={className} />;
}

// Enhanced Preview Panel with responsive preview
export function PreviewPanel({ className = "" }: { className?: string } = {}) {
  const { state, config, selectSection } = useEditor();

  const getPreviewDimensions = useCallback(() => {
    switch (config.previewMode) {
      case "mobile":
        return { width: "375px", height: "667px" };
      case "tablet":
        return { width: "768px", height: "1024px" };
      case "desktop":
      default:
        return { width: "100%", height: "100%" };
    }
  }, [config.previewMode]);

  const dimensions = getPreviewDimensions();

  return (
    <div className={`flex-1 bg-gray-100 overflow-auto ${className}`}>
      <div className="h-full flex items-center justify-center p-8">
        <div
          className="bg-white shadow-lg rounded-lg overflow-hidden"
          style={{
            width: dimensions.width,
            height: dimensions.height,
            maxWidth: "100%",
            maxHeight: "100%",
          }}
        >
          {/* Preview Header */}
          <div className="bg-gray-50 border-b px-4 py-2 flex items-center justify-between">
            <span className="text-sm font-medium text-gray-600">
              미리보기 ({config.previewMode})
            </span>
            <div className="flex items-center space-x-2">
              <span className="text-xs text-gray-500">
                {state.sections.length}개 섹션
              </span>
              <div
                className={`
                w-2 h-2 rounded-full
                ${state.isDirty ? "bg-orange-400" : "bg-green-400"}
              `}
              />
            </div>
          </div>

          {/* Preview Content */}
          <div className="h-full overflow-y-auto">
            {state.sections.length === 0 ? (
              <div className="h-full flex items-center justify-center text-gray-500">
                <div className="text-center">
                  <div className="text-6xl mb-4">📄</div>
                  <p className="text-lg font-medium mb-2">섹션이 없습니다</p>
                  <p className="text-sm">왼쪽에서 섹션을 추가하여 시작하세요</p>
                </div>
              </div>
            ) : (
              <div className="divide-y divide-gray-200">
                {state.sections
                  .sort((a, b) => a.order - b.order)
                  .filter((section) => section.isActive)
                  .map((section) => (
                    <div
                      key={section.id}
                      onClick={() => selectSection(section.id)}
                      className={`
                        p-8 cursor-pointer transition-all duration-200 min-h-32
                        ${
                          state.selectedSection === section.id
                            ? "bg-blue-50 border-2 border-blue-300"
                            : "hover:bg-gray-50"
                        }
                      `}
                      style={{
                        backgroundColor:
                          section.styles.background.color || "#ffffff",
                      }}
                    >
                      <div className="flex items-center justify-between mb-4">
                        <div className="flex items-center space-x-3">
                          <span className="text-3xl">
                            {iconMap[section.type] || iconMap.custom}
                          </span>
                          <div>
                            <h3 className="text-lg font-semibold text-gray-900">
                              {section.name}
                            </h3>
                            <p className="text-sm text-gray-500 capitalize">
                              {section.type} 섹션
                            </p>
                          </div>
                        </div>

                        {state.selectedSection === section.id && (
                          <div className="text-blue-600 text-sm font-medium">
                            선택됨
                          </div>
                        )}
                      </div>

                      {/* Section Content Preview */}
                      <div className="text-gray-600">
                        <pre className="text-sm whitespace-pre-wrap">
                          {JSON.stringify(section.content, null, 2)}
                        </pre>
                      </div>
                    </div>
                  ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// Enhanced Property Panel with better form controls
export function PropertyPanel({ className = "" }: PropertyPanelProps = {}) {
  const { selectedSectionData } = useEditorSelectors();
  const { updateSection } = useCMSEditor();
  const [activeTab, setActiveTab] = useState<"content" | "style" | "settings">(
    "content"
  );

  if (!selectedSectionData) {
    return (
      <div
        className={`bg-white border-l border-gray-200 w-80 p-6 ${className}`}
      >
        <div className="text-center text-gray-500 mt-12">
          <AdjustmentsHorizontalIcon className="w-12 h-12 mx-auto mb-4 text-gray-300" />
          <h3 className="text-lg font-medium mb-2">속성 패널</h3>
          <p className="text-sm">섹션을 선택하여 속성을 편집하세요</p>
        </div>
      </div>
    );
  }

  const handleSectionUpdate = async (data: Partial<BaseSection>) => {
    // This will be handled by the optimistic form
    return Promise.resolve();
  };

  const tabs = [
    { id: "content", label: "콘텐츠", icon: DocumentDuplicateIcon },
    { id: "style", label: "스타일", icon: PaintBrushIcon },
    { id: "settings", label: "설정", icon: CogIcon },
  ] as const;

  return (
    <div
      className={`bg-white border-l border-gray-200 w-80 flex flex-col ${className}`}
    >
      {/* Header */}
      <div className="p-4 border-b border-gray-200">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-lg font-semibold text-gray-900">속성 편집</h2>
          <ValidationIndicator sectionId={selectedSectionData.id} />
        </div>

        <div className="bg-gray-50 rounded-md p-2 mb-3">
          <div className="text-sm font-medium text-gray-700">
            {selectedSectionData.name}
          </div>
          <div className="text-xs text-gray-500 capitalize">
            {selectedSectionData.type} 섹션
          </div>
        </div>

        {/* Tabs */}
        <div className="flex space-x-1 bg-gray-100 rounded-lg p-1">
          {tabs.map((tab) => {
            const Icon = tab.icon;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`
                  flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium rounded-md transition-colors
                  ${
                    activeTab === tab.id
                      ? "bg-white text-blue-600 shadow-sm"
                      : "text-gray-600 hover:text-gray-900"
                  }
                `}
              >
                <Icon className="w-4 h-4 mr-1" />
                {tab.label}
              </button>
            );
          })}
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto">
        {activeTab === "content" && (
          <ContentTab
            section={selectedSectionData}
            onUpdate={handleSectionUpdate}
          />
        )}
        {activeTab === "style" && (
          <StyleTab
            section={selectedSectionData}
            onUpdate={handleSectionUpdate}
          />
        )}
        {activeTab === "settings" && (
          <SettingsTab
            section={selectedSectionData}
            onUpdate={handleSectionUpdate}
          />
        )}
      </div>
    </div>
  );
}

// Content Tab Component
const ContentTab: React.FC<{
  section: BaseSection;
  onUpdate: (data: Partial<BaseSection>) => Promise<void>;
}> = ({ section, onUpdate }) => {
  const contentSchema = useMemo(() => {
    switch (section.type) {
      case "hero":
        return heroSectionContentSchema;
      default:
        return heroSectionContentSchema; // Fallback
    }
  }, [section.type]);

  const defaultValues = useMemo(
    () => ({
      content: section.content,
    }),
    [section.content]
  );

  return (
    <OptimisticForm
      sectionId={section.id}
      schema={contentSchema}
      defaultValues={defaultValues}
      onSubmit={onUpdate}
      className="p-4 space-y-6"
    >
      {({ control }) => (
        <>
          {section.type === "hero" && (
            <div className="space-y-4">
              <TextField
                name="content.title"
                label="제목"
                description="섹션의 메인 제목을 입력하세요"
                required
                control={control}
              />

              <TextField
                name="content.subtitle"
                label="부제목"
                description="선택적 부제목을 입력하세요"
                control={control}
              />

              <TextField
                name="content.description"
                label="설명"
                description="섹션 설명을 입력하세요"
                control={control}
              />

              <TextField
                name="content.image.url"
                label="이미지 URL"
                type="url"
                description="배경 이미지 URL을 입력하세요"
                control={control}
              />

              <TextField
                name="content.image.alt"
                label="이미지 대체 텍스트"
                description="접근성을 위한 이미지 설명"
                control={control}
              />
            </div>
          )}

          {/* Other section types */}
          {section.type !== "hero" && (
            <div className="text-center text-gray-500 py-8">
              <DocumentDuplicateIcon className="w-8 h-8 mx-auto mb-2 text-gray-300" />
              <p className="text-sm">
                {section.type} 섹션의 콘텐츠 편집기가 곧 제공됩니다
              </p>
            </div>
          )}
        </>
      )}
    </OptimisticForm>
  );
};

// Style Tab Component
const StyleTab: React.FC<{
  section: BaseSection;
  onUpdate: (data: Partial<BaseSection>) => Promise<void>;
}> = ({ section, onUpdate }) => {
  const defaultValues = useMemo(
    () => ({
      styles: section.styles,
    }),
    [section.styles]
  );

  return (
    <OptimisticForm
      sectionId={section.id}
      schema={sectionSchema.pick({ styles: true })}
      defaultValues={defaultValues}
      onSubmit={onUpdate}
      className="p-4 space-y-6"
    >
      {({ control }) => (
        <>
          {/* Background */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-gray-900 border-b border-gray-200 pb-2">
              배경
            </h3>

            <ColorField
              name="styles.colors.background"
              label="배경 색상"
              description="섹션의 배경 색상을 선택하세요"
              allowTransparent
              control={control}
            />

            <TextField
              name="styles.background.image.url"
              label="배경 이미지"
              type="url"
              description="배경 이미지 URL을 입력하세요"
              control={control}
            />

            <SelectField
              name="styles.background.image.size"
              label="배경 크기"
              options={[
                { value: "cover", label: "커버" },
                { value: "contain", label: "컨테인" },
                { value: "auto", label: "자동" },
              ]}
              control={control}
            />
          </div>

          {/* Spacing */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-gray-900 border-b border-gray-200 pb-2">
              여백
            </h3>

            <div className="grid grid-cols-2 gap-4">
              <NumberField
                name="styles.spacing.padding.top"
                label="상단 패딩"
                min={0}
                max={200}
                control={control}
              />
              <NumberField
                name="styles.spacing.padding.bottom"
                label="하단 패딩"
                min={0}
                max={200}
                control={control}
              />
              <NumberField
                name="styles.spacing.padding.left"
                label="좌측 패딩"
                min={0}
                max={200}
                control={control}
              />
              <NumberField
                name="styles.spacing.padding.right"
                label="우측 패딩"
                min={0}
                max={200}
                control={control}
              />
            </div>
          </div>

          {/* Typography */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-gray-900 border-b border-gray-200 pb-2">
              타이포그래피
            </h3>

            <SelectField
              name="styles.typography.fontFamily"
              label="폰트 패밀리"
              options={[
                { value: "Inter", label: "Inter" },
                { value: "Roboto", label: "Roboto" },
                { value: "Noto Sans KR", label: "Noto Sans Korean" },
                { value: "system-ui", label: "시스템 기본" },
              ]}
              control={control}
            />

            <RangeField
              name="styles.typography.fontSize"
              label="폰트 크기"
              min={8}
              max={128}
              formatValue={(value) => `${value}px`}
              control={control}
            />

            <SelectField
              name="styles.typography.fontWeight"
              label="폰트 굵기"
              options={[
                { value: "100", label: "100 (Thin)" },
                { value: "300", label: "300 (Light)" },
                { value: "400", label: "400 (Regular)" },
                { value: "600", label: "600 (SemiBold)" },
                { value: "700", label: "700 (Bold)" },
                { value: "900", label: "900 (Black)" },
              ]}
              control={control}
            />

            <ColorField
              name="styles.colors.text"
              label="텍스트 색상"
              control={control}
            />
          </div>

          {/* Borders */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-gray-900 border-b border-gray-200 pb-2">
              테두리
            </h3>

            <RangeField
              name="styles.borders.width"
              label="테두리 두께"
              min={0}
              max={20}
              formatValue={(value) => `${value}px`}
              control={control}
            />

            <SelectField
              name="styles.borders.style"
              label="테두리 스타일"
              options={[
                { value: "none", label: "없음" },
                { value: "solid", label: "실선" },
                { value: "dashed", label: "점선" },
                { value: "dotted", label: "점선 (작은)" },
              ]}
              control={control}
            />

            <ColorField
              name="styles.borders.color"
              label="테두리 색상"
              control={control}
            />

            <RangeField
              name="styles.borders.radius"
              label="테두리 둥글기"
              min={0}
              max={50}
              formatValue={(value) => `${value}px`}
              control={control}
            />
          </div>
        </>
      )}
    </OptimisticForm>
  );
};

// Settings Tab Component
const SettingsTab: React.FC<{
  section: BaseSection;
  onUpdate: (data: Partial<BaseSection>) => Promise<void>;
}> = ({ section, onUpdate }) => {
  const defaultValues = useMemo(
    () => ({
      settings: section.settings,
      metadata: section.metadata,
    }),
    [section.settings, section.metadata]
  );

  return (
    <OptimisticForm
      sectionId={section.id}
      schema={sectionSchema.pick({ settings: true, metadata: true })}
      defaultValues={defaultValues}
      onSubmit={onUpdate}
      className="p-4 space-y-6"
    >
      {({ control }) => (
        <>
          {/* Visibility Settings */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-gray-900 border-b border-gray-200 pb-2">
              표시 설정
            </h3>

            <ToggleField
              name="settings.isVisible"
              label="섹션 표시"
              description="웹사이트에서 이 섹션을 표시할지 설정합니다"
              control={control}
            />

            <ToggleField
              name="settings.isLocked"
              label="편집 잠금"
              description="실수로 편집되지 않도록 잠금 설정합니다"
              control={control}
            />
          </div>

          {/* Animation Settings */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-gray-900 border-b border-gray-200 pb-2">
              애니메이션
            </h3>

            <ToggleField
              name="settings.animation.enabled"
              label="애니메이션 활성화"
              description="섹션 로드시 애니메이션을 적용합니다"
              control={control}
            />

            <SelectField
              name="settings.animation.type"
              label="애니메이션 유형"
              options={[
                { value: "fade", label: "페이드" },
                { value: "slide", label: "슬라이드" },
                { value: "scale", label: "확대/축소" },
                { value: "rotate", label: "회전" },
                { value: "bounce", label: "바운스" },
              ]}
              control={control}
            />

            <RangeField
              name="settings.animation.duration"
              label="애니메이션 지속시간"
              min={100}
              max={3000}
              step={100}
              formatValue={(value) => `${value}ms`}
              control={control}
            />

            <RangeField
              name="settings.animation.delay"
              label="애니메이션 지연시간"
              min={0}
              max={2000}
              step={100}
              formatValue={(value) => `${value}ms`}
              control={control}
            />
          </div>

          {/* SEO Settings */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-gray-900 border-b border-gray-200 pb-2">
              SEO 설정
            </h3>

            <TextField
              name="settings.seo.title"
              label="SEO 제목"
              description="검색 엔진 결과에 표시될 제목"
              maxLength={60}
              control={control}
            />

            <TextField
              name="settings.seo.description"
              label="SEO 설명"
              description="검색 엔진 결과에 표시될 설명"
              maxLength={160}
              control={control}
            />
          </div>

          {/* Accessibility */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-gray-900 border-b border-gray-200 pb-2">
              접근성
            </h3>

            <TextField
              name="settings.accessibility.ariaLabel"
              label="ARIA 라벨"
              description="스크린 리더를 위한 섹션 설명"
              control={control}
            />

            <ToggleField
              name="settings.accessibility.focusable"
              label="포커스 가능"
              description="키보드로 이 섹션에 포커스할 수 있도록 설정"
              control={control}
            />
          </div>

          {/* Metadata */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold text-gray-900 border-b border-gray-200 pb-2">
              메타데이터
            </h3>

            <div className="bg-gray-50 rounded-lg p-3 text-sm space-y-2">
              <div className="flex justify-between">
                <span className="text-gray-600">생성일:</span>
                <span className="font-mono">
                  {new Date(section.metadata.createdAt).toLocaleDateString()}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600">수정일:</span>
                <span className="font-mono">
                  {new Date(section.metadata.updatedAt).toLocaleDateString()}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600">버전:</span>
                <span className="font-mono">v{section.metadata.version}</span>
              </div>
            </div>
          </div>
        </>
      )}
    </OptimisticForm>
  );
};

// Section Template Selector Component
export function SectionTemplateSelector({
  className = "",
  onSelectTemplate,
}: SectionTemplateProps) {
  const { addSection } = useEditor();

  const sectionTemplates = [
    {
      type: "hero" as SectionType,
      name: "히어로 섹션",
      description: "메인 배너 영역",
      icon: iconMap.hero,
    },
    {
      type: "features" as SectionType,
      name: "기능 섹션",
      description: "주요 기능 소개",
      icon: iconMap.features,
    },
    {
      type: "cta" as SectionType,
      name: "CTA 섹션",
      description: "행동 유도 버튼",
      icon: iconMap.cta,
    },
    {
      type: "pricing" as SectionType,
      name: "가격 섹션",
      description: "요금제 표시",
      icon: iconMap.pricing,
    },
    {
      type: "testimonials" as SectionType,
      name: "후기 섹션",
      description: "고객 리뷰",
      icon: iconMap.testimonials,
    },
    {
      type: "contact" as SectionType,
      name: "연락처 섹션",
      description: "문의 정보",
      icon: iconMap.contact,
    },
    {
      type: "gallery" as SectionType,
      name: "갤러리 섹션",
      description: "이미지 갤러리",
      icon: iconMap.gallery,
    },
    {
      type: "text" as SectionType,
      name: "텍스트 섹션",
      description: "일반 텍스트",
      icon: iconMap.text,
    },
    {
      type: "custom" as SectionType,
      name: "커스텀 섹션",
      description: "사용자 정의",
      icon: iconMap.custom,
    },
  ];

  const handleTemplateSelect = useCallback(
    (sectionType: SectionType) => {
      const template = sectionTemplates.find((t) => t.type === sectionType);
      if (template) {
        const newSection = {
          id: `section-${Date.now()}`,
          type: sectionType,
          name: template.name,
          order: 0,
          isActive: true,
          content: {},
          styles: {
            background: { type: "color" as const, color: "#ffffff" },
            spacing: {
              padding: { top: 32, right: 16, bottom: 32, left: 16 },
              margin: { top: 0, right: 0, bottom: 0, left: 0 },
            },
            typography: {
              fontFamily: "Inter",
              fontSize: 16,
              fontWeight: 400,
              lineHeight: 1.5,
              letterSpacing: 0,
              textAlign: "left" as const,
              textDecoration: "none" as const,
              textTransform: "none" as const,
            },
            colors: {
              primary: "#3b82f6",
              secondary: "#64748b",
              accent: "#f59e0b",
              text: "#1f2937",
              textSecondary: "#6b7280",
              background: "#ffffff",
              border: "#e5e7eb",
            },
            borders: {
              width: 0,
              style: "none" as const,
              color: "#e5e7eb",
              radius: 0,
            },
            effects: {
              shadow: "none",
              blur: 0,
              opacity: 1,
              transform: "none",
              transition: "all 0.2s ease",
              animation: "none",
            },
            responsive: {
              mobile: {},
              tablet: {},
              desktop: {},
            },
          },
          settings: {
            isVisible: true,
            isLocked: false,
            animation: {
              enabled: false,
              type: "fade" as const,
              duration: 300,
              delay: 0,
              easing: "ease-in-out",
              trigger: "scroll" as const,
            },
            seo: {},
            accessibility: {
              focusable: true,
            },
          },
          metadata: {
            createdAt: new Date(),
            updatedAt: new Date(),
            createdBy: "user",
            updatedBy: "user",
            version: 1,
          },
        };

        addSection(newSection);
        onSelectTemplate?.(newSection);
      }
    },
    [addSection, onSelectTemplate]
  );

  return (
    <div className={`w-80 bg-white border-l overflow-y-auto ${className}`}>
      <div className="p-4">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">
          섹션 템플릿
        </h3>

        <div className="space-y-2">
          {sectionTemplates.map((template) => (
            <button
              key={template.type}
              onClick={() => handleTemplateSelect(template.type)}
              className="w-full text-left p-3 rounded-lg border border-gray-200 hover:border-blue-300 hover:bg-blue-50 transition-colors"
            >
              <div className="flex items-center space-x-3">
                <span className="text-2xl">{template.icon}</span>
                <div className="flex-1 min-w-0">
                  <h4 className="text-sm font-medium text-gray-900">
                    {template.name}
                  </h4>
                  <p className="text-xs text-gray-500">
                    {template.description}
                  </p>
                </div>
                <span className="text-blue-600 text-xl">+</span>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// Main Section Editor Component
export function SectionEditor({
  className = "",
  showTemplateSelector = true,
}: SectionEditorProps = {}) {
  const { state } = useEditor();

  return (
    <div className={`h-screen flex flex-col bg-gray-100 ${className}`}>
      <EditorToolbar />

      <div className="flex-1 flex overflow-hidden">
        <SectionList />
        <PreviewPanel />
        {state.selectedSection ? (
          <PropertyPanel />
        ) : (
          showTemplateSelector && <SectionTemplateSelector />
        )}
      </div>
    </div>
  );
}

// Publishing Status Bar Component
export function PublishingStatusBar() {
  const {
    isSaving,
    isPublishing,
    isPublished,
    lastSaved,
    publishedAt,
    saveError,
    publishError,
    isDirty,
    draftState,
    saveDraft,
    publishSections,
    unpublishSections,
    getPreviewUrl,
  } = useCMSEditor();

  const handleSaveDraft = async () => {
    try {
      await saveDraft();
    } catch (error) {
      console.error("Draft save failed:", error);
    }
  };

  const handlePublish = async () => {
    try {
      await publishSections();
    } catch (error) {
      console.error("Publish failed:", error);
    }
  };

  const handleUnpublish = async () => {
    try {
      await unpublishSections();
    } catch (error) {
      console.error("Unpublish failed:", error);
    }
  };

  const handlePreview = async () => {
    try {
      const url = await getPreviewUrl();
      window.open(url, "_blank");
    } catch (error) {
      console.error("Preview failed:", error);
    }
  };

  return (
    <div className="flex items-center justify-between p-4 bg-gray-50 border-b border-gray-200">
      {/* Left: Status Info */}
      <div className="flex items-center space-x-4">
        {/* Save Status */}
        <div className="flex items-center space-x-2">
          {isSaving ? (
            <>
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-500"></div>
              <span className="text-sm text-blue-600">저장 중...</span>
            </>
          ) : isDirty ? (
            <>
              <div className="h-2 w-2 rounded-full bg-orange-500"></div>
              <span className="text-sm text-gray-600">변경사항 있음</span>
            </>
          ) : (
            <>
              <div className="h-2 w-2 rounded-full bg-green-500"></div>
              <span className="text-sm text-gray-600">
                {lastSaved
                  ? `저장됨 (${formatRelativeTime(lastSaved)})`
                  : "저장됨"}
              </span>
            </>
          )}
        </div>

        {/* Publish Status */}
        <div className="flex items-center space-x-2">
          {isPublishing ? (
            <>
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-green-500"></div>
              <span className="text-sm text-green-600">발행 중...</span>
            </>
          ) : isPublished ? (
            <>
              <div className="h-2 w-2 rounded-full bg-green-500"></div>
              <span className="text-sm text-gray-600">
                {publishedAt
                  ? `발행됨 (${formatRelativeTime(publishedAt)})`
                  : "발행됨"}
              </span>
            </>
          ) : (
            <>
              <div className="h-2 w-2 rounded-full bg-gray-400"></div>
              <span className="text-sm text-gray-600">미발행</span>
            </>
          )}
        </div>

        {/* Draft Info */}
        {draftState && (
          <div className="flex items-center space-x-2">
            <span className="text-xs px-2 py-1 bg-yellow-100 text-yellow-800 rounded">
              초안 v{draftState.version}
            </span>
          </div>
        )}

        {/* Error Messages */}
        {saveError && (
          <div className="flex items-center space-x-1 text-red-600">
            <ExclamationTriangleIcon className="h-4 w-4" />
            <span className="text-sm">저장 오류: {saveError}</span>
          </div>
        )}

        {publishError && (
          <div className="flex items-center space-x-1 text-red-600">
            <ExclamationTriangleIcon className="h-4 w-4" />
            <span className="text-sm">발행 오류: {publishError}</span>
          </div>
        )}
      </div>

      {/* Right: Action Buttons */}
      <div className="flex items-center space-x-2">
        <button
          onClick={handleSaveDraft}
          disabled={isSaving || !isDirty}
          className="px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isSaving ? "저장 중..." : "초안 저장"}
        </button>

        <button
          onClick={handlePreview}
          className="px-3 py-1.5 text-sm font-medium text-blue-700 bg-blue-50 border border-blue-300 rounded-md hover:bg-blue-100"
        >
          미리보기
        </button>

        {isPublished ? (
          <button
            onClick={handleUnpublish}
            disabled={isPublishing}
            className="px-3 py-1.5 text-sm font-medium text-white bg-red-600 border border-transparent rounded-md hover:bg-red-700 disabled:opacity-50"
          >
            {isPublishing ? "처리 중..." : "발행 취소"}
          </button>
        ) : (
          <button
            onClick={handlePublish}
            disabled={isPublishing || isSaving}
            className="px-3 py-1.5 text-sm font-medium text-white bg-green-600 border border-transparent rounded-md hover:bg-green-700 disabled:opacity-50"
          >
            {isPublishing ? "발행 중..." : "발행"}
          </button>
        )}
      </div>
    </div>
  );
}

// Network Status Indicator
export function NetworkStatusIndicator() {
  const { isOnline, lastSync, syncError } = useCMSEditor();

  return (
    <div className="flex items-center space-x-2">
      <div
        className={`h-2 w-2 rounded-full ${
          isOnline ? "bg-green-500" : "bg-red-500"
        }`}
      />
      <span className="text-xs text-gray-500">
        {isOnline
          ? lastSync
            ? `동기화됨 ${formatRelativeTime(lastSync)}`
            : "온라인"
          : "오프라인"}
      </span>
      {syncError && (
        <ExclamationTriangleIcon
          className="h-3 w-3 text-red-500"
          title={syncError}
        />
      )}
    </div>
  );
}

// Auto-save Status Indicator
export function AutoSaveIndicator() {
  const { isSaving, isDirty, lastSaved } = useCMSEditor();

  if (isSaving) {
    return (
      <div className="flex items-center space-x-2 text-blue-600">
        <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-blue-500"></div>
        <span className="text-xs">자동 저장 중...</span>
      </div>
    );
  }

  if (isDirty) {
    return (
      <div className="flex items-center space-x-2 text-orange-600">
        <div className="h-2 w-2 rounded-full bg-orange-500"></div>
        <span className="text-xs">저장 필요</span>
      </div>
    );
  }

  return (
    <div className="flex items-center space-x-2 text-green-600">
      <div className="h-2 w-2 rounded-full bg-green-500"></div>
      <span className="text-xs">
        {lastSaved ? `저장됨 ${formatRelativeTime(lastSaved)}` : "저장됨"}
      </span>
    </div>
  );
}

// Publishing Actions Menu
export function PublishingActionsMenu() {
  const {
    isPublished,
    isPublishing,
    isDirty,
    publishSections,
    unpublishSections,
    saveDraft,
    getPreviewUrl,
  } = useCMSEditor();

  const [isOpen, setIsOpen] = React.useState(false);
  const menuRef = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const handleAction = async (action: string) => {
    setIsOpen(false);

    try {
      switch (action) {
        case "save-draft":
          await saveDraft();
          break;
        case "publish":
          await publishSections();
          break;
        case "unpublish":
          await unpublishSections();
          break;
        case "preview":
          const url = await getPreviewUrl();
          window.open(url, "_blank");
          break;
      }
    } catch (error) {
      console.error(`Action ${action} failed:`, error);
    }
  };

  return (
    <div className="relative" ref={menuRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center space-x-1 px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
      >
        <span>발행</span>
        <ChevronDownIcon className="h-4 w-4" />
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg border border-gray-200 z-50">
          <div className="py-1">
            <button
              onClick={() => handleAction("save-draft")}
              disabled={!isDirty}
              className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              초안으로 저장
            </button>

            <button
              onClick={() => handleAction("preview")}
              className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              미리보기
            </button>

            <div className="border-t border-gray-100 my-1"></div>

            {isPublished ? (
              <button
                onClick={() => handleAction("unpublish")}
                disabled={isPublishing}
                className="w-full text-left px-4 py-2 text-sm text-red-700 hover:bg-red-50 disabled:opacity-50"
              >
                {isPublishing ? "처리 중..." : "발행 취소"}
              </button>
            ) : (
              <button
                onClick={() => handleAction("publish")}
                disabled={isPublishing}
                className="w-full text-left px-4 py-2 text-sm text-green-700 hover:bg-green-50 disabled:opacity-50"
              >
                {isPublishing ? "발행 중..." : "웹사이트 발행"}
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

// Utility function for relative time formatting
function formatRelativeTime(date: Date): string {
  const now = new Date();
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);

  if (diffInSeconds < 60) {
    return "방금 전";
  } else if (diffInSeconds < 3600) {
    const minutes = Math.floor(diffInSeconds / 60);
    return `${minutes}분 전`;
  } else if (diffInSeconds < 86400) {
    const hours = Math.floor(diffInSeconds / 3600);
    return `${hours}시간 전`;
  } else {
    const days = Math.floor(diffInSeconds / 86400);
    return `${days}일 전`;
  }
}
