# AgentC Customer Chat Library

[![Version](https://img.shields.io/badge/version-1.0.0-blue.svg)](https://github.com/agentc/starter-kit)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
[![React](https://img.shields.io/badge/React-18+-blue.svg)](https://reactjs.org/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)

한국 기업을 위한 포괄적이고 반응형 고객 채팅 라이브러리입니다. 데스크톱과 모바일 환경을 모두 지원하며, 디바이스 감지, 성능 최적화, 접근성 기능이 내장되어 있습니다.

## 🌟 주요 기능

- **🎯 통합 채팅 시스템**: 모든 채팅 컴포넌트를 하나로 통합
- **📱 반응형 디자인**: 자동 디바이스 감지 및 적응형 UI
- **⚡ 성능 최적화**: 메모리 관리, 가상화, 레이지 로딩
- **🌐 다국어 지원**: 7개 언어 (한국어, 영어, 일본어, 중국어, 스페인어, 프랑스어, 독일어)
- **🎨 테마 시스템**: 기본, 다크, 컴팩트 테마 및 커스텀 테마 지원
- **♿ 접근성**: WCAG 2.1 AA 준수, 스크린 리더 지원
- **🔒 타입 안전성**: 완전한 TypeScript 지원
- **🛡️ 엣지 케이스 처리**: 방향 변경, 키보드 감지, 메모리 관리

## 📦 설치

```bash
npm install agentc-customer-chat
# 또는
yarn add agentc-customer-chat
# 또는
pnpm add agentc-customer-chat
```

## 🚀 빠른 시작

### 기본 사용법

```tsx
import { SimpleCustomerChat } from 'agentc-customer-chat';

function App() {
  return (
    <SimpleCustomerChat
      apiKey="your-api-key"
      welcomeMessage="안녕하세요! 무엇을 도와드릴까요?"
      language="ko"
      theme="default"
      onMessage={(message) => console.log('메시지 전송:', message)}
      onResponse={(response) => console.log('응답 수신:', response)}
    />
  );
}
```

### 고급 사용법

```tsx
import { 
  UnifiedCustomerChatLibrary,
  UnifiedCustomerChatLibraryConfig 
} from 'agentc-customer-chat';

const config: Partial<UnifiedCustomerChatLibraryConfig> = {
  // API 설정
  api: {
    baseUrl: 'https://api.example.com',
    apiKey: 'your-api-key',
    timeout: 10000,
    retryAttempts: 3
  },
  
  // UI 설정
  ui: {
    theme: 'dark',
    brandName: '내 브랜드',
    primaryColor: '#3B82F6',
    enableThemeToggle: true
  },
  
  // 언어 설정
  i18n: {
    defaultLanguage: 'ko',
    enableLanguageSelector: true,
    autoDetectLanguage: true
  },
  
  // 기능 설정
  features: {
    enableSuggestedQuestions: true,
    enableTypingIndicator: true,
    enableFileUpload: true,
    enableChatHistory: true,
    enableRealTimeSync: true,
    enableNotifications: true
  },
  
  // 플로팅 버튼 설정
  floatingButton: {
    enabled: true,
    position: 'bottom-right',
    size: 'medium',
    showBadge: true
  },
  
  // 반응형 설정
  mobileBreakpoint: 768,
  tabletBreakpoint: 1024,
  desktopBreakpoint: 1200,
  defaultChatMode: 'auto',
  
  // 성능 설정
  performance: {
    enableOptimization: true,
    enableMemoryManagement: true,
    enableGarbageCollection: true,
    memoryThreshold: 0.8,
    maxCacheSize: 100,
    debounceMs: 300,
    throttleMs: 100
  },
  
  // 접근성 설정
  accessibility: {
    enableScreenReader: true,
    enableKeyboardNavigation: true,
    enableHighContrast: false,
    enableFocusVisible: true,
    ariaLabels: {
      chatButton: '채팅 열기',
      closeButton: '채팅 닫기',
      sendButton: '메시지 전송'
    }
  }
};

function App() {
  return (
    <UnifiedCustomerChatLibrary
      config={config}
      onMessage={(message) => {
        console.log('메시지 전송:', message);
      }}
      onResponse={(response) => {
        console.log('응답 수신:', response);
      }}
      onDeviceChange={(deviceInfo) => {
        console.log('디바이스 변경:', deviceInfo);
      }}
      onError={(error) => {
        console.error('에러 발생:', error);
      }}
    />
  );
}
```

## 🔧 컴포넌트 API

### UnifiedCustomerChatLibrary

메인 통합 채팅 라이브러리 컴포넌트입니다.

#### Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `config` | `Partial<UnifiedCustomerChatLibraryConfig>` | `{}` | 라이브러리 설정 객체 |
| `children` | `ReactNode` | - | 자식 컴포넌트 |
| `onMessage` | `(message: string) => void` | - | 메시지 전송 시 호출 |
| `onResponse` | `(response: string) => void` | - | 응답 수신 시 호출 |
| `onDeviceChange` | `(deviceInfo: DeviceInfo) => void` | - | 디바이스 변경 시 호출 |
| `onError` | `(error: Error) => void` | - | 에러 발생 시 호출 |
| `className` | `string` | - | CSS 클래스명 |
| `style` | `CSSProperties` | - | 인라인 스타일 |

### SimpleCustomerChat

간단한 설정으로 사용할 수 있는 기본 채팅 컴포넌트입니다.

#### Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `apiKey` | `string` | - | API 키 |
| `welcomeMessage` | `string` | - | 환영 메시지 |
| `language` | `SupportedLanguage` | `'ko'` | 언어 설정 |
| `theme` | `string` | `'default'` | 테마 이름 |
| `onMessage` | `(message: string) => void` | - | 메시지 전송 시 호출 |
| `onResponse` | `(response: string) => void` | - | 응답 수신 시 호출 |

### AdvancedCustomerChat

커스터마이징 가능한 고급 채팅 컴포넌트입니다.

#### Props

`UnifiedCustomerChatLibraryProps`의 모든 props 외에:

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `customComponents` | `CustomComponents` | - | 커스텀 컴포넌트 객체 |

```tsx
interface CustomComponents {
  FloatingButton?: ComponentType<any>;
  ChatWidget?: ComponentType<any>;
  SuggestedQuestions?: ComponentType<any>;
}
```

## 🎣 훅(Hooks)

### useCustomerChat

채팅 상태와 액션을 관리하는 훅입니다.

```tsx
import { useCustomerChat } from 'agentc-customer-chat';

function MyComponent() {
  const {
    // 상태
    deviceInfo,
    isMobile,
    isTablet,
    isDesktop,
    isTouchDevice,
    isKeyboardVisible,
    connectionType,
    batteryLevel,
    isCharging,
    orientation,
    theme,
    
    // 메서드
    sendMessage,
    clearHistory,
    changeTheme
  } = useCustomerChat();
  
  return (
    <div>
      <p>현재 디바이스: {deviceInfo.type}</p>
      <p>화면 크기: {deviceInfo.screenWidth}x{deviceInfo.screenHeight}</p>
      <button onClick={() => changeTheme('dark')}>
        다크 테마로 변경
      </button>
    </div>
  );
}
```

### useDeviceDetection

디바이스 정보를 감지하는 훅입니다.

```tsx
import { useDeviceDetection } from 'agentc-customer-chat';

function MyComponent() {
  const {
    deviceInfo,
    isDesktop,
    isTablet,
    isMobile,
    orientation,
    breakpoint
  } = useDeviceDetection();
  
  return (
    <div>
      {isMobile && <MobileLayout />}
      {isTablet && <TabletLayout />}
      {isDesktop && <DesktopLayout />}
    </div>
  );
}
```

### useResponsiveChatSystem

반응형 채팅 시스템을 관리하는 통합 훅입니다.

```tsx
import { useResponsiveChatSystem } from 'agentc-customer-chat';

function MyComponent() {
  const {
    // 채팅 상태
    isOpen,
    isConnected,
    isTyping,
    messages,
    session,
    
    // 디바이스 상태
    deviceInfo,
    isDesktop,
    isMobile,
    
    // 채팅 액션
    sendMessage,
    openChat,
    closeChat,
    toggleChat,
    clearHistory,
    
    // 설정
    chatMode,
    setChatMode,
    config
  } = useResponsiveChatSystem();
  
  return (
    <div>
      <button onClick={toggleChat}>
        {isOpen ? '채팅 닫기' : '채팅 열기'}
      </button>
      <p>연결 상태: {isConnected ? '연결됨' : '연결 안됨'}</p>
      <p>메시지 수: {messages.length}</p>
    </div>
  );
}
```

## 🎨 테마 시스템

### 기본 테마

```tsx
import { themes, applyTheme } from 'agentc-customer-chat';

// 사용 가능한 테마
const availableThemes = {
  default: themes.default,
  dark: themes.dark,
  compact: themes.compact
};

// 테마 적용
applyTheme('dark');
```

### 커스텀 테마

```tsx
import { ChatbotTheme, applyTheme } from 'agentc-customer-chat';

const customTheme: ChatbotTheme = {
  primary: '#FF6B6B',
  secondary: '#4ECDC4',
  background: '#FFFFFF',
  surface: '#F8F9FA',
  text: {
    primary: '#2D3748',
    secondary: '#718096',
    inverse: '#FFFFFF'
  },
  border: '#E2E8F0',
  shadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)',
  success: '#48BB78',
  warning: '#ED8936',
  error: '#F56565',
  radius: {
    sm: '0.25rem',
    md: '0.375rem',
    lg: '0.5rem',
    full: '9999px'
  },
  spacing: {
    xs: '0.25rem',
    sm: '0.5rem',
    md: '1rem',
    lg: '1.5rem',
    xl: '2rem'
  },
  typography: {
    fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, sans-serif',
    fontSize: {
      xs: '0.75rem',
      sm: '0.875rem',
      md: '1rem',
      lg: '1.125rem',
      xl: '1.25rem'
    },
    fontWeight: {
      normal: '400',
      medium: '500',
      semibold: '600',
      bold: '700'
    }
  }
};

// 커스텀 테마 적용
applyTheme(customTheme);
```

## 🌐 다국어 지원

### 지원 언어

- `ko` - 한국어 (기본)
- `en` - English
- `ja` - 日本語
- `zh` - 中文
- `es` - Español
- `fr` - Français
- `de` - Deutsch

### 사용법

```tsx
import { I18nProvider, useI18n } from 'agentc-customer-chat';

function App() {
  return (
    <I18nProvider defaultLanguage="ko">
      <MyComponent />
    </I18nProvider>
  );
}

function MyComponent() {
  const { t, currentLanguage, changeLanguage } = useI18n();
  
  return (
    <div>
      <h1>{t('welcome')}</h1>
      <button onClick={() => changeLanguage('en')}>
        English
      </button>
    </div>
  );
}
```

### 커스텀 번역

```tsx
import { translations } from 'agentc-customer-chat';

// 기존 번역 확장
const customTranslations = {
  ...translations.ko,
  customMessage: '커스텀 메시지',
  newFeature: '새로운 기능'
};

// 새로운 언어 추가
const myLanguageTranslations = {
  chatbot: 'My Chatbot',
  placeholder: 'Type your message...',
  send: 'Send',
  // ... 기타 번역
};
```

## 📱 반응형 동작

### 디바이스 감지

라이브러리는 다음 방법으로 디바이스를 자동 감지합니다:

- **화면 크기**: 브레이크포인트 기반 감지
- **터치 지원**: 터치 이벤트 지원 여부
- **사용자 에이전트**: 브라우저 문자열 분석
- **방향**: 가로/세로 모드
- **키보드**: 모바일 키보드 표시 여부

### 브레이크포인트

```tsx
const defaultBreakpoints = {
  mobile: 768,    // 0 ~ 767px
  tablet: 1024,   // 768 ~ 1023px
  desktop: 1200   // 1024px+
};
```

### 조건부 렌더링

```tsx
import { DeviceConditional } from 'agentc-customer-chat';

function MyComponent() {
  return (
    <>
      <DeviceConditional device="mobile">
        <MobileOnlyComponent />
      </DeviceConditional>
      
      <DeviceConditional device={['tablet', 'desktop']}>
        <TabletDesktopComponent />
      </DeviceConditional>
    </>
  );
}
```

## ⚡ 성능 최적화

### 메모리 관리

```tsx
const config = {
  performance: {
    enableOptimization: true,
    enableMemoryManagement: true,
    enableGarbageCollection: true,
    memoryThreshold: 0.8,        // 80% 메모리 사용시 정리
    maxCacheSize: 100,           // 최대 캐시 아이템 수
    debounceMs: 300,            // 디바운스 시간
    throttleMs: 100             // 스로틀 시간
  }
};
```

### 가상화 리스트

```tsx
import { VirtualizedList } from 'agentc-customer-chat';

function MessageList({ messages }) {
  return (
    <VirtualizedList
      items={messages}
      itemHeight={60}
      containerHeight={400}
      renderItem={({ item, index }) => (
        <MessageItem key={item.id} message={item} />
      )}
    />
  );
}
```

### 레이지 로딩

```tsx
import { LazyComponent } from 'agentc-customer-chat';

function App() {
  return (
    <LazyComponent
      fallback={<div>로딩 중...</div>}
      rootMargin="100px"
    >
      <HeavyComponent />
    </LazyComponent>
  );
}
```

## 🛡️ 타입 안전성

### 타입 가드 사용

```tsx
import { 
  isMessage, 
  isChatSession, 
  validateUnifiedChatLibraryConfig 
} from 'agentc-customer-chat';

function handleMessage(data: unknown) {
  if (isMessage(data)) {
    // data는 이제 Message 타입
    console.log('메시지 내용:', data.content);
  }
}

function validateConfig(config: any) {
  const result = validateUnifiedChatLibraryConfig(config);
  if (!result.isValid) {
    console.error('설정 오류:', result.errors);
  }
}
```

### 런타임 검증

```tsx
import { 
  assertIsMessage, 
  sanitizeMessage,
  ChatLibraryTypeError 
} from 'agentc-customer-chat';

function processMessage(rawMessage: any) {
  try {
    // 런타임에서 타입 검증
    assertIsMessage(rawMessage);
    
    // 이제 rawMessage는 Message 타입
    console.log('검증된 메시지:', rawMessage.content);
  } catch (error) {
    if (error instanceof ChatLibraryTypeError) {
      console.error('타입 오류:', error.message);
    }
  }
}

function sanitizeUserInput(input: Partial<Message>) {
  const sanitized = sanitizeMessage(input);
  if (sanitized) {
    // 안전하게 정제된 메시지 사용
    processMessage(sanitized);
  }
}
```

## 🔧 고급 기능

### 플러그인 시스템

```tsx
import { ChatPlugin, ChatPluginContext } from 'agentc-customer-chat';

const analyticsPlugin: ChatPlugin = {
  name: 'analytics',
  version: '1.0.0',
  enabled: true,
  config: {
    trackingId: 'GA-XXXXX-XX'
  },
  initialize(context: ChatPluginContext) {
    // 플러그인 초기화 로직
    console.log('Analytics plugin initialized');
  },
  destroy() {
    // 정리 로직
    console.log('Analytics plugin destroyed');
  }
};
```

### 커스텀 컴포넌트

```tsx
import { AdvancedCustomerChat } from 'agentc-customer-chat';

function CustomFloatingButton() {
  return (
    <button className="my-custom-button">
      💬 채팅하기
    </button>
  );
}

function CustomChatWidget() {
  return (
    <div className="my-custom-chat">
      <h3>커스텀 채팅 위젯</h3>
      {/* 커스텀 UI */}
    </div>
  );
}

function App() {
  return (
    <AdvancedCustomerChat
      customComponents={{
        FloatingButton: CustomFloatingButton,
        ChatWidget: CustomChatWidget
      }}
    />
  );
}
```

### 엣지 케이스 처리

```tsx
import { useEdgeCaseHandler } from 'agentc-customer-chat';

function MyComponent() {
  const { 
    isRapidResizing,
    isOrientationChanging,
    memoryUsage,
    hasMultipleInstances 
  } = useEdgeCaseHandler({
    enableOrientationLock: true,
    enableRapidResizeProtection: true,
    enableMultipleInstancePrevention: true,
    enableMemoryLeakPrevention: true
  });
  
  if (hasMultipleInstances) {
    return <div>이미 다른 탭에서 채팅이 열려있습니다.</div>;
  }
  
  return (
    <div>
      {isRapidResizing && <div>화면 크기 조정 중...</div>}
      {memoryUsage > 0.9 && <div>메모리 사용량이 높습니다.</div>}
    </div>
  );
}
```

## 🐛 디버깅

### 개발 도구

```tsx
import { ChatLibraryDebugInfo } from 'agentc-customer-chat';

function App() {
  return (
    <>
      <MyApp />
      {/* 개발 환경에서만 표시됨 */}
      <ChatLibraryDebugInfo />
    </>
  );
}
```

### 로깅

```tsx
const config = {
  enableDebug: true,
  debugLevel: 'info' as const,  // 'error' | 'warn' | 'info' | 'debug'
};
```

## 🧪 테스트

### 단위 테스트

```tsx
import { render, screen } from '@testing-library/react';
import { SimpleCustomerChat } from 'agentc-customer-chat';

test('채팅 컴포넌트가 렌더링됨', () => {
  render(
    <SimpleCustomerChat
      apiKey="test-key"
      welcomeMessage="테스트 메시지"
    />
  );
  
  expect(screen.getByText('테스트 메시지')).toBeInTheDocument();
});
```

### 통합 테스트

```tsx
import { render, fireEvent, waitFor } from '@testing-library/react';
import { UnifiedCustomerChatLibrary } from 'agentc-customer-chat';

test('메시지 전송 기능', async () => {
  const mockOnMessage = jest.fn();
  
  render(
    <UnifiedCustomerChatLibrary
      config={{ api: { apiKey: 'test' } }}
      onMessage={mockOnMessage}
    />
  );
  
  const input = screen.getByPlaceholderText('메시지를 입력하세요...');
  const sendButton = screen.getByRole('button', { name: '전송' });
  
  fireEvent.change(input, { target: { value: '테스트 메시지' } });
  fireEvent.click(sendButton);
  
  await waitFor(() => {
    expect(mockOnMessage).toHaveBeenCalledWith('테스트 메시지');
  });
});
```

## 📄 라이선스

MIT License - 자세한 내용은 [LICENSE](LICENSE) 파일을 참조하세요.

## 🤝 기여하기

1. 포크하기
2. 기능 브랜치 생성 (`git checkout -b feature/amazing-feature`)
3. 변경사항 커밋 (`git commit -m 'Add amazing feature'`)
4. 브랜치에 푸시 (`git push origin feature/amazing-feature`)
5. Pull Request 생성

## 📞 지원

- 📧 이메일: support@agentc.kr
- 📚 문서: [https://docs.agentc.kr](https://docs.agentc.kr)
- 🐛 이슈: [GitHub Issues](https://github.com/agentc/starter-kit/issues)

## 📝 변경사항

최신 변경사항은 [CHANGELOG.md](CHANGELOG.md)를 참조하세요.

---

**AgentC Customer Chat Library**는 한국 기업의 고객 서비스를 위해 설계된 포괄적인 채팅 솔루션입니다. 🇰🇷