// =================================================================
// KT AI 이벤트 마케팅 서비스 - 공통 JavaScript 모듈
// Version: 1.0.0
// =================================================================

const KTEventApp = (() => {
  'use strict';

  // =================================================================
  // 1. Utility Functions
  // =================================================================
  const Utils = {
    /**
     * 전화번호 포맷팅 (010-1234-5678)
     */
    formatPhoneNumber(phone) {
      const cleaned = phone.replace(/\D/g, '');
      const match = cleaned.match(/^(\d{3})(\d{3,4})(\d{4})$/);
      if (match) {
        return `${match[1]}-${match[2]}-${match[3]}`;
      }
      return phone;
    },

    /**
     * 이메일 유효성 검사
     */
    validateEmail(email) {
      const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return re.test(email);
    },

    /**
     * 비밀번호 유효성 검사 (8자 이상, 영문+숫자 포함)
     */
    validatePassword(password) {
      const hasLength = password.length >= 8;
      const hasLetter = /[a-zA-Z]/.test(password);
      const hasNumber = /\d/.test(password);
      return hasLength && hasLetter && hasNumber;
    },

    /**
     * 날짜 포맷팅 (YYYY.MM.DD)
     */
    formatDate(date) {
      if (typeof date === 'string') {
        date = new Date(date);
      }
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}.${month}.${day}`;
    },

    /**
     * 날짜 시간 포맷팅 (YYYY.MM.DD HH:MM)
     */
    formatDateTime(date) {
      if (typeof date === 'string') {
        date = new Date(date);
      }
      const dateStr = this.formatDate(date);
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${dateStr} ${hours}:${minutes}`;
    },

    /**
     * 숫자 포맷팅 (1,234,567)
     */
    formatNumber(num) {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    },

    /**
     * 금액 포맷팅 (1,234,567원)
     */
    formatCurrency(amount) {
      return `${this.formatNumber(amount)}원`;
    },

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

    /**
     * LocalStorage 저장
     */
    saveToStorage(key, value) {
      try {
        localStorage.setItem(key, JSON.stringify(value));
        return true;
      } catch (e) {
        console.error('Storage save failed:', e);
        return false;
      }
    },

    /**
     * LocalStorage 읽기
     */
    getFromStorage(key, defaultValue = null) {
      try {
        const item = localStorage.getItem(key);
        return item ? JSON.parse(item) : defaultValue;
      } catch (e) {
        console.error('Storage read failed:', e);
        return defaultValue;
      }
    },

    /**
     * LocalStorage 삭제
     */
    removeFromStorage(key) {
      try {
        localStorage.removeItem(key);
        return true;
      } catch (e) {
        console.error('Storage remove failed:', e);
        return false;
      }
    },

    /**
     * 랜덤 ID 생성
     */
    generateId() {
      return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    }
  };

  // =================================================================
  // 2. Navigation Components
  // =================================================================
  const Navigation = {
    /**
     * 헤더 생성
     */
    createHeader({ title = '', showBack = true, showMenu = true, showProfile = true } = {}) {
      const header = document.createElement('header');
      header.className = 'header';

      const leftDiv = document.createElement('div');
      leftDiv.className = 'header-left';

      if (showMenu) {
        const menuBtn = document.createElement('button');
        menuBtn.className = 'header-icon-btn';
        menuBtn.innerHTML = '<span class="material-icons">menu</span>';
        menuBtn.setAttribute('aria-label', '메뉴');
        leftDiv.appendChild(menuBtn);
      }

      if (showBack) {
        const backBtn = document.createElement('button');
        backBtn.className = 'header-icon-btn';
        backBtn.innerHTML = '<span class="material-icons">arrow_back</span>';
        backBtn.setAttribute('aria-label', '뒤로가기');
        backBtn.addEventListener('click', () => window.history.back());
        leftDiv.appendChild(backBtn);
      }

      const titleEl = document.createElement('h1');
      titleEl.className = 'header-title';
      titleEl.textContent = title;
      leftDiv.appendChild(titleEl);

      const rightDiv = document.createElement('div');
      rightDiv.className = 'header-right';

      if (showProfile) {
        const profileBtn = document.createElement('button');
        profileBtn.className = 'header-icon-btn';
        profileBtn.innerHTML = '<span class="material-icons">account_circle</span>';
        profileBtn.setAttribute('aria-label', '프로필');
        rightDiv.appendChild(profileBtn);
      }

      header.appendChild(leftDiv);
      header.appendChild(rightDiv);

      return header;
    },

    /**
     * 하단 네비게이션 생성
     */
    createBottomNav(currentPage = 'home') {
      const nav = document.createElement('nav');
      nav.className = 'bottom-nav';
      nav.setAttribute('role', 'navigation');
      nav.setAttribute('aria-label', '주 네비게이션');

      const navItems = [
        { id: 'home', label: '홈', icon: 'home', href: '05-대시보드.html' },
        { id: 'events', label: '이벤트', icon: 'celebration', href: '06-이벤트목록.html' },
        { id: 'analytics', label: '분석', icon: 'analytics', href: '17-성과분석.html' },
        { id: 'profile', label: '프로필', icon: 'person', href: '03-프로필.html' }
      ];

      navItems.forEach(item => {
        const link = document.createElement('a');
        link.className = 'bottom-nav-item';
        if (item.id === currentPage) {
          link.classList.add('active');
        }
        link.href = item.href;
        link.innerHTML = `
          <span class="material-icons bottom-nav-icon">${item.icon}</span>
          <span>${item.label}</span>
        `;
        nav.appendChild(link);
      });

      return nav;
    },

    /**
     * Floating Action Button 생성
     */
    createFAB(icon = 'add', onClick) {
      const fab = document.createElement('button');
      fab.className = 'fab';
      fab.innerHTML = `<span class="material-icons">${icon}</span>`;
      fab.setAttribute('aria-label', '새 이벤트 생성');

      if (onClick) {
        fab.addEventListener('click', onClick);
      }

      return fab;
    }
  };

  // =================================================================
  // 3. Form Components
  // =================================================================
  const Form = {
    /**
     * 입력 필드 생성
     */
    createInput({
      type = 'text',
      id,
      name,
      label,
      placeholder = '',
      required = false,
      value = '',
      error = '',
      hint = '',
      disabled = false,
      onChange
    } = {}) {
      const group = document.createElement('div');
      group.className = 'form-group';

      if (label) {
        const labelEl = document.createElement('label');
        labelEl.className = 'form-label';
        if (required) {
          labelEl.classList.add('form-label-required');
        }
        labelEl.setAttribute('for', id);
        labelEl.textContent = label;
        group.appendChild(labelEl);
      }

      const input = document.createElement('input');
      input.type = type;
      input.id = id;
      input.name = name || id;
      input.className = 'form-input';
      input.placeholder = placeholder;
      input.value = value;
      input.disabled = disabled;

      if (required) {
        input.required = true;
      }

      if (onChange) {
        input.addEventListener('input', onChange);
      }

      group.appendChild(input);

      if (error) {
        const errorEl = document.createElement('span');
        errorEl.className = 'form-error';
        errorEl.textContent = error;
        group.appendChild(errorEl);
      }

      if (hint) {
        const hintEl = document.createElement('span');
        hintEl.className = 'form-hint';
        hintEl.textContent = hint;
        group.appendChild(hintEl);
      }

      return { group, input };
    },

    /**
     * 선택 필드 생성
     */
    createSelect({
      id,
      name,
      label,
      options = [],
      required = false,
      value = '',
      onChange
    } = {}) {
      const group = document.createElement('div');
      group.className = 'form-group';

      if (label) {
        const labelEl = document.createElement('label');
        labelEl.className = 'form-label';
        if (required) {
          labelEl.classList.add('form-label-required');
        }
        labelEl.setAttribute('for', id);
        labelEl.textContent = label;
        group.appendChild(labelEl);
      }

      const select = document.createElement('select');
      select.id = id;
      select.name = name || id;
      select.className = 'form-select';

      if (required) {
        select.required = true;
      }

      options.forEach(opt => {
        const option = document.createElement('option');
        option.value = opt.value;
        option.textContent = opt.label;
        if (opt.value === value) {
          option.selected = true;
        }
        select.appendChild(option);
      });

      if (onChange) {
        select.addEventListener('change', onChange);
      }

      group.appendChild(select);

      return { group, select };
    },

    /**
     * 텍스트 영역 생성
     */
    createTextarea({
      id,
      name,
      label,
      placeholder = '',
      required = false,
      value = '',
      rows = 4,
      onChange
    } = {}) {
      const group = document.createElement('div');
      group.className = 'form-group';

      if (label) {
        const labelEl = document.createElement('label');
        labelEl.className = 'form-label';
        if (required) {
          labelEl.classList.add('form-label-required');
        }
        labelEl.setAttribute('for', id);
        labelEl.textContent = label;
        group.appendChild(labelEl);
      }

      const textarea = document.createElement('textarea');
      textarea.id = id;
      textarea.name = name || id;
      textarea.className = 'form-textarea';
      textarea.placeholder = placeholder;
      textarea.value = value;
      textarea.rows = rows;

      if (required) {
        textarea.required = true;
      }

      if (onChange) {
        textarea.addEventListener('input', onChange);
      }

      group.appendChild(textarea);

      return { group, textarea };
    },

    /**
     * 체크박스 생성
     */
    createCheckbox({
      id,
      name,
      label,
      checked = false,
      onChange
    } = {}) {
      const checkDiv = document.createElement('div');
      checkDiv.className = 'form-check';

      const input = document.createElement('input');
      input.type = 'checkbox';
      input.id = id;
      input.name = name || id;
      input.className = 'form-check-input';
      input.checked = checked;

      if (onChange) {
        input.addEventListener('change', onChange);
      }

      const labelEl = document.createElement('label');
      labelEl.className = 'form-check-label';
      labelEl.setAttribute('for', id);
      labelEl.textContent = label;

      checkDiv.appendChild(input);
      checkDiv.appendChild(labelEl);

      return { checkDiv, input };
    },

    /**
     * 라디오 버튼 생성
     */
    createRadio({
      id,
      name,
      value,
      label,
      checked = false,
      onChange
    } = {}) {
      const radioDiv = document.createElement('div');
      radioDiv.className = 'form-check';

      const input = document.createElement('input');
      input.type = 'radio';
      input.id = id;
      input.name = name;
      input.value = value;
      input.className = 'form-check-input';
      input.checked = checked;

      if (onChange) {
        input.addEventListener('change', onChange);
      }

      const labelEl = document.createElement('label');
      labelEl.className = 'form-check-label';
      labelEl.setAttribute('for', id);
      labelEl.textContent = label;

      radioDiv.appendChild(input);
      radioDiv.appendChild(labelEl);

      return { radioDiv, input };
    },

    /**
     * 버튼 생성
     */
    createButton({
      text,
      variant = 'primary',
      size = 'large',
      icon = null,
      fullWidth = false,
      disabled = false,
      onClick
    } = {}) {
      const button = document.createElement('button');
      button.className = `btn btn-${variant} btn-${size}`;

      if (fullWidth) {
        button.classList.add('btn-full');
      }

      button.disabled = disabled;

      if (icon) {
        const iconEl = document.createElement('span');
        iconEl.className = 'material-icons';
        iconEl.textContent = icon;
        button.appendChild(iconEl);
      }

      const textNode = document.createTextNode(text);
      button.appendChild(textNode);

      if (onClick) {
        button.addEventListener('click', onClick);
      }

      return button;
    }
  };

  // =================================================================
  // 4. Feedback Components
  // =================================================================
  const Feedback = {
    /**
     * Toast 메시지 표시
     */
    showToast(message, duration = 3000) {
      const toast = document.createElement('div');
      toast.className = 'toast';
      toast.textContent = message;

      document.body.appendChild(toast);

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

    /**
     * Modal 표시
     */
    showModal({ title, content, buttons = [] } = {}) {
      const backdrop = document.createElement('div');
      backdrop.className = 'modal-backdrop';

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

      if (title) {
        const header = document.createElement('div');
        header.className = 'modal-header';
        const titleEl = document.createElement('h2');
        titleEl.className = 'modal-title';
        titleEl.textContent = title;
        header.appendChild(titleEl);
        modal.appendChild(header);
      }

      if (content) {
        const body = document.createElement('div');
        body.className = 'modal-body';
        if (typeof content === 'string') {
          body.innerHTML = content;
        } else {
          body.appendChild(content);
        }
        modal.appendChild(body);
      }

      if (buttons.length > 0) {
        const footer = document.createElement('div');
        footer.className = 'modal-footer';

        buttons.forEach(btnConfig => {
          const btn = Form.createButton(btnConfig);
          footer.appendChild(btn);
        });

        modal.appendChild(footer);
      }

      const close = () => {
        backdrop.remove();
      };

      backdrop.addEventListener('click', (e) => {
        if (e.target === backdrop) {
          close();
        }
      });

      backdrop.appendChild(modal);
      document.body.appendChild(backdrop);

      return { backdrop, modal, close };
    },

    /**
     * Bottom Sheet 표시
     */
    showBottomSheet(content) {
      const backdrop = document.createElement('div');
      backdrop.className = 'modal-backdrop';

      const sheet = document.createElement('div');
      sheet.className = 'bottom-sheet';

      const handle = document.createElement('div');
      handle.className = 'bottom-sheet-handle';
      sheet.appendChild(handle);

      const sheetContent = document.createElement('div');
      sheetContent.className = 'bottom-sheet-content';

      if (typeof content === 'string') {
        sheetContent.innerHTML = content;
      } else {
        sheetContent.appendChild(content);
      }

      sheet.appendChild(sheetContent);

      const close = () => {
        backdrop.remove();
      };

      backdrop.addEventListener('click', (e) => {
        if (e.target === backdrop) {
          close();
        }
      });

      backdrop.appendChild(sheet);
      document.body.appendChild(backdrop);

      return { backdrop, sheet, close };
    },

    /**
     * Loading Spinner 표시
     */
    showSpinner(message = '') {
      const container = document.createElement('div');
      container.className = 'spinner-center';
      container.innerHTML = `
        <div style="text-align: center;">
          <div class="spinner"></div>
          ${message ? `<p class="text-body text-secondary mt-md">${message}</p>` : ''}
        </div>
      `;
      return container;
    },

    /**
     * Progress Bar 생성
     */
    createProgressBar(value = 0) {
      const progress = document.createElement('div');
      progress.className = 'progress';

      const bar = document.createElement('div');
      bar.className = 'progress-bar';
      bar.style.width = `${value}%`;
      bar.setAttribute('role', 'progressbar');
      bar.setAttribute('aria-valuenow', value);
      bar.setAttribute('aria-valuemin', '0');
      bar.setAttribute('aria-valuemax', '100');

      progress.appendChild(bar);

      return {
        element: progress,
        setValue: (newValue) => {
          bar.style.width = `${newValue}%`;
          bar.setAttribute('aria-valuenow', newValue);
        }
      };
    }
  };

  // =================================================================
  // 5. Card Components
  // =================================================================
  const Cards = {
    /**
     * 이벤트 카드 생성
     */
    createEventCard({
      id,
      title,
      status,
      startDate,
      endDate,
      participants,
      views,
      roi,
      onClick
    } = {}) {
      const card = document.createElement('div');
      card.className = 'card event-card';

      if (onClick) {
        card.classList.add('card-clickable');
        card.addEventListener('click', () => onClick(id));
      }

      const statusBadgeClass = status === '진행중' ? 'badge-active' :
                               status === '예정' ? 'badge-scheduled' :
                               'badge-ended';

      card.innerHTML = `
        <div class="event-card-header">
          <h3 class="text-headline">${title}</h3>
          <span class="event-card-badge ${statusBadgeClass}">${status}</span>
        </div>
        <p class="text-body-small text-secondary">
          ${Utils.formatDate(startDate)} ~ ${Utils.formatDate(endDate)}
        </p>
        <div class="event-card-stats">
          <div class="stat-item">
            <div class="stat-label">참여자</div>
            <div class="stat-value">${Utils.formatNumber(participants)}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">조회수</div>
            <div class="stat-value">${Utils.formatNumber(views)}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">ROI</div>
            <div class="stat-value text-kt-red">${roi}%</div>
          </div>
        </div>
      `;

      return card;
    },

    /**
     * KPI 카드 생성
     */
    createKPICard({
      icon,
      iconType = 'primary',
      label,
      value,
      onClick
    } = {}) {
      const card = document.createElement('div');
      card.className = 'card kpi-card';

      if (onClick) {
        card.classList.add('card-clickable');
        card.addEventListener('click', onClick);
      }

      card.innerHTML = `
        <div class="kpi-icon kpi-icon-${iconType}">
          <span class="material-icons">${icon}</span>
        </div>
        <div class="kpi-content">
          <div class="kpi-label">${label}</div>
          <div class="kpi-value">${value}</div>
        </div>
      `;

      return card;
    },

    /**
     * 옵션 선택 카드 생성
     */
    createOptionCard({
      id,
      title,
      description,
      content,
      selected = false,
      onSelect
    } = {}) {
      const card = document.createElement('div');
      card.className = 'card option-card';

      if (selected) {
        card.classList.add('selected');
      }

      card.innerHTML = `
        <input type="radio" name="option" class="option-card-radio" ${selected ? 'checked' : ''}>
        <h3 class="text-headline mb-sm">${title}</h3>
        ${description ? `<p class="text-body text-secondary mb-md">${description}</p>` : ''}
        ${content || ''}
      `;

      card.addEventListener('click', () => {
        document.querySelectorAll('.option-card').forEach(c => c.classList.remove('selected'));
        card.classList.add('selected');
        const radio = card.querySelector('input[type="radio"]');
        radio.checked = true;

        if (onSelect) {
          onSelect(id);
        }
      });

      return card;
    }
  };

  // =================================================================
  // 6. Session Management
  // =================================================================
  const Session = {
    /**
     * 사용자 정보 저장
     */
    saveUser(user) {
      return Utils.saveToStorage('kt_event_user', user);
    },

    /**
     * 사용자 정보 가져오기
     */
    getUser() {
      return Utils.getFromStorage('kt_event_user');
    },

    /**
     * 로그인 여부 확인
     */
    isLoggedIn() {
      return this.getUser() !== null;
    },

    /**
     * 로그아웃
     */
    logout() {
      Utils.removeFromStorage('kt_event_user');
      window.location.href = '01-로그인.html';
    },

    /**
     * 로그인 필요 페이지 보호
     */
    requireAuth() {
      if (!this.isLoggedIn()) {
        window.location.href = '01-로그인.html';
      }
    }
  };

  // =================================================================
  // 7. Mock Data
  // =================================================================
  const MockData = {
    /**
     * 예제 이벤트 데이터
     */
    getEvents() {
      return [
        {
          id: 'evt001',
          title: 'SNS 팔로우 이벤트',
          status: '진행중',
          purpose: '신규 고객 유치',
          startDate: '2025-01-15',
          endDate: '2025-02-15',
          participants: 142,
          views: 856,
          roi: 520,
          budget: '저비용',
          channel: '온라인',
          prize: '커피 쿠폰'
        },
        {
          id: 'evt002',
          title: '설 맞이 할인 이벤트',
          status: '예정',
          purpose: '매출 증대',
          startDate: '2025-02-01',
          endDate: '2025-02-10',
          participants: 0,
          views: 0,
          roi: 0,
          budget: '중비용',
          channel: '오프라인',
          prize: '10% 할인권'
        },
        {
          id: 'evt003',
          title: '고객 만족도 조사',
          status: '종료',
          purpose: '고객 유지',
          startDate: '2024-12-01',
          endDate: '2024-12-31',
          participants: 287,
          views: 1234,
          roi: 340,
          budget: '저비용',
          channel: '온라인',
          prize: '포인트 적립'
        }
      ];
    },

    /**
     * 예제 사용자 데이터
     */
    getDefaultUser() {
      return {
        id: 'user001',
        name: '홍길동',
        email: 'hong@example.com',
        phone: '010-1234-5678',
        businessName: '홍길동 고깃집',
        businessType: '음식점',
        joinDate: '2025-01-01'
      };
    },

    /**
     * 이벤트 목적 옵션
     */
    getEventPurposes() {
      return [
        {
          id: 'new_customers',
          title: '신규 고객 유치',
          description: '새로운 고객을 매장으로 끌어들이고 싶어요',
          icon: 'person_add'
        },
        {
          id: 'sales',
          title: '매출 증대',
          description: '단기간에 매출을 올리고 싶어요',
          icon: 'trending_up'
        },
        {
          id: 'retention',
          title: '고객 유지',
          description: '기존 고객이 계속 방문하도록 하고 싶어요',
          icon: 'favorite'
        },
        {
          id: 'awareness',
          title: '브랜드 인지도',
          description: '우리 가게를 더 많은 사람에게 알리고 싶어요',
          icon: 'campaign'
        }
      ];
    },

    /**
     * AI 추천 이벤트 데이터
     */
    getAIRecommendations() {
      return {
        trends: {
          industry: '음식점업 신년 프로모션 트렌드',
          location: '강남구 음식점 할인 이벤트 증가',
          season: '설 연휴 특수 대비 고객 유치 전략'
        },
        recommendations: [
          // 저비용
          {
            budget: '저비용',
            type: '온라인',
            title: 'SNS 팔로우 이벤트',
            prize: '커피 쿠폰',
            method: 'SNS 팔로우',
            participants: 180,
            cost: 250000,
            roi: 520
          },
          {
            budget: '저비용',
            type: '오프라인',
            title: '전화번호 등록 이벤트',
            prize: '커피 쿠폰',
            method: '전화번호 등록',
            participants: 150,
            cost: 300000,
            roi: 450
          },
          // 중비용
          {
            budget: '중비용',
            type: '온라인',
            title: '리뷰 작성 이벤트',
            prize: '5천원 상품권',
            method: '리뷰 작성',
            participants: 250,
            cost: 1500000,
            roi: 380
          },
          {
            budget: '중비용',
            type: '오프라인',
            title: '방문 도장 적립 이벤트',
            prize: '무료 식사권',
            method: '방문 도장 적립',
            participants: 200,
            cost: 1800000,
            roi: 320
          },
          // 고비용
          {
            budget: '고비용',
            type: '온라인',
            title: '인플루언서 협업 이벤트',
            prize: '1만원 할인권',
            method: '인플루언서 팔로우',
            participants: 400,
            cost: 5000000,
            roi: 280
          },
          {
            budget: '고비용',
            type: '오프라인',
            title: 'VIP 고객 초대 이벤트',
            prize: '특별 메뉴 제공',
            method: 'VIP 초대장',
            participants: 300,
            cost: 6000000,
            roi: 240
          }
        ]
      };
    }
  };

  // =================================================================
  // Public API
  // =================================================================
  return {
    Utils,
    Navigation,
    Form,
    Feedback,
    Cards,
    Session,
    MockData
  };
})();

// Material Icons 폰트 로드
if (!document.querySelector('link[href*="material-icons"]')) {
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = 'https://fonts.googleapis.com/icon?family=Material+Icons';
  document.head.appendChild(link);
}

// Pretendard 폰트 로드
if (!document.querySelector('link[href*="pretendard"]')) {
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = 'https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css';
  document.head.appendChild(link);
}
