// 회의록 작성 서비스 - 공통 JavaScript

// ========== Mock Data ==========
const MockData = {
  user: {
    id: 'user-001',
    username: 'kimmin',
    name: '김민준',
    email: 'kimmin@example.com',
    role: 'user'
  },

  meetings: [
    {
      id: 'meeting-001',
      title: '주간 회의',
      startTime: '2025-01-20T14:00:00Z',
      endTime: '2025-01-20T15:00:00Z',
      location: '회의실 A',
      attendees: ['김민준', '박서연', '이준호', '최유진', '정도현'],
      attendeesCount: 5,
      status: 'scheduled'
    },
    {
      id: 'meeting-002',
      title: 'Q1 기획 회의',
      startTime: '2025-01-20T16:00:00Z',
      endTime: '2025-01-20T17:00:00Z',
      location: '회의실 B',
      attendees: ['김민준', '박서연', '이준호'],
      attendeesCount: 3,
      status: 'scheduled'
    }
  ],

  minutes: [
    {
      id: 'minutes-001',
      meetingId: 'meeting-001',
      title: 'Q4 기획 회의',
      date: '2025-01-15',
      attendees: ['김민준', '박서연', '이준호'],
      content: '# 참석자\n- 김민준\n- 박서연\n- 이준호\n\n# 논의 내용\n...',
      status: 'completed'
    },
    {
      id: 'minutes-002',
      meetingId: 'meeting-002',
      title: '개발팀 스크럼',
      date: '2025-01-14',
      attendees: ['이준호', '최유진'],
      content: '# 어제 한 일\n...',
      status: 'completed'
    }
  ],

  todos: [
    {
      id: 'todo-001',
      content: 'API 명세서 작성',
      assignee: '이준호',
      dueDate: '2025-01-25',
      status: 'inprogress',
      progress: 60,
      minutesId: 'minutes-001'
    },
    {
      id: 'todo-002',
      content: 'UI 프로토타입 완성',
      assignee: '최유진',
      dueDate: '2025-01-23',
      status: 'inprogress',
      progress: 80,
      minutesId: 'minutes-001'
    },
    {
      id: 'todo-003',
      content: '테스트 케이스 작성',
      assignee: '정도현',
      dueDate: '2025-01-22',
      status: 'completed',
      progress: 100,
      minutesId: 'minutes-002'
    }
  ],

  templates: [
    {
      id: 'general',
      name: '일반 회의',
      description: '참석자, 안건, 논의, 결정, Todo',
      sections: [
        { id: 'attendees', name: '참석자', order: 1, required: true },
        { id: 'agenda', name: '안건', order: 2, required: false },
        { id: 'discussion', name: '논의 내용', order: 3, required: true },
        { id: 'decisions', name: '결정 사항', order: 4, required: true },
        { id: 'todos', name: 'Todo', order: 5, required: false }
      ]
    },
    {
      id: 'scrum',
      name: '스크럼 회의',
      description: '어제, 오늘, 이슈',
      sections: [
        { id: 'yesterday', name: '어제 한 일', order: 1, required: true },
        { id: 'today', name: '오늘 할 일', order: 2, required: true },
        { id: 'issues', name: '이슈', order: 3, required: false }
      ]
    },
    {
      id: 'kickoff',
      name: '프로젝트 킥오프',
      description: '개요, 목표, 일정, 역할',
      sections: [
        { id: 'overview', name: '프로젝트 개요', order: 1, required: true },
        { id: 'goals', name: '목표', order: 2, required: true },
        { id: 'schedule', name: '일정', order: 3, required: true },
        { id: 'roles', name: '역할', order: 4, required: true },
        { id: 'risks', name: '리스크', order: 5, required: false }
      ]
    },
    {
      id: 'weekly',
      name: '주간 회의',
      description: '실적, 이슈, 계획',
      sections: [
        { id: 'achievements', name: '주간 실적', order: 1, required: true },
        { id: 'issues', name: '주요 이슈', order: 2, required: false },
        { id: 'plan', name: '다음 주 계획', order: 3, required: true }
      ]
    }
  ]
};

// ========== Storage Utilities ==========
const Storage = {
  set(key, value) {
    try {
      localStorage.setItem(key, JSON.stringify(value));
    } catch (e) {
      console.error('Storage set error:', e);
    }
  },

  get(key) {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : null;
    } catch (e) {
      console.error('Storage get error:', e);
      return null;
    }
  },

  remove(key) {
    try {
      localStorage.removeItem(key);
    } catch (e) {
      console.error('Storage remove error:', e);
    }
  },

  clear() {
    try {
      localStorage.clear();
    } catch (e) {
      console.error('Storage clear error:', e);
    }
  }
};

// ========== Navigation ==========
const Navigation = {
  goTo(page) {
    window.location.href = page;
  },

  goBack() {
    window.history.back();
  },

  reload() {
    window.location.reload();
  }
};

// ========== Toast Notifications ==========
const Toast = {
  show(message, type = 'info', duration = 3000) {
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');

    document.body.appendChild(toast);

    setTimeout(() => {
      toast.remove();
    }, duration);
  },

  success(message) {
    this.show(message, 'success');
  },

  error(message) {
    this.show(message, 'error');
  },

  warning(message) {
    this.show(message, 'warning');
  },

  info(message) {
    this.show(message, 'info');
  }
};

// ========== Modal ==========
const Modal = {
  show(options) {
    const { title, content, buttons = [] } = options;

    const overlay = document.createElement('div');
    overlay.className = 'modal-overlay';
    overlay.setAttribute('role', 'dialog');
    overlay.setAttribute('aria-modal', 'true');
    overlay.setAttribute('aria-labelledby', 'modal-title');

    const modal = document.createElement('div');
    modal.className = 'modal';

    const header = document.createElement('div');
    header.className = 'modal-header';
    header.innerHTML = `
      <h2 id="modal-title" class="modal-title">${title}</h2>
      <button class="modal-close" aria-label="닫기">×</button>
    `;

    const body = document.createElement('div');
    body.className = 'modal-body';
    body.innerHTML = content;

    const footer = document.createElement('div');
    footer.className = 'modal-footer';
    buttons.forEach(btn => {
      const button = document.createElement('button');
      button.className = `btn ${btn.className || 'btn-secondary'}`;
      button.textContent = btn.text;
      button.onclick = () => {
        if (btn.onClick) btn.onClick();
        this.close(overlay);
      };
      footer.appendChild(button);
    });

    modal.appendChild(header);
    modal.appendChild(body);
    if (buttons.length > 0) modal.appendChild(footer);
    overlay.appendChild(modal);
    document.body.appendChild(overlay);

    // Close handlers
    header.querySelector('.modal-close').onclick = () => this.close(overlay);
    overlay.onclick = (e) => {
      if (e.target === overlay) this.close(overlay);
    };

    return overlay;
  },

  close(overlay) {
    if (overlay && overlay.parentElement) {
      overlay.remove();
    }
  },

  confirm(message) {
    return new Promise((resolve) => {
      this.show({
        title: '확인',
        content: message,
        buttons: [
          {
            text: '취소',
            className: 'btn-secondary',
            onClick: () => resolve(false)
          },
          {
            text: '확인',
            className: 'btn-primary',
            onClick: () => resolve(true)
          }
        ]
      });
    });
  }
};

// ========== Loading ==========
const Loading = {
  show() {
    const overlay = document.createElement('div');
    overlay.className = 'loading-overlay';
    overlay.id = 'loading-overlay';
    overlay.setAttribute('role', 'status');
    overlay.setAttribute('aria-live', 'polite');
    overlay.innerHTML = '<div class="loading"></div><span class="sr-only">로딩 중...</span>';
    document.body.appendChild(overlay);
  },

  hide() {
    const overlay = document.getElementById('loading-overlay');
    if (overlay) overlay.remove();
  }
};

// ========== Form Validation ==========
const Validator = {
  required(value) {
    return value && value.trim().length > 0;
  },

  email(value) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(value);
  },

  minLength(value, length) {
    return value && value.length >= length;
  },

  maxLength(value, length) {
    return value && value.length <= length;
  },

  validateForm(formId, rules) {
    const form = document.getElementById(formId);
    if (!form) return false;

    let isValid = true;

    Object.keys(rules).forEach(fieldName => {
      const field = form.querySelector(`[name="${fieldName}"]`);
      const fieldRules = rules[fieldName];
      const formGroup = field.closest('.form-group');

      formGroup.classList.remove('has-error');

      for (const rule of fieldRules) {
        if (!rule.validator(field.value)) {
          isValid = false;
          formGroup.classList.add('has-error');
          const errorEl = formGroup.querySelector('.form-error');
          if (errorEl) errorEl.textContent = rule.message;
          break;
        }
      }
    });

    return isValid;
  }
};

// ========== Date/Time Utilities ==========
const DateTime = {
  formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('ko-KR', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  },

  formatTime(dateString) {
    const date = new Date(dateString);
    return date.toLocaleTimeString('ko-KR', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    });
  },

  formatDateTime(dateString) {
    return `${this.formatDate(dateString)} ${this.formatTime(dateString)}`;
  },

  formatDuration(seconds) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  }
};

// ========== Authentication ==========
const Auth = {
  login(username, password) {
    // Mock login - in real app, call API
    if (username === 'kimmin' && password === 'password123') {
      const token = 'mock-jwt-token-' + Date.now();
      Storage.set('auth_token', token);
      Storage.set('user', MockData.user);
      return true;
    }
    return false;
  },

  logout() {
    Storage.remove('auth_token');
    Storage.remove('user');
    Navigation.goTo('01-로그인.html');
  },

  isAuthenticated() {
    return !!Storage.get('auth_token');
  },

  getCurrentUser() {
    return Storage.get('user');
  },

  requireAuth() {
    if (!this.isAuthenticated()) {
      Navigation.goTo('01-로그인.html');
      return false;
    }
    return true;
  }
};

// ========== API Mock ==========
const API = {
  delay() {
    return new Promise(resolve => setTimeout(resolve, 500));
  },

  async getMeetings() {
    await this.delay();
    return { success: true, data: MockData.meetings };
  },

  async getMinutes() {
    await this.delay();
    return { success: true, data: MockData.minutes };
  },

  async getTodos() {
    await this.delay();
    const todos = MockData.todos;
    const summary = {
      inProgress: todos.filter(t => t.status === 'inprogress').length,
      completed: todos.filter(t => t.status === 'completed').length,
      total: todos.length
    };
    return { success: true, data: { todos, summary } };
  },

  async createMeeting(data) {
    await this.delay();
    const newMeeting = {
      id: 'meeting-' + Date.now(),
      ...data,
      status: 'scheduled'
    };
    MockData.meetings.push(newMeeting);
    return { success: true, data: newMeeting };
  },

  async getTemplates() {
    await this.delay();
    return { success: true, data: MockData.templates };
  },

  async updateTodo(id, updates) {
    await this.delay();
    const todo = MockData.todos.find(t => t.id === id);
    if (todo) {
      Object.assign(todo, updates);
      return { success: true, data: todo };
    }
    return { success: false, error: 'Todo not found' };
  }
};

// ========== UI Helpers ==========
const UI = {
  showLoading() {
    Loading.show();
  },

  hideLoading() {
    Loading.hide();
  },

  showToast(message, type = 'info') {
    Toast.show(message, type);
  },

  showModal(options) {
    return Modal.show(options);
  },

  confirm(message) {
    return Modal.confirm(message);
  },

  setTitle(title) {
    document.title = title + ' - 회의록 작성 서비스';
    const headerTitle = document.querySelector('.header-title');
    if (headerTitle) headerTitle.textContent = title;
  },

  createElement(tag, className, content) {
    const el = document.createElement(tag);
    if (className) el.className = className;
    if (content) el.innerHTML = content;
    return el;
  }
};

// ========== Initialize ==========
document.addEventListener('DOMContentLoaded', () => {
  // Back button handler
  const backButtons = document.querySelectorAll('.header-back');
  backButtons.forEach(btn => {
    btn.addEventListener('click', () => Navigation.goBack());
  });

  // Bottom navigation active state
  const currentPage = window.location.pathname.split('/').pop();
  const navItems = document.querySelectorAll('.bottom-nav-item');
  navItems.forEach(item => {
    const href = item.getAttribute('href');
    if (href === currentPage) {
      item.classList.add('active');
    }
  });
});

// ========== Export for use in pages ==========
window.App = {
  MockData,
  Storage,
  Navigation,
  Toast,
  Modal,
  Loading,
  Validator,
  DateTime,
  Auth,
  API,
  UI
};
