/**
 * 회의록 작성 및 공유 개선 서비스 - 공통 JavaScript
 * Mobile First Design
 * 작성일: 2025-10-21
 */

/* ========================================
   1. 전역 설정 및 상수
   ======================================== */
const APP_CONFIG = {
  APP_NAME: '회의록 작성 및 공유 개선 서비스',
  STORAGE_KEYS: {
    USER: 'current_user',
    MEETINGS: 'meetings_data',
    TODOS: 'todos_data',
    TEMPLATES: 'templates_data',
    INITIALIZED: 'app_initialized'
  },
  ROUTES: {
    LOGIN: '01-로그인.html',
    DASHBOARD: '02-대시보드.html',
    MEETING_SCHEDULE: '03-회의예약.html',
    TEMPLATE_SELECT: '04-템플릿선택.html',
    MEETING_IN_PROGRESS: '05-회의진행.html',
    VERIFICATION: '06-검증완료.html',
    MEETING_END: '07-회의종료.html',
    MEETING_SHARE: '08-회의록공유.html',
    TODO_MANAGE: '09-Todo관리.html',
    MEETING_DETAIL: '10-회의록상세조회.html',
    MEETING_EDIT: '11-회의록수정.html'
  }
};

// 더미 사용자 데이터
const DUMMY_USERS = [
  { id: 'EMP001', password: '1234', name: '김철수', email: 'kim@company.com', role: '기획팀', position: '팀장' },
  { id: 'EMP002', password: '1234', name: '이영희', email: 'lee@company.com', role: '개발팀', position: '선임' },
  { id: 'EMP003', password: '1234', name: '박민수', email: 'park@company.com', role: '디자인팀', position: '사원' },
  { id: 'EMP004', password: '1234', name: '정수진', email: 'jung@company.com', role: '기획팀', position: '사원' },
  { id: 'EMP005', password: '1234', name: '최동욱', email: 'choi@company.com', role: '개발팀', position: '팀장' }
];

// 템플릿 데이터
const TEMPLATES = {
  general: {
    id: 'TPL001',
    name: '일반 회의',
    type: 'general',
    icon: '📝',
    description: '참석자, 안건, 논의 내용, 결정 사항, Todo',
    sections: [
      { id: 'SEC_participants', name: '참석자', order: 1, content: '' },
      { id: 'SEC_agenda', name: '안건', order: 2, content: '' },
      { id: 'SEC_discussion', name: '논의 내용', order: 3, content: '' },
      { id: 'SEC_decisions', name: '결정 사항', order: 4, content: '' },
      { id: 'SEC_todos', name: 'Todo', order: 5, content: '' }
    ],
    isDefault: true
  },
  scrum: {
    id: 'TPL002',
    name: '스크럼 회의',
    type: 'scrum',
    icon: '🏃',
    description: '어제 한 일, 오늘 할 일, 이슈',
    sections: [
      { id: 'SEC_yesterday', name: '어제 한 일', order: 1, content: '' },
      { id: 'SEC_today', name: '오늘 할 일', order: 2, content: '' },
      { id: 'SEC_issues', name: '이슈', order: 3, content: '' }
    ],
    isDefault: false
  },
  kickoff: {
    id: 'TPL003',
    name: '프로젝트 킥오프',
    type: 'kickoff',
    icon: '🚀',
    description: '프로젝트 개요, 목표, 일정, 역할, 리스크',
    sections: [
      { id: 'SEC_overview', name: '프로젝트 개요', order: 1, content: '' },
      { id: 'SEC_goals', name: '목표', order: 2, content: '' },
      { id: 'SEC_schedule', name: '일정', order: 3, content: '' },
      { id: 'SEC_roles', name: '역할', order: 4, content: '' },
      { id: 'SEC_risks', name: '리스크', order: 5, content: '' }
    ],
    isDefault: false
  },
  weekly: {
    id: 'TPL004',
    name: '주간 회의',
    type: 'weekly',
    icon: '📅',
    description: '주간 실적, 주요 이슈, 다음 주 계획',
    sections: [
      { id: 'SEC_performance', name: '주간 실적', order: 1, content: '' },
      { id: 'SEC_issues', name: '주요 이슈', order: 2, content: '' },
      { id: 'SEC_next_week', name: '다음 주 계획', order: 3, content: '' }
    ],
    isDefault: false
  }
};

/* ========================================
   2. 유틸리티 함수
   ======================================== */
const Utils = {
  // 고유 ID 생성
  generateId: (prefix = 'ID') => {
    return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  },

  // 날짜 포맷팅
  formatDate: (date, format = 'YYYY-MM-DD') => {
    if (!date) return '';
    const d = new Date(date);
    if (isNaN(d.getTime())) return '';

    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');

    const formats = {
      'YYYY-MM-DD': `${year}-${month}-${day}`,
      'YYYY.MM.DD': `${year}.${month}.${day}`,
      'MM/DD': `${month}/${day}`,
      'YYYY-MM-DD HH:mm': `${year}-${month}-${day} ${hours}:${minutes}`,
      'HH:mm': `${hours}:${minutes}`
    };

    return formats[format] || formats['YYYY-MM-DD'];
  },

  // 상대 시간 포맷팅
  formatTimeAgo: (date) => {
    if (!date) return '';
    const now = new Date();
    const past = new Date(date);
    const diffMs = now - past;
    const diffMinutes = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMinutes < 1) return '방금 전';
    if (diffMinutes < 60) return `${diffMinutes}분 전`;
    if (diffHours < 24) return `${diffHours}시간 전`;
    if (diffDays < 7) return `${diffDays}일 전`;
    return Utils.formatDate(date);
  },

  // 경과 시간 포맷팅 (milliseconds → HH:mm:ss)
  formatDuration: (ms) => {
    const totalSeconds = Math.floor(ms / 1000);
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;

    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  },

  // 시간 포맷팅 (HH:mm → 분 단위)
  timeToMinutes: (timeString) => {
    const [hours, minutes] = timeString.split(':').map(Number);
    return hours * 60 + minutes;
  },

  // 문자열 자르기
  truncateText: (text, maxLength) => {
    if (!text || text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
  },

  // 이메일 검증
  isValidEmail: (email) => {
    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return regex.test(email);
  },

  // 사번 검증 (EMP + 3자리 숫자)
  isValidEmployeeId: (id) => {
    const regex = /^EMP\d{3}$/;
    return regex.test(id);
  },

  // DOM 헬퍼
  $: (selector) => document.querySelector(selector),
  $$: (selector) => document.querySelectorAll(selector),

  // 엘리먼트 생성
  createElement: (tag, className = '', attributes = {}) => {
    const element = document.createElement(tag);
    if (className) element.className = className;
    Object.entries(attributes).forEach(([key, value]) => {
      element.setAttribute(key, value);
    });
    return element;
  },

  // 디바운스
  debounce: (func, wait = 300) => {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout);
        func(...args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  },

  // 스로틀
  throttle: (func, limit = 100) => {
    let inThrottle;
    return function(...args) {
      if (!inThrottle) {
        func.apply(this, args);
        inThrottle = true;
        setTimeout(() => inThrottle = false, limit);
      }
    };
  },

  // 배열 섞기
  shuffleArray: (array) => {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  }
};

/* ========================================
   3. 로컬 스토리지 관리
   ======================================== */
const StorageManager = {
  // 기본 CRUD
  get: (key) => {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : null;
    } catch (e) {
      console.error('Storage get error:', e);
      return null;
    }
  },

  set: (key, value) => {
    try {
      localStorage.setItem(key, JSON.stringify(value));
      return true;
    } catch (e) {
      console.error('Storage set error:', e);
      return false;
    }
  },

  remove: (key) => {
    try {
      localStorage.removeItem(key);
      return true;
    } catch (e) {
      console.error('Storage remove error:', e);
      return false;
    }
  },

  clear: () => {
    try {
      localStorage.clear();
      return true;
    } catch (e) {
      console.error('Storage clear error:', e);
      return false;
    }
  },

  // 사용자 관련
  getCurrentUser: () => {
    return StorageManager.get(APP_CONFIG.STORAGE_KEYS.USER);
  },

  setCurrentUser: (user) => {
    return StorageManager.set(APP_CONFIG.STORAGE_KEYS.USER, user);
  },

  logout: () => {
    StorageManager.remove(APP_CONFIG.STORAGE_KEYS.USER);
    NavigationHelper.navigate('LOGIN');
  },

  // 회의록 관련
  getMeetings: () => {
    return StorageManager.get(APP_CONFIG.STORAGE_KEYS.MEETINGS) || [];
  },

  getMeetingById: (id) => {
    const meetings = StorageManager.getMeetings();
    return meetings.find(m => m.id === id);
  },

  addMeeting: (meeting) => {
    const meetings = StorageManager.getMeetings();
    meetings.push(meeting);
    return StorageManager.set(APP_CONFIG.STORAGE_KEYS.MEETINGS, meetings);
  },

  updateMeeting: (id, updates) => {
    const meetings = StorageManager.getMeetings();
    const index = meetings.findIndex(m => m.id === id);
    if (index !== -1) {
      meetings[index] = { ...meetings[index], ...updates, updatedAt: new Date().toISOString() };
      return StorageManager.set(APP_CONFIG.STORAGE_KEYS.MEETINGS, meetings);
    }
    return false;
  },

  deleteMeeting: (id) => {
    const meetings = StorageManager.getMeetings();
    const filtered = meetings.filter(m => m.id !== id);
    return StorageManager.set(APP_CONFIG.STORAGE_KEYS.MEETINGS, filtered);
  },

  // Todo 관련
  getTodos: () => {
    return StorageManager.get(APP_CONFIG.STORAGE_KEYS.TODOS) || [];
  },

  getTodoById: (id) => {
    const todos = StorageManager.getTodos();
    return todos.find(t => t.id === id);
  },

  addTodo: (todo) => {
    const todos = StorageManager.getTodos();
    todos.push(todo);
    return StorageManager.set(APP_CONFIG.STORAGE_KEYS.TODOS, todos);
  },

  updateTodo: (id, updates) => {
    const todos = StorageManager.getTodos();
    const index = todos.findIndex(t => t.id === id);
    if (index !== -1) {
      todos[index] = { ...todos[index], ...updates };
      return StorageManager.set(APP_CONFIG.STORAGE_KEYS.TODOS, todos);
    }
    return false;
  },

  deleteTodo: (id) => {
    const todos = StorageManager.getTodos();
    const filtered = todos.filter(t => t.id !== id);
    return StorageManager.set(APP_CONFIG.STORAGE_KEYS.TODOS, filtered);
  },

  // 템플릿 관련
  getTemplates: () => {
    return TEMPLATES;
  },

  getTemplateById: (type) => {
    return TEMPLATES[type] || TEMPLATES.general;
  }
};

/* ========================================
   4. 네비게이션 헬퍼
   ======================================== */
const NavigationHelper = {
  navigate: (routeKey, params = {}) => {
    const route = APP_CONFIG.ROUTES[routeKey];
    if (!route) {
      console.error('Invalid route:', routeKey);
      return;
    }

    // 파라미터를 query string으로 변환
    const queryString = Object.keys(params).length > 0
      ? '?' + Object.entries(params).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join('&')
      : '';

    window.location.href = route + queryString;
  },

  goBack: () => {
    window.history.back();
  },

  reload: () => {
    window.location.reload();
  },

  getCurrentPage: () => {
    return window.location.pathname.split('/').pop();
  },

  getQueryParams: () => {
    const params = {};
    const queryString = window.location.search.substring(1);
    const pairs = queryString.split('&');

    pairs.forEach(pair => {
      const [key, value] = pair.split('=');
      if (key) {
        params[decodeURIComponent(key)] = decodeURIComponent(value || '');
      }
    });

    return params;
  },

  getQueryParam: (key) => {
    const params = NavigationHelper.getQueryParams();
    return params[key] || null;
  },

  requireAuth: () => {
    const user = StorageManager.getCurrentUser();
    if (!user) {
      NavigationHelper.navigate('LOGIN');
      return false;
    }
    return true;
  },

  redirectToLogin: () => {
    NavigationHelper.navigate('LOGIN');
  }
};

/* ========================================
   5. UI 컴포넌트 생성기
   ======================================== */
const UIComponents = {
  // Toast 메시지
  showToast: (message, type = 'info', duration = 3000) => {
    // 기존 toast 제거
    const existing = Utils.$('.toast');
    if (existing) existing.remove();

    // 새 toast 생성
    const toast = Utils.createElement('div', `toast ${type} active`);
    toast.textContent = message;
    document.body.appendChild(toast);

    // 자동 제거
    setTimeout(() => {
      toast.classList.remove('active');
      setTimeout(() => toast.remove(), 300);
    }, duration);
  },

  // 로딩 인디케이터
  showLoading: (message = '로딩 중...') => {
    const existing = Utils.$('#loading-overlay');
    if (existing) return;

    const overlay = Utils.createElement('div', 'modal-overlay active', { id: 'loading-overlay' });
    overlay.innerHTML = `
      <div class="d-flex flex-column align-center gap-4" style="background: white; padding: 32px; border-radius: 12px;">
        <div class="spinner"></div>
        <p class="text-body">${message}</p>
      </div>
    `;
    document.body.appendChild(overlay);
  },

  hideLoading: () => {
    const overlay = Utils.$('#loading-overlay');
    if (overlay) overlay.remove();
  },

  // 확인 다이얼로그
  confirm: (message, onConfirm, onCancel) => {
    const overlay = Utils.createElement('div', 'modal-overlay active');
    overlay.innerHTML = `
      <div class="modal-container">
        <div class="modal-header">
          <h2 class="modal-title">확인</h2>
        </div>
        <div class="modal-body">
          <p class="text-body">${message}</p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" id="modal-cancel">취소</button>
          <button class="btn btn-primary" id="modal-confirm">확인</button>
        </div>
      </div>
    `;
    document.body.appendChild(overlay);

    Utils.$('#modal-confirm').addEventListener('click', () => {
      overlay.remove();
      if (onConfirm) onConfirm();
    });

    Utils.$('#modal-cancel').addEventListener('click', () => {
      overlay.remove();
      if (onCancel) onCancel();
    });

    overlay.addEventListener('click', (e) => {
      if (e.target === overlay) {
        overlay.remove();
        if (onCancel) onCancel();
      }
    });
  },

  // 모달 표시
  showModal: (options) => {
    const { title, content, footer, onClose } = options;

    const overlay = Utils.createElement('div', 'modal-overlay active');
    overlay.innerHTML = `
      <div class="modal-container">
        <div class="modal-header">
          <h2 class="modal-title">${title}</h2>
          <button class="modal-close" id="modal-close-btn">×</button>
        </div>
        <div class="modal-body">
          ${content}
        </div>
        ${footer ? `<div class="modal-footer">${footer}</div>` : ''}
      </div>
    `;
    document.body.appendChild(overlay);

    // 닫기 버튼
    Utils.$('#modal-close-btn').addEventListener('click', () => {
      overlay.remove();
      if (onClose) onClose();
    });

    // 오버레이 클릭 시 닫기
    overlay.addEventListener('click', (e) => {
      if (e.target === overlay) {
        overlay.remove();
        if (onClose) onClose();
      }
    });

    return overlay;
  },

  // 배지 생성
  createBadge: (text, type = 'status') => {
    const badgeClass = `badge badge-${type}`;
    return `<span class="${badgeClass}">${text}</span>`;
  },

  // 아바타 생성
  createAvatar: (name, size = 40) => {
    const initial = name ? name[0].toUpperCase() : '?';
    const colors = ['#2196F3', '#4CAF50', '#FF9800', '#9C27B0', '#F44336'];
    const colorIndex = name ? name.charCodeAt(0) % colors.length : 0;
    const bgColor = colors[colorIndex];

    return `
      <div class="avatar" style="width: ${size}px; height: ${size}px; background: ${bgColor}; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: ${size / 2}px;">
        ${initial}
      </div>
    `;
  },

  // 회의록 아이템 카드 생성
  createMeetingItem: (meeting) => {
    const statusText = {
      'scheduled': '예정',
      'in-progress': '진행중',
      'draft': '작성중',
      'confirmed': '확정완료'
    };

    const statusClass = {
      'scheduled': 'badge-shared',
      'in-progress': 'badge-shared',
      'draft': 'badge-draft',
      'confirmed': 'badge-confirmed'
    };

    return `
      <div class="meeting-item" onclick="NavigationHelper.navigate('MEETING_DETAIL', { id: '${meeting.id}' })">
        <div style="flex: 1;">
          <h3 class="text-h5">${meeting.title}</h3>
          <p class="text-caption text-gray">${Utils.formatDate(meeting.date)} ${meeting.startTime || ''} · ${meeting.attendees?.length || 0}명</p>
        </div>
        <div class="d-flex align-center gap-2">
          ${UIComponents.createBadge(statusText[meeting.status] || '작성중', statusClass[meeting.status] || 'draft')}
        </div>
      </div>
    `;
  },

  // Todo 아이템 카드 생성
  createTodoItem: (todo) => {
    const today = new Date();
    const dueDate = new Date(todo.dueDate);
    const diffDays = Math.ceil((dueDate - today) / (1000 * 60 * 60 * 24));

    let itemClass = 'todo-item';
    if (todo.completed) {
      itemClass += ' completed';
    } else if (diffDays < 0) {
      itemClass += ' overdue';
    } else if (diffDays <= 3) {
      itemClass += ' due-soon';
    }

    const priorityBadge = todo.priority === 'high'
      ? '<span class="badge badge-priority-high">높음</span>'
      : todo.priority === 'medium'
        ? '<span class="badge badge-priority-medium">보통</span>'
        : '';

    return `
      <div class="${itemClass}">
        <label class="form-checkbox">
          <input type="checkbox" ${todo.completed ? 'checked' : ''}
            onchange="handleTodoToggle('${todo.id}', this.checked)">
        </label>
        <div style="flex: 1;">
          <p class="text-body" style="${todo.completed ? 'text-decoration: line-through; opacity: 0.6;' : ''}">${todo.content}</p>
          <div class="d-flex align-center gap-3 mt-2">
            <span class="text-caption">👤 ${todo.assignee}</span>
            <span class="text-caption">📅 ${Utils.formatDate(todo.dueDate)}</span>
            ${priorityBadge}
          </div>
        </div>
        <button class="btn-icon" onclick="NavigationHelper.navigate('MEETING_DETAIL', { id: '${todo.meetingId}' })">→</button>
      </div>
    `;
  },

  // 진행률 바 생성
  createProgressBar: (percent) => {
    return `
      <div class="progress-bar">
        <div class="progress-fill" style="width: ${percent}%;"></div>
      </div>
    `;
  },

  // 원형 진행률 생성
  createCircularProgress: (percent) => {
    return `
      <div class="circular-progress" style="--progress-percent: ${percent}%;">
        <div class="progress-inner">
          <span class="progress-percent">${Math.round(percent)}%</span>
          <span class="progress-label">완료율</span>
        </div>
      </div>
    `;
  }
};

/* ========================================
   6. 폼 검증
   ======================================== */
const FormValidator = {
  rules: {
    required: (value) => {
      return value.trim() !== '';
    },
    email: (value) => {
      return Utils.isValidEmail(value);
    },
    minLength: (value, min) => {
      return value.length >= min;
    },
    maxLength: (value, max) => {
      return value.length <= max;
    },
    employeeId: (value) => {
      return Utils.isValidEmployeeId(value);
    }
  },

  messages: {
    required: '필수 입력 항목입니다.',
    email: '올바른 이메일 형식이 아닙니다.',
    minLength: (min) => `최소 ${min}자 이상 입력해주세요.`,
    maxLength: (max) => `최대 ${max}자까지 입력 가능합니다.`,
    employeeId: '올바른 사번 형식이 아닙니다. (예: EMP001)'
  },

  validateField: (fieldElement, ruleName, ...args) => {
    const value = fieldElement.value;
    const rule = FormValidator.rules[ruleName];

    if (!rule) {
      console.error('Unknown validation rule:', ruleName);
      return true;
    }

    const isValid = rule(value, ...args);

    if (!isValid) {
      const message = typeof FormValidator.messages[ruleName] === 'function'
        ? FormValidator.messages[ruleName](...args)
        : FormValidator.messages[ruleName];
      FormValidator.showError(fieldElement, message);
    } else {
      FormValidator.clearError(fieldElement);
    }

    return isValid;
  },

  validate: (formElement) => {
    let isValid = true;
    const fields = formElement.querySelectorAll('[data-validate]');

    fields.forEach(field => {
      const rules = field.dataset.validate.split('|');
      rules.forEach(rule => {
        const [ruleName, ...args] = rule.split(':');
        if (!FormValidator.validateField(field, ruleName, ...args)) {
          isValid = false;
        }
      });
    });

    return isValid;
  },

  showError: (fieldElement, message) => {
    FormValidator.clearError(fieldElement);

    fieldElement.classList.add('error');
    const errorDiv = Utils.createElement('div', 'form-error');
    errorDiv.textContent = message;
    fieldElement.parentNode.appendChild(errorDiv);
  },

  clearError: (fieldElement) => {
    fieldElement.classList.remove('error');
    const errorDiv = fieldElement.parentNode.querySelector('.form-error');
    if (errorDiv) errorDiv.remove();
  }
};

/* ========================================
   7. 데이터 초기화
   ======================================== */
const DataInitializer = {
  initializeSampleData: () => {
    // 이미 초기화되었는지 확인
    if (StorageManager.get(APP_CONFIG.STORAGE_KEYS.INITIALIZED)) {
      return;
    }

    // 샘플 회의록 데이터
    const sampleMeetings = [
      {
        id: 'MTG001',
        title: '프로젝트 킥오프 회의',
        date: '2025-10-20',
        startTime: '10:00',
        endTime: '11:30',
        duration: 5400000,
        location: '회의실 A',
        attendees: ['김철수', '이영희', '박민수'],
        template: 'kickoff',
        status: 'confirmed',
        sections: [
          { id: 'SEC001', name: '프로젝트 개요', content: '신규 회의록 서비스 개발 프로젝트 킥오프', verified: true, verifiedBy: ['김철수', '이영희'] },
          { id: 'SEC002', name: '목표', content: '2025년 Q4 런칭, Mobile First 설계', verified: true, verifiedBy: ['김철수'] },
          { id: 'SEC003', name: '일정', content: '기획 2주, 설계 3주, 개발 8주, 테스트 2주', verified: true, verifiedBy: ['이영희'] },
          { id: 'SEC004', name: '역할', content: '김철수(PM), 이영희(개발리드), 박민수(디자인)', verified: false, verifiedBy: [] },
          { id: 'SEC005', name: '리스크', content: '일정 지연 가능성, AI 모델 성능', verified: false, verifiedBy: [] }
        ],
        createdBy: 'EMP001',
        createdAt: '2025-10-20T09:00:00Z',
        updatedAt: '2025-10-20T11:30:00Z',
        confirmedAt: '2025-10-20T12:00:00Z',
        sharedWith: ['EMP002', 'EMP003']
      },
      {
        id: 'MTG002',
        title: '주간 스크럼 회의',
        date: '2025-10-21',
        startTime: '09:00',
        endTime: '09:30',
        duration: 1800000,
        location: '온라인',
        attendees: ['김철수', '이영희', '정수진'],
        template: 'scrum',
        status: 'confirmed',
        sections: [
          { id: 'SEC011', name: '어제 한 일', content: 'API 설계 완료, 데이터베이스 스키마 정의', verified: true, verifiedBy: ['김철수'] },
          { id: 'SEC012', name: '오늘 할 일', content: '프론트엔드 프로토타입 개발 시작', verified: true, verifiedBy: ['이영희'] },
          { id: 'SEC013', name: '이슈', content: '외부 API 연동 지연 (해결 중)', verified: true, verifiedBy: ['정수진'] }
        ],
        createdBy: 'EMP001',
        createdAt: '2025-10-21T08:30:00Z',
        updatedAt: '2025-10-21T09:30:00Z',
        confirmedAt: '2025-10-21T10:00:00Z',
        sharedWith: ['EMP002', 'EMP004']
      },
      {
        id: 'MTG003',
        title: '디자인 리뷰 회의',
        date: '2025-10-19',
        startTime: '14:00',
        endTime: '15:00',
        duration: 3600000,
        location: '회의실 B',
        attendees: ['박민수', '김철수', '정수진'],
        template: 'general',
        status: 'draft',
        sections: [
          { id: 'SEC021', name: '참석자', content: '박민수, 김철수, 정수진', verified: false, verifiedBy: [] },
          { id: 'SEC022', name: '안건', content: 'UI/UX 초안 검토', verified: false, verifiedBy: [] },
          { id: 'SEC023', name: '논의 내용', content: 'Mobile First 접근 방식 확정, 컬러 시스템 논의 중', verified: false, verifiedBy: [] },
          { id: 'SEC024', name: '결정 사항', content: '', verified: false, verifiedBy: [] },
          { id: 'SEC025', name: 'Todo', content: '', verified: false, verifiedBy: [] }
        ],
        createdBy: 'EMP003',
        createdAt: '2025-10-19T13:30:00Z',
        updatedAt: '2025-10-19T15:00:00Z',
        confirmedAt: null,
        sharedWith: []
      }
    ];

    // 샘플 Todo 데이터
    const sampleTodos = [
      {
        id: 'TODO001',
        meetingId: 'MTG001',
        sectionId: 'SEC003',
        content: '프로젝트 계획서 작성 및 공유',
        assignee: '김철수',
        assigneeId: 'EMP001',
        dueDate: '2025-10-25',
        priority: 'high',
        status: 'in-progress',
        completed: false,
        completedAt: null,
        createdAt: '2025-10-20T11:30:00Z'
      },
      {
        id: 'TODO002',
        meetingId: 'MTG001',
        sectionId: 'SEC004',
        content: '디자인 시안 1차 검토',
        assignee: '박민수',
        assigneeId: 'EMP003',
        dueDate: '2025-10-23',
        priority: 'medium',
        status: 'completed',
        completed: true,
        completedAt: '2025-10-22T15:00:00Z',
        createdAt: '2025-10-20T11:30:00Z'
      },
      {
        id: 'TODO003',
        meetingId: 'MTG002',
        sectionId: 'SEC012',
        content: 'API 문서 작성',
        assignee: '이영희',
        assigneeId: 'EMP002',
        dueDate: '2025-10-24',
        priority: 'high',
        status: 'in-progress',
        completed: false,
        completedAt: null,
        createdAt: '2025-10-21T09:30:00Z'
      },
      {
        id: 'TODO004',
        meetingId: 'MTG001',
        sectionId: 'SEC005',
        content: 'AI 모델 성능 테스트',
        assignee: '정수진',
        assigneeId: 'EMP004',
        dueDate: '2025-10-22',
        priority: 'high',
        status: 'overdue',
        completed: false,
        completedAt: null,
        createdAt: '2025-10-20T11:30:00Z'
      },
      {
        id: 'TODO005',
        meetingId: 'MTG002',
        sectionId: 'SEC013',
        content: '외부 API 연동 이슈 해결',
        assignee: '이영희',
        assigneeId: 'EMP002',
        dueDate: '2025-10-26',
        priority: 'medium',
        status: 'in-progress',
        completed: false,
        completedAt: null,
        createdAt: '2025-10-21T09:30:00Z'
      }
    ];

    // 데이터 저장
    StorageManager.set(APP_CONFIG.STORAGE_KEYS.MEETINGS, sampleMeetings);
    StorageManager.set(APP_CONFIG.STORAGE_KEYS.TODOS, sampleTodos);
    StorageManager.set(APP_CONFIG.STORAGE_KEYS.INITIALIZED, true);

    console.log('Sample data initialized successfully');
  },

  resetData: () => {
    StorageManager.clear();
    DataInitializer.initializeSampleData();
    console.log('Data reset successfully');
  }
};

/* ========================================
   8. 전역 이벤트 핸들러
   ======================================== */

// Todo 완료/미완료 토글
function handleTodoToggle(todoId, completed) {
  const todo = StorageManager.getTodoById(todoId);
  if (!todo) return;

  todo.completed = completed;
  todo.status = completed ? 'completed' : 'in-progress';
  todo.completedAt = completed ? new Date().toISOString() : null;

  StorageManager.updateTodo(todoId, todo);

  // 회의록의 Todo 섹션 업데이트
  const meeting = StorageManager.getMeetingById(todo.meetingId);
  if (meeting) {
    // 실시간 반영 시뮬레이션
    console.log(`Todo ${todoId} 완료 상태가 회의록 ${todo.meetingId}에 반영되었습니다.`);
  }

  UIComponents.showToast(
    completed ? 'Todo가 완료되었습니다' : 'Todo가 미완료로 변경되었습니다',
    completed ? 'success' : 'info'
  );

  // 현재 페이지가 Todo 관리 화면이면 리로드
  if (NavigationHelper.getCurrentPage() === APP_CONFIG.ROUTES.TODO_MANAGE) {
    setTimeout(() => window.location.reload(), 1000);
  }
}

// 마감 임박 여부 확인 (3일 이내)
function isDueSoon(dueDate) {
  if (!dueDate) return false;
  const today = new Date();
  const due = new Date(dueDate);
  const diffDays = Math.ceil((due - today) / (1000 * 60 * 60 * 24));
  return diffDays >= 0 && diffDays <= 3;
}

/* ========================================
   9. 앱 초기화
   ======================================== */
document.addEventListener('DOMContentLoaded', () => {
  // 샘플 데이터 초기화 (최초 1회만)
  DataInitializer.initializeSampleData();

  // 하단 네비게이션 활성화
  const currentPage = NavigationHelper.getCurrentPage();
  const navItems = document.querySelectorAll('.bottom-nav-item');

  navItems.forEach(item => {
    const href = item.getAttribute('href');
    if (href && href.includes(currentPage)) {
      item.classList.add('active');
    }
  });
});

// 전역 함수로 노출
window.Utils = Utils;
window.StorageManager = StorageManager;
window.NavigationHelper = NavigationHelper;
window.UIComponents = UIComponents;
window.FormValidator = FormValidator;
window.DataInitializer = DataInitializer;
window.handleTodoToggle = handleTodoToggle;
window.isDueSoon = isDueSoon;
window.TEMPLATES = TEMPLATES;
window.DUMMY_USERS = DUMMY_USERS;
