/**
 * 품목기준관리 Zustand Store
 *
 * 핵심 원칙:
 * 1. 정규화된 상태 구조 → 1곳 수정으로 모든 뷰 업데이트
 * 2. Immer로 불변성 관리
 * 3. 기존 API와 100% 호환
 */

import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { devtools } from 'zustand/middleware';
import type {
  ItemMasterStore,
  ItemMasterState,
  PageEntity,
  SectionEntity,
  FieldEntity,
  BOMItemEntity,
} from './types';
import { itemMasterApi } from '@/lib/api/item-master';
import {
  normalizeInitResponse,
  normalizeSectionResponse,
  denormalizePageForRequest,
  denormalizeSectionForRequest,
  denormalizeFieldForRequest,
} from './normalizers';

// ===== 초기 상태 =====

const initialState: ItemMasterState = {
  entities: {
    pages: {},
    sections: {},
    fields: {},
    bomItems: {},
  },
  ids: {
    pages: [],
    independentSections: [],
    independentFields: [],
    independentBomItems: [],
  },
  references: {
    itemMasters: [],
    specificationMasters: [],
    materialItemNames: [],
    itemCategories: [],
    itemUnits: [],
    itemMaterials: [],
    surfaceTreatments: [],
    partTypeOptions: [],
    partUsageOptions: [],
    guideRailOptions: [],
    masterFields: [],
  },
  ui: {
    isLoading: false,
    error: null,
    selectedPageId: null,
    selectedSectionId: null,
    selectedFieldId: null,
  },
};

// ===== 스토어 생성 =====

export const useItemMasterStore = create<ItemMasterStore>()(
  devtools(
    immer((set, get) => ({
      ...initialState,

      // ===== 페이지 액션 =====

      loadPages: (pages) => {
        set((state) => {
          // 기존 데이터 초기화
          state.entities.pages = {};
          state.ids.pages = [];

          pages.forEach((page) => {
            state.entities.pages[page.id] = page;
            state.ids.pages.push(page.id);
          });
        });
      },

      createPage: async (pageData) => {
        const state = get();
        state.ui.isLoading = true;

        try {
          // TODO: API 호출
          // const response = await itemMasterApi.createPage(pageData);

          // 임시: 로컬에서 ID 생성 (실제로는 API 응답 사용)
          const newPage: PageEntity = {
            ...pageData,
            id: Date.now(),
            sectionIds: [],
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
          };

          set((state) => {
            state.entities.pages[newPage.id] = newPage;
            state.ids.pages.push(newPage.id);
            state.ui.isLoading = false;
          });

          return newPage;
        } catch (error) {
          set((state) => {
            state.ui.isLoading = false;
            state.ui.error = error instanceof Error ? error.message : '페이지 생성 실패';
          });
          throw error;
        }
      },

      updatePage: async (id, updates) => {
        try {

          // ✅ Phase 3: API 연동
          const apiData = denormalizePageForRequest(updates);
          await itemMasterApi.pages.update(id, apiData);

          // ✅ 변경된 필드만 로컬 상태 업데이트 (sectionIds는 건드리지 않음!)
          // API 응답에 sections가 빈 배열로 오기 때문에 initFromApi() 사용 안 함
          set((state) => {
            const page = state.entities.pages[id];
            if (page) {
              // 변경 요청된 필드들만 업데이트
              if (updates.page_name !== undefined) page.page_name = updates.page_name;
              if (updates.description !== undefined) page.description = updates.description;
              if (updates.item_type !== undefined) page.item_type = updates.item_type;
              if (updates.absolute_path !== undefined) page.absolute_path = updates.absolute_path;
              if (updates.is_active !== undefined) page.is_active = updates.is_active;
              if (updates.order_no !== undefined) page.order_no = updates.order_no;
              // sectionIds는 건드리지 않음 - 페이지 정보만 수정한 거니까!
              page.updated_at = new Date().toISOString();
            }
          });

        } catch (error) {
          console.error('[ItemMasterStore] updatePage 실패:', error);
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '페이지 수정 실패';
          });
          throw error;
        }
      },

      deletePage: async (id) => {
        try {
          // TODO: API 호출
          // await itemMasterApi.deletePage(id);

          set((state) => {
            // 페이지에 연결된 섹션들을 독립 섹션으로 변경
            const page = state.entities.pages[id];
            if (page) {
              page.sectionIds.forEach((sectionId) => {
                if (state.entities.sections[sectionId]) {
                  state.entities.sections[sectionId].page_id = null;
                  state.ids.independentSections.push(sectionId);
                }
              });
            }

            // 페이지 삭제
            delete state.entities.pages[id];
            state.ids.pages = state.ids.pages.filter((pageId) => pageId !== id);
          });
        } catch (error) {
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '페이지 삭제 실패';
          });
          throw error;
        }
      },

      // ===== 섹션 액션 =====

      loadSections: (sections) => {
        set((state) => {
          sections.forEach((section) => {
            state.entities.sections[section.id] = section;

            // 독립 섹션 목록 관리
            if (section.page_id === null) {
              if (!state.ids.independentSections.includes(section.id)) {
                state.ids.independentSections.push(section.id);
              }
            }

            // 페이지에 섹션 ID 추가
            if (section.page_id !== null && state.entities.pages[section.page_id]) {
              const page = state.entities.pages[section.page_id];
              if (!page.sectionIds.includes(section.id)) {
                page.sectionIds.push(section.id);
              }
            }
          });
        });
      },

      createSection: async (sectionData) => {
        try {
          // TODO: API 호출

          const newSection: SectionEntity = {
            ...sectionData,
            id: Date.now(),
            fieldIds: [],
            bomItemIds: [],
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
          };

          set((state) => {
            state.entities.sections[newSection.id] = newSection;

            if (newSection.page_id === null) {
              state.ids.independentSections.push(newSection.id);
            } else if (state.entities.pages[newSection.page_id]) {
              state.entities.pages[newSection.page_id].sectionIds.push(newSection.id);
            }
          });

          return newSection;
        } catch (error) {
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '섹션 생성 실패';
          });
          throw error;
        }
      },

      createSectionInPage: async (pageId, sectionData) => {
        const { createSection } = get();
        return createSection({
          ...sectionData,
          page_id: pageId,
        });
      },

      updateSection: async (id, updates) => {
        try {

          // ✅ Phase 3: API 연동
          const apiData = denormalizeSectionForRequest(updates);
          await itemMasterApi.sections.update(id, apiData);

          // ✅ 변경된 필드만 로컬 상태 업데이트 (fieldIds, bomItemIds는 건드리지 않음!)
          // API 응답에 fields가 빈 배열로 오기 때문에 initFromApi() 사용 안 함
          set((state) => {
            const section = state.entities.sections[id];
            if (section) {
              // 변경 요청된 필드들만 업데이트
              if (updates.title !== undefined) section.title = updates.title;
              if (updates.description !== undefined) section.description = updates.description;
              if (updates.section_type !== undefined) section.section_type = updates.section_type;
              if (updates.order_no !== undefined) section.order_no = updates.order_no;
              if (updates.is_template !== undefined) section.is_template = updates.is_template;
              if (updates.is_default !== undefined) section.is_default = updates.is_default;
              if (updates.is_collapsible !== undefined) section.is_collapsible = updates.is_collapsible;
              if (updates.is_default_open !== undefined) section.is_default_open = updates.is_default_open;
              // fieldIds, bomItemIds는 건드리지 않음 - 섹션 정보만 수정한 거니까!
              section.updated_at = new Date().toISOString();
            }
          });

        } catch (error) {
          console.error('[ItemMasterStore] updateSection 실패:', error);
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '섹션 수정 실패';
          });
          throw error;
        }
      },

      deleteSection: async (id) => {
        try {
          // TODO: API 호출

          set((state) => {
            const section = state.entities.sections[id];
            if (!section) return;

            // 섹션에 연결된 필드들을 독립 필드로 변경
            section.fieldIds.forEach((fieldId) => {
              if (state.entities.fields[fieldId]) {
                state.entities.fields[fieldId].section_id = null;
                state.ids.independentFields.push(fieldId);
              }
            });

            // 섹션에 연결된 BOM들을 독립 BOM으로 변경
            section.bomItemIds.forEach((bomId) => {
              if (state.entities.bomItems[bomId]) {
                state.entities.bomItems[bomId].section_id = null;
                state.ids.independentBomItems.push(bomId);
              }
            });

            // 페이지에서 섹션 ID 제거
            if (section.page_id !== null && state.entities.pages[section.page_id]) {
              const page = state.entities.pages[section.page_id];
              page.sectionIds = page.sectionIds.filter((sId) => sId !== id);
            }

            // 독립 섹션 목록에서 제거
            state.ids.independentSections = state.ids.independentSections.filter(
              (sId) => sId !== id
            );

            // 섹션 삭제
            delete state.entities.sections[id];
          });
        } catch (error) {
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '섹션 삭제 실패';
          });
          throw error;
        }
      },

      linkSectionToPage: async (sectionId, pageId) => {
        try {
          // TODO: API 호출

          set((state) => {
            const section = state.entities.sections[sectionId];
            const page = state.entities.pages[pageId];

            if (!section || !page) return;

            // 기존 페이지에서 제거
            if (section.page_id !== null && state.entities.pages[section.page_id]) {
              const oldPage = state.entities.pages[section.page_id];
              oldPage.sectionIds = oldPage.sectionIds.filter((id) => id !== sectionId);
            }

            // 독립 섹션 목록에서 제거
            state.ids.independentSections = state.ids.independentSections.filter(
              (id) => id !== sectionId
            );

            // 새 페이지에 연결
            section.page_id = pageId;
            if (!page.sectionIds.includes(sectionId)) {
              page.sectionIds.push(sectionId);
            }
          });
        } catch (error) {
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '섹션 연결 실패';
          });
          throw error;
        }
      },

      unlinkSectionFromPage: async (sectionId) => {
        try {
          // TODO: API 호출

          set((state) => {
            const section = state.entities.sections[sectionId];
            if (!section || section.page_id === null) return;

            // 페이지에서 섹션 ID 제거
            const page = state.entities.pages[section.page_id];
            if (page) {
              page.sectionIds = page.sectionIds.filter((id) => id !== sectionId);
            }

            // 독립 섹션으로 변경
            section.page_id = null;
            if (!state.ids.independentSections.includes(sectionId)) {
              state.ids.independentSections.push(sectionId);
            }
          });
        } catch (error) {
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '섹션 연결 해제 실패';
          });
          throw error;
        }
      },

      reorderSections: async (pageId, dragSectionId, hoverSectionId) => {
        try {
          set((state) => {
            const page = state.entities.pages[pageId];
            if (!page) return;

            const sectionIds = [...page.sectionIds];
            const dragIndex = sectionIds.indexOf(dragSectionId);
            const hoverIndex = sectionIds.indexOf(hoverSectionId);

            if (dragIndex === -1 || hoverIndex === -1) return;

            // 배열에서 드래그된 항목 제거 후 새 위치에 삽입
            sectionIds.splice(dragIndex, 1);
            sectionIds.splice(hoverIndex, 0, dragSectionId);

            // 페이지의 sectionIds 업데이트
            page.sectionIds = sectionIds;

            // 각 섹션의 order_no 업데이트
            sectionIds.forEach((id, index) => {
              if (state.entities.sections[id]) {
                state.entities.sections[id].order_no = index;
              }
            });
          });

          // TODO: API 호출하여 서버에도 순서 저장
        } catch (error) {
          console.error('[ItemMasterStore] reorderSections 실패:', error);
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '섹션 순서 변경 실패';
          });
          throw error;
        }
      },

      // ===== 필드 액션 =====

      loadFields: (fields) => {
        set((state) => {
          fields.forEach((field) => {
            state.entities.fields[field.id] = field;

            // 독립 필드 목록 관리
            if (field.section_id === null) {
              if (!state.ids.independentFields.includes(field.id)) {
                state.ids.independentFields.push(field.id);
              }
            }

            // 섹션에 필드 ID 추가
            if (field.section_id !== null && state.entities.sections[field.section_id]) {
              const section = state.entities.sections[field.section_id];
              if (!section.fieldIds.includes(field.id)) {
                section.fieldIds.push(field.id);
              }
            }
          });
        });
      },

      createField: async (fieldData) => {
        try {
          // TODO: API 호출

          const newField: FieldEntity = {
            ...fieldData,
            id: Date.now(),
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
          };

          set((state) => {
            state.entities.fields[newField.id] = newField;

            if (newField.section_id === null) {
              state.ids.independentFields.push(newField.id);
            } else if (state.entities.sections[newField.section_id]) {
              state.entities.sections[newField.section_id].fieldIds.push(newField.id);
            }
          });

          return newField;
        } catch (error) {
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '필드 생성 실패';
          });
          throw error;
        }
      },

      createFieldInSection: async (sectionId, fieldData) => {
        const { createField } = get();
        return createField({
          ...fieldData,
          section_id: sectionId,
        });
      },

      updateField: async (id, updates) => {
        try {
          // ✅ Phase 3: API 연동
          const apiData = denormalizeFieldForRequest(updates);
          const response = await itemMasterApi.fields.update(id, apiData);

          // ⭐ 핵심: 1곳만 수정하면 끝!
          set((state) => {
            if (state.entities.fields[id]) {
              Object.assign(state.entities.fields[id], updates, {
                updated_at: response.data?.updated_at || new Date().toISOString(),
              });
            }
          });

        } catch (error) {
          console.error('[ItemMasterStore] updateField 실패:', error);
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '필드 수정 실패';
          });
          throw error;
        }
      },

      deleteField: async (id) => {
        try {
          // TODO: API 호출

          set((state) => {
            const field = state.entities.fields[id];
            if (!field) return;

            // 섹션에서 필드 ID 제거
            if (field.section_id !== null && state.entities.sections[field.section_id]) {
              const section = state.entities.sections[field.section_id];
              section.fieldIds = section.fieldIds.filter((fId) => fId !== id);
            }

            // 독립 필드 목록에서 제거
            state.ids.independentFields = state.ids.independentFields.filter(
              (fId) => fId !== id
            );

            // 필드 삭제
            delete state.entities.fields[id];
          });
        } catch (error) {
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '필드 삭제 실패';
          });
          throw error;
        }
      },

      linkFieldToSection: async (fieldId, sectionId) => {
        try {
          // TODO: API 호출

          set((state) => {
            const field = state.entities.fields[fieldId];
            const section = state.entities.sections[sectionId];

            if (!field || !section) return;

            // 기존 섹션에서 제거
            if (field.section_id !== null && state.entities.sections[field.section_id]) {
              const oldSection = state.entities.sections[field.section_id];
              oldSection.fieldIds = oldSection.fieldIds.filter((id) => id !== fieldId);
            }

            // 독립 필드 목록에서 제거
            state.ids.independentFields = state.ids.independentFields.filter(
              (id) => id !== fieldId
            );

            // 새 섹션에 연결
            field.section_id = sectionId;
            if (!section.fieldIds.includes(fieldId)) {
              section.fieldIds.push(fieldId);
            }
          });
        } catch (error) {
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '필드 연결 실패';
          });
          throw error;
        }
      },

      unlinkFieldFromSection: async (fieldId) => {
        try {
          // TODO: API 호출

          set((state) => {
            const field = state.entities.fields[fieldId];
            if (!field || field.section_id === null) return;

            // 섹션에서 필드 ID 제거
            const section = state.entities.sections[field.section_id];
            if (section) {
              section.fieldIds = section.fieldIds.filter((id) => id !== fieldId);
            }

            // 독립 필드로 변경
            field.section_id = null;
            if (!state.ids.independentFields.includes(fieldId)) {
              state.ids.independentFields.push(fieldId);
            }
          });
        } catch (error) {
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '필드 연결 해제 실패';
          });
          throw error;
        }
      },

      reorderFields: async (sectionId, dragFieldId, hoverFieldId) => {
        try {
          set((state) => {
            const section = state.entities.sections[sectionId];
            if (!section) return;

            const fieldIds = [...section.fieldIds];
            const dragIndex = fieldIds.indexOf(dragFieldId);
            const hoverIndex = fieldIds.indexOf(hoverFieldId);

            if (dragIndex === -1 || hoverIndex === -1) return;

            // 배열에서 드래그된 항목 제거 후 새 위치에 삽입
            fieldIds.splice(dragIndex, 1);
            fieldIds.splice(hoverIndex, 0, dragFieldId);

            // 섹션의 fieldIds 업데이트
            section.fieldIds = fieldIds;

            // 각 필드의 order_no 업데이트
            fieldIds.forEach((id, index) => {
              if (state.entities.fields[id]) {
                state.entities.fields[id].order_no = index;
              }
            });
          });

          // TODO: API 호출하여 서버에도 순서 저장
        } catch (error) {
          console.error('[ItemMasterStore] reorderFields 실패:', error);
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : '필드 순서 변경 실패';
          });
          throw error;
        }
      },

      // ===== BOM 액션 =====

      loadBomItems: (items) => {
        set((state) => {
          items.forEach((item) => {
            state.entities.bomItems[item.id] = item;

            // 독립 BOM 목록 관리
            if (item.section_id === null) {
              if (!state.ids.independentBomItems.includes(item.id)) {
                state.ids.independentBomItems.push(item.id);
              }
            }

            // 섹션에 BOM ID 추가
            if (item.section_id !== null && state.entities.sections[item.section_id]) {
              const section = state.entities.sections[item.section_id];
              if (!section.bomItemIds.includes(item.id)) {
                section.bomItemIds.push(item.id);
              }
            }
          });
        });
      },

      createBomItem: async (itemData) => {
        try {
          // TODO: API 호출

          const newItem: BOMItemEntity = {
            ...itemData,
            id: Date.now(),
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
          };

          set((state) => {
            state.entities.bomItems[newItem.id] = newItem;

            if (newItem.section_id === null) {
              state.ids.independentBomItems.push(newItem.id);
            } else if (state.entities.sections[newItem.section_id]) {
              state.entities.sections[newItem.section_id].bomItemIds.push(newItem.id);
            }
          });

          return newItem;
        } catch (error) {
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : 'BOM 생성 실패';
          });
          throw error;
        }
      },

      updateBomItem: async (id, updates) => {
        try {
          // TODO: API 호출

          set((state) => {
            if (state.entities.bomItems[id]) {
              Object.assign(state.entities.bomItems[id], updates, {
                updated_at: new Date().toISOString(),
              });
            }
          });
        } catch (error) {
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : 'BOM 수정 실패';
          });
          throw error;
        }
      },

      deleteBomItem: async (id) => {
        try {
          // TODO: API 호출

          set((state) => {
            const item = state.entities.bomItems[id];
            if (!item) return;

            // 섹션에서 BOM ID 제거
            if (item.section_id !== null && state.entities.sections[item.section_id]) {
              const section = state.entities.sections[item.section_id];
              section.bomItemIds = section.bomItemIds.filter((bId) => bId !== id);
            }

            // 독립 BOM 목록에서 제거
            state.ids.independentBomItems = state.ids.independentBomItems.filter(
              (bId) => bId !== id
            );

            // BOM 삭제
            delete state.entities.bomItems[id];
          });
        } catch (error) {
          set((state) => {
            state.ui.error = error instanceof Error ? error.message : 'BOM 삭제 실패';
          });
          throw error;
        }
      },

      // ===== UI 액션 =====

      setLoading: (loading) => {
        set((state) => {
          state.ui.isLoading = loading;
        });
      },

      setError: (error) => {
        set((state) => {
          state.ui.error = error;
        });
      },

      selectPage: (pageId) => {
        set((state) => {
          state.ui.selectedPageId = pageId;
        });
      },

      selectSection: (sectionId) => {
        set((state) => {
          state.ui.selectedSectionId = sectionId;
        });
      },

      selectField: (fieldId) => {
        set((state) => {
          state.ui.selectedFieldId = fieldId;
        });
      },

      // ===== 초기화 =====

      reset: () => {
        set(initialState);
      },

      // ===== 속성(단위/재질/표면처리) 액션 =====

      // 단위 CRUD
      addUnit: async (unitData: {
        unitCode: string;
        unitName: string;
        description?: string;
        isActive?: boolean;
      }) => {
        try {
          const response = await itemMasterApi.units.create({
            unit_code: unitData.unitCode,
            unit_name: unitData.unitName,
            description: unitData.description,
            is_active: unitData.isActive ?? true,
          });

          const newUnit = {
            id: String(response.data.id),
            unitCode: response.data.unit_code,
            unitName: response.data.unit_name,
            description: response.data.description,
            isActive: response.data.is_active,
            createdAt: response.data.created_at,
            updatedAt: response.data.updated_at,
          };

          set((state) => {
            state.references.itemUnits.push(newUnit);
          });

          return newUnit;
        } catch (error) {
          console.error('[ItemMasterStore] addUnit 실패:', error);
          throw error;
        }
      },

      updateUnit: async (
        id: string,
        updates: {
          unitCode?: string;
          unitName?: string;
          description?: string;
          isActive?: boolean;
        }
      ) => {
        try {
          const response = await itemMasterApi.units.update(Number(id), {
            unit_code: updates.unitCode,
            unit_name: updates.unitName,
            description: updates.description,
            is_active: updates.isActive,
          });

          set((state) => {
            const index = state.references.itemUnits.findIndex((u) => u.id === id);
            if (index !== -1) {
              state.references.itemUnits[index] = {
                ...state.references.itemUnits[index],
                unitCode: updates.unitCode ?? state.references.itemUnits[index].unitCode,
                unitName: updates.unitName ?? state.references.itemUnits[index].unitName,
                description: updates.description,
                isActive: updates.isActive ?? state.references.itemUnits[index].isActive,
                updatedAt: response.data.updated_at,
              };
            }
          });

        } catch (error) {
          console.error('[ItemMasterStore] updateUnit 실패:', error);
          throw error;
        }
      },

      deleteUnit: async (id) => {
        try {
          await itemMasterApi.units.delete(Number(id));

          set((state) => {
            state.references.itemUnits = state.references.itemUnits.filter((u) => u.id !== id);
          });

        } catch (error) {
          console.error('[ItemMasterStore] deleteUnit 실패:', error);
          throw error;
        }
      },

      // 재질 CRUD
      addMaterial: async (materialData: {
        materialCode: string;
        materialName: string;
        materialType: 'STEEL' | 'ALUMINUM' | 'PLASTIC' | 'OTHER';
        thickness?: string;
        description?: string;
        isActive?: boolean;
      }) => {
        try {
          const response = await itemMasterApi.materials.create({
            material_code: materialData.materialCode,
            material_name: materialData.materialName,
            material_type: materialData.materialType || 'OTHER',
            thickness: materialData.thickness,
            description: materialData.description,
            is_active: materialData.isActive ?? true,
          });

          const newMaterial = {
            id: String(response.data.id),
            materialCode: response.data.material_code,
            materialName: response.data.material_name,
            materialType: response.data.material_type,
            thickness: response.data.thickness,
            description: response.data.description,
            isActive: response.data.is_active,
            createdAt: response.data.created_at,
            updatedAt: response.data.updated_at,
          };

          set((state) => {
            state.references.itemMaterials.push(newMaterial);
          });

          return newMaterial;
        } catch (error) {
          console.error('[ItemMasterStore] addMaterial 실패:', error);
          throw error;
        }
      },

      updateMaterial: async (
        id: string,
        updates: {
          materialCode?: string;
          materialName?: string;
          materialType?: 'STEEL' | 'ALUMINUM' | 'PLASTIC' | 'OTHER';
          thickness?: string;
          description?: string;
          isActive?: boolean;
        }
      ) => {
        try {
          const response = await itemMasterApi.materials.update(id, {
            material_code: updates.materialCode,
            material_name: updates.materialName,
            material_type: updates.materialType,
            thickness: updates.thickness,
            description: updates.description,
            is_active: updates.isActive,
          });

          set((state) => {
            const index = state.references.itemMaterials.findIndex((m) => m.id === id);
            if (index !== -1) {
              state.references.itemMaterials[index] = {
                ...state.references.itemMaterials[index],
                materialCode: updates.materialCode ?? state.references.itemMaterials[index].materialCode,
                materialName: updates.materialName ?? state.references.itemMaterials[index].materialName,
                materialType: updates.materialType ?? state.references.itemMaterials[index].materialType,
                thickness: updates.thickness,
                description: updates.description,
                isActive: updates.isActive ?? state.references.itemMaterials[index].isActive,
                updatedAt: response.data.updated_at,
              };
            }
          });

        } catch (error) {
          console.error('[ItemMasterStore] updateMaterial 실패:', error);
          throw error;
        }
      },

      deleteMaterial: async (id) => {
        try {
          await itemMasterApi.materials.delete(id);

          set((state) => {
            state.references.itemMaterials = state.references.itemMaterials.filter((m) => m.id !== id);
          });

        } catch (error) {
          console.error('[ItemMasterStore] deleteMaterial 실패:', error);
          throw error;
        }
      },

      // 표면처리 CRUD
      addTreatment: async (treatmentData: {
        treatmentCode: string;
        treatmentName: string;
        treatmentType: 'PAINTING' | 'COATING' | 'PLATING' | 'NONE';
        description?: string;
        isActive?: boolean;
      }) => {
        try {
          const response = await itemMasterApi.treatments.create({
            treatment_code: treatmentData.treatmentCode,
            treatment_name: treatmentData.treatmentName,
            treatment_type: treatmentData.treatmentType || 'NONE',
            description: treatmentData.description,
            is_active: treatmentData.isActive ?? true,
          });

          const newTreatment = {
            id: String(response.data.id),
            treatmentCode: response.data.treatment_code,
            treatmentName: response.data.treatment_name,
            treatmentType: response.data.treatment_type,
            description: response.data.description,
            isActive: response.data.is_active,
            createdAt: response.data.created_at,
            updatedAt: response.data.updated_at,
          };

          set((state) => {
            state.references.surfaceTreatments.push(newTreatment);
          });

          return newTreatment;
        } catch (error) {
          console.error('[ItemMasterStore] addTreatment 실패:', error);
          throw error;
        }
      },

      updateTreatment: async (
        id: string,
        updates: {
          treatmentCode?: string;
          treatmentName?: string;
          treatmentType?: 'PAINTING' | 'COATING' | 'PLATING' | 'NONE';
          description?: string;
          isActive?: boolean;
        }
      ) => {
        try {
          const response = await itemMasterApi.treatments.update(id, {
            treatment_code: updates.treatmentCode,
            treatment_name: updates.treatmentName,
            treatment_type: updates.treatmentType,
            description: updates.description,
            is_active: updates.isActive,
          });

          set((state) => {
            const index = state.references.surfaceTreatments.findIndex((t) => t.id === id);
            if (index !== -1) {
              state.references.surfaceTreatments[index] = {
                ...state.references.surfaceTreatments[index],
                treatmentCode: updates.treatmentCode ?? state.references.surfaceTreatments[index].treatmentCode,
                treatmentName: updates.treatmentName ?? state.references.surfaceTreatments[index].treatmentName,
                treatmentType: updates.treatmentType ?? state.references.surfaceTreatments[index].treatmentType,
                description: updates.description,
                isActive: updates.isActive ?? state.references.surfaceTreatments[index].isActive,
                updatedAt: response.data.updated_at,
              };
            }
          });

        } catch (error) {
          console.error('[ItemMasterStore] updateTreatment 실패:', error);
          throw error;
        }
      },

      deleteTreatment: async (id) => {
        try {
          await itemMasterApi.treatments.delete(id);

          set((state) => {
            state.references.surfaceTreatments = state.references.surfaceTreatments.filter((t) => t.id !== id);
          });

        } catch (error) {
          console.error('[ItemMasterStore] deleteTreatment 실패:', error);
          throw error;
        }
      },

      // ===== 섹션 복제 =====

      cloneSection: async (sectionId) => {
        try {
          const response = await itemMasterApi.sections.clone(sectionId);

          // 정규화된 섹션 엔티티 생성
          const clonedSection = normalizeSectionResponse(response);

          set((state) => {
            state.entities.sections[clonedSection.id] = clonedSection;
            // 독립 섹션으로 추가
            state.ids.independentSections.push(clonedSection.id);
          });

          return clonedSection;
        } catch (error) {
          console.error('[ItemMasterStore] cloneSection 실패:', error);
          throw error;
        }
      },

      // ===== API 연동 =====

      initFromApi: async () => {
        set((state) => {
          state.ui.isLoading = true;
          state.ui.error = null;
        });

        try {
          // API 호출
          const data = await itemMasterApi.init();

          // 정규화
          const normalized = normalizeInitResponse(data);

          set((state) => {
            // 엔티티 설정
            state.entities = normalized.entities;
            state.ids = normalized.ids;

            // 참조 데이터 설정 (API에서 masterFields 등 포함 시)
            if (data.masterFields) {
              state.references.masterFields = data.masterFields;
            }

            state.ui.isLoading = false;
          });

        } catch (error) {
          console.error('[ItemMasterStore] initFromApi 실패:', error);
          set((state) => {
            state.ui.isLoading = false;
            state.ui.error = error instanceof Error ? error.message : 'API 초기화 실패';
          });
          throw error;
        }
      },
    })),
    { name: 'item-master-store' }
  )
);

// ===== 타입 export =====
export type { ItemMasterStore, ItemMasterState };