@adstage/web-sdk 2.5.3 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +59 -0
  2. package/dist/index.cjs.js +2073 -1045
  3. package/dist/index.d.ts +55 -12
  4. package/dist/index.esm.js +2073 -1045
  5. package/dist/index.standalone.js +2073 -1045
  6. package/package.json +1 -1
  7. package/src/constants/endpoints.ts +0 -1
  8. package/src/core/{AdStage.ts → adstage.ts} +36 -8
  9. package/src/index.ts +9 -3
  10. package/src/managers/ads/advertisement-event-tracker.ts +15 -11
  11. package/src/managers/ads/carousel-slider-manager.ts +90 -12
  12. package/src/managers/ads/slider-event-tracker.ts +57 -0
  13. package/src/managers/ads/text-transition-manager.ts +91 -26
  14. package/src/modules/ads/ad-renderer.ts +259 -0
  15. package/src/modules/ads/{AdsModule.ts → ads-module.ts} +202 -21
  16. package/src/modules/ads/interfaces/i-ad-renderer.ts +77 -0
  17. package/src/modules/ads/renderers/banner-ad-renderer.ts +414 -0
  18. package/src/modules/ads/renderers/base-ad-renderer.ts +340 -0
  19. package/src/modules/ads/renderers/interstitial-ad-renderer.ts +256 -0
  20. package/src/modules/ads/renderers/native-ad-renderer.ts +154 -0
  21. package/src/modules/ads/renderers/text-ad-renderer.ts +120 -0
  22. package/src/modules/ads/renderers/video-ad-renderer.ts +433 -0
  23. package/src/modules/config/{ConfigModule.ts → config-module.ts} +1 -5
  24. package/src/react/{AdStageProvider.tsx → ad-stage-provider.tsx} +1 -1
  25. package/src/react/index.ts +2 -2
  26. package/src/types/config.ts +2 -184
  27. package/src/utils/ad-click-handler.ts +155 -0
  28. package/src/utils/text-ad-utils.ts +37 -0
  29. package/src/dummy/ads_dummy.json +0 -84
  30. package/src/modules/ads/AdRenderer.ts +0 -735
  31. package/src/renderers/banner-renderer.ts +0 -35
  32. package/src/renderers/base-renderer.ts +0 -209
  33. package/src/renderers/index.ts +0 -71
  34. package/src/renderers/interstitial-renderer.ts +0 -70
  35. package/src/renderers/native-renderer.ts +0 -35
  36. package/src/renderers/text-renderer.ts +0 -94
  37. package/src/renderers/video-renderer.ts +0 -63
  38. /package/src/modules/events/{EventsModule.ts → events-module.ts} +0 -0
package/dist/index.esm.js CHANGED
@@ -31,47 +31,6 @@ var DeviceType;
31
31
  DeviceType["TABLET"] = "TABLET";
32
32
  })(DeviceType || (DeviceType = {}));
33
33
 
34
- /**
35
- * 단순한 VIEWABLE 이벤트 중복 방지 관리 클래스
36
- * - 세션당 동일 광고 1회만 VIEWABLE 이벤트 허용
37
- * - 메모리 기반 추적으로 단순화
38
- */
39
- class ViewableEventTracker {
40
- /**
41
- * 중복 viewable 이벤트 여부 확인
42
- */
43
- static isDuplicateViewable(adId, slotId, debug = false) {
44
- const key = `${adId}_${slotId}`;
45
- // 이미 VIEWABLE 이벤트가 발생한 광고인지 확인
46
- if (ViewableEventTracker.viewableTracker.has(key)) {
47
- if (debug) {
48
- console.log(`Duplicate viewable blocked for ad ${adId} in slot ${slotId}`);
49
- }
50
- return true;
51
- }
52
- // 새로운 VIEWABLE 이벤트 기록
53
- ViewableEventTracker.viewableTracker.add(key);
54
- if (debug) {
55
- console.log(`✅ New viewable recorded for ad ${adId} in slot ${slotId}`);
56
- }
57
- return false;
58
- }
59
- /**
60
- * 모든 추적 데이터 정리 (디버그용)
61
- */
62
- static clear() {
63
- ViewableEventTracker.viewableTracker.clear();
64
- }
65
- /**
66
- * 특정 광고의 viewable 추적 초기화 (디버그용)
67
- */
68
- static clearAdViewable(adId, slotId) {
69
- const key = `${adId}_${slotId}`;
70
- ViewableEventTracker.viewableTracker.delete(key);
71
- }
72
- }
73
- ViewableEventTracker.viewableTracker = new Set();
74
-
75
34
  /**
76
35
  * SSR 안전한 DOM API 래퍼 클래스
77
36
  * 서버사이드 렌더링 환경에서 DOM API 접근 시 오류를 방지합니다.
@@ -497,7 +456,7 @@ class ApiHeaders {
497
456
  * AdStage SDK - 버전 정보 유틸리티
498
457
  */
499
458
  // package.json에서 버전 정보 가져오기 (빌드 시 자동으로 교체됨)
500
- const SDK_VERSION$1 = '"2.5.3"';
459
+ const SDK_VERSION$1 = '"2.6.0"';
501
460
  /**
502
461
  * SDK 버전 정보 반환
503
462
  */
@@ -526,15 +485,6 @@ class AdvertisementEventTracker {
526
485
  if (this.debug) {
527
486
  console.log(`🚀 AdvertisementEventTracker: Processing ${eventType} event for ad ${adId} in slot ${slotId}`);
528
487
  }
529
- // VIEWABLE 이벤트 중복 확인
530
- if (eventType === AdEventType.VIEWABLE) {
531
- if (ViewableEventTracker.isDuplicateViewable(adId, slotId, this.debug)) {
532
- if (this.debug) {
533
- console.log(`⏭️ Skipping duplicate viewable event for ad ${adId} in slot ${slotId}`);
534
- }
535
- return;
536
- }
537
- }
538
488
  // 현재 슬롯 정보 가져오기
539
489
  const slot = this.slots.get(slotId);
540
490
  // 디바이스 정보 수집
@@ -578,6 +528,12 @@ class AdvertisementEventTracker {
578
528
  headers,
579
529
  eventData
580
530
  });
531
+ console.log(`🌐 Full API call details:`, {
532
+ method: 'POST',
533
+ url,
534
+ hasApiKey: !!this.apiKey,
535
+ bodySize: JSON.stringify(eventData).length
536
+ });
581
537
  }
582
538
  const response = await fetch(url, {
583
539
  method: 'POST',
@@ -599,7 +555,15 @@ class AdvertisementEventTracker {
599
555
  }
600
556
  }
601
557
  catch (error) {
602
- console.error('Failed to track advertisement event:', error);
558
+ console.error('Failed to track advertisement event:', error);
559
+ console.error('🔍 Debug info:', {
560
+ baseUrl: this.baseUrl,
561
+ apiKey: this.apiKey ? `${this.apiKey.substring(0, 8)}...` : 'NOT_SET',
562
+ url: `${this.baseUrl}/advertisements/events/${adId}/${eventType}`,
563
+ eventType,
564
+ adId,
565
+ slotId
566
+ });
603
567
  }
604
568
  }
605
569
  /**
@@ -722,7 +686,6 @@ class EndpointBuilder {
722
686
  */
723
687
  setBaseUrl(url) {
724
688
  this.baseUrl = url;
725
- console.log('🔄 API endpoint changed:', url);
726
689
  }
727
690
  /**
728
691
  * 기본 URL 반환
@@ -743,454 +706,152 @@ class EndpointBuilder {
743
706
  const endpoints = new EndpointBuilder();
744
707
 
745
708
  /**
746
- * 기본 광고 렌더러 추상 클래스
709
+ * 슬라이더 이벤트 추적 공통 유틸리티
710
+ * - 모든 슬라이더 타입에서 일관된 VIEWABLE 이벤트 추적
711
+ * - 중복 방지는 상위 레벨에서 처리
747
712
  */
748
- class BaseAdRenderer {
749
- constructor(trackEvent) {
750
- this.trackEvent = trackEvent;
751
- }
752
- /**
753
- * 공통 클릭 이벤트 핸들러 (SSR 안전)
754
- */
755
- addClickHandler(element, ad, slot) {
756
- DOMUtils.safeAddEventListener(element, 'click', () => {
757
- this.trackEvent?.(ad._id, slot.id, 'CLICK');
758
- if (ad.linkUrl) {
759
- DOMUtils.safeWindowOpen(ad.linkUrl, '_blank');
760
- }
761
- });
762
- }
763
- /**
764
- * 공통 스타일 적용 유틸리티 (SSR 안전)
765
- */
766
- applyStyles(element, styles) {
767
- DOMUtils.safeApplyStyles(element, styles);
768
- }
769
- /**
770
- * 크기 값 파싱 유틸리티 (px, %, number 지원)
771
- */
772
- parseSizeValue(value) {
773
- if (!value)
774
- return undefined;
775
- if (typeof value === 'number') {
776
- return value > 0 ? `${value}px` : undefined;
777
- }
778
- if (typeof value === 'string') {
779
- const trimmed = value.trim();
780
- if (!trimmed)
781
- return undefined;
782
- // 퍼센트 값 처리
783
- if (trimmed.endsWith('%')) {
784
- const percent = parseFloat(trimmed);
785
- return !isNaN(percent) && percent > 0 ? trimmed : undefined;
786
- }
787
- // px 값 처리 (px 단위 포함/미포함 모두 지원)
788
- const numValue = trimmed.endsWith('px')
789
- ? parseFloat(trimmed.slice(0, -2))
790
- : parseFloat(trimmed);
791
- return !isNaN(numValue) && numValue > 0 ? `${numValue}px` : undefined;
792
- }
793
- return undefined;
794
- }
795
- /**
796
- * 기본 컨테이너 스타일 (사용자 지정 크기만 적용)
797
- */
798
- getBaseContainerStyles(slot) {
799
- const styles = {
800
- cursor: 'pointer',
801
- position: 'relative',
802
- overflow: 'hidden',
803
- };
804
- // 사용자가 지정한 크기가 있을 때만 적용
805
- const parsedWidth = this.parseSizeValue(slot.width);
806
- const parsedHeight = this.parseSizeValue(slot.height);
807
- if (parsedWidth) {
808
- styles.width = parsedWidth;
809
- }
810
- if (parsedHeight) {
811
- styles.height = parsedHeight;
812
- }
813
- return styles;
814
- }
713
+ class SliderEventTracker {
815
714
  /**
816
- * 이미지 스타일 (고유 사이즈 유지, 사용자 지정 크기 우선)
715
+ * 슬라이드 변경 VIEWABLE 이벤트 추적
716
+ * @param advertisement 현재 슬라이드의 광고
717
+ * @param slot 광고 슬롯
718
+ * @param slideIndex 현재 슬라이드 인덱스
719
+ * @param trackEventCallback 이벤트 추적 콜백
720
+ * @param debug 디버그 모드
817
721
  */
818
- getImageStyles(slot) {
819
- const styles = {
820
- display: 'block',
821
- 'max-width': '100%',
822
- height: 'auto',
823
- 'object-position': 'center', // 🎯 이미지 항상 중앙 정렬
824
- };
825
- // 사용자가 컨테이너 크기를 지정한 경우에만 크기 제한
826
- const parsedWidth = this.parseSizeValue(slot?.width);
827
- const parsedHeight = this.parseSizeValue(slot?.height);
828
- if (parsedWidth && parsedHeight) {
829
- styles.width = '100%';
830
- styles.height = '100%';
831
- styles['object-fit'] = 'cover';
832
- styles['object-position'] = 'center'; // 🎯 크기 조정 시에도 중앙 정렬
722
+ static trackSlideViewable(advertisement, slot, slideIndex, trackEventCallback, debug = false) {
723
+ if (debug) {
724
+ console.log(`🎯 Triggering VIEWABLE event for slide change: ad ${advertisement._id} (index: ${slideIndex}) in slot: ${slot.id}`);
833
725
  }
834
- return styles;
726
+ // 모든 슬라이드에 대해 VIEWABLE 이벤트 추적 (첫 번째 포함)
727
+ trackEventCallback(advertisement._id, slot.id, AdEventType.VIEWABLE);
835
728
  }
836
729
  /**
837
- * 기본 폰트 스타일
730
+ * 초기 슬라이드 로딩 시 VIEWABLE 이벤트 추적
731
+ * @param advertisement 첫 번째 슬라이드의 광고
732
+ * @param slot 광고 슬롯
733
+ * @param trackEventCallback 이벤트 추적 콜백
734
+ * @param debug 디버그 모드
838
735
  */
839
- getBaseFontStyles() {
840
- return {
841
- 'font-family': 'Arial, sans-serif',
842
- 'line-height': '1.4',
843
- 'word-break': 'keep-all',
844
- };
845
- }
846
- /**
847
- * 이미지 요소 생성 (SSR 안전)
848
- */
849
- createImageElement(imageUrl, alt = '', slot) {
850
- const img = DOMUtils.safeCreateElement('img');
851
- if (!img)
852
- return null;
853
- img.src = imageUrl;
854
- img.alt = alt;
855
- this.applyStyles(img, this.getImageStyles(slot));
856
- return img;
857
- }
858
- /**
859
- * 텍스트 요소 생성 (SSR 안전)
860
- */
861
- createTextElement(text, tag = 'div', additionalStyles = {}) {
862
- const element = DOMUtils.safeCreateElement(tag);
863
- if (!element)
864
- return null;
865
- DOMUtils.safeSetTextContent(element, text);
866
- this.applyStyles(element, {
867
- ...this.getBaseFontStyles(),
868
- ...additionalStyles,
869
- });
870
- return element;
871
- }
872
- /**
873
- * 플레이스홀더 요소 생성
874
- */
875
- createPlaceholder(slot, text = '광고') {
876
- let placeholder = DOMUtils.safeCreateElement('div');
877
- // SSR 환경에서 DOM을 사용할 수 없는 경우, 런타임에 생성되도록 함
878
- if (!placeholder) {
879
- // SSR에서는 빈 div를 반환하되, 브라우저에서는 제대로 작동하도록 함
880
- if (typeof document !== 'undefined') {
881
- placeholder = document.createElement('div');
882
- }
883
- else {
884
- // SSR 환경에서는 더미 객체 반환 (타입 단언 사용)
885
- placeholder = {};
886
- }
887
- }
888
- // DOM이 사용 가능한 경우에만 스타일 적용
889
- if (DOMUtils.canUseDOM() && placeholder) {
890
- this.applyStyles(placeholder, {
891
- ...this.getBaseContainerStyles(slot),
892
- background: '#f8f9fa',
893
- display: 'flex',
894
- 'align-items': 'center',
895
- 'justify-content': 'center',
896
- color: '#6c757d',
897
- ...this.getBaseFontStyles(),
898
- // 플레이스홀더는 최소 크기 보장
899
- 'min-width': '100px',
900
- 'min-height': '100px',
901
- });
902
- DOMUtils.safeSetTextContent(placeholder, text);
903
- }
904
- return placeholder;
905
- }
906
- }
907
-
908
- /**
909
- * 배너 광고 렌더러 - 이미지만 표시
910
- */
911
- class BannerAdRenderer extends BaseAdRenderer {
912
- render(ad, slot) {
913
- const adElement = DOMUtils.safeCreateElement('div');
914
- if (!adElement) {
915
- // SSR 환경에서는 기본 div 반환
916
- return document.createElement('div');
917
- }
918
- // 기본 컨테이너 스타일 적용 (불필요한 스타일 제거)
919
- this.applyStyles(adElement, this.getBaseContainerStyles(slot));
920
- // 배너 광고는 이미지만 표시
921
- if (!ad.imageUrl) {
922
- // 이미지가 없는 경우 플레이스홀더 반환
923
- const placeholder = this.createPlaceholder(slot, '배너 광고');
924
- return placeholder || adElement;
925
- }
926
- const img = this.createImageElement(ad.imageUrl, '', slot);
927
- if (img) {
928
- DOMUtils.safeAppendChild(adElement, img);
929
- // 클릭 이벤트 추가
930
- this.addClickHandler(adElement, ad, slot);
931
- }
932
- return adElement;
933
- }
934
- }
935
-
936
- /**
937
- * 텍스트 광고 렌더러 - textContent만 표시
938
- */
939
- class TextAdRenderer extends BaseAdRenderer {
940
- render(ad, slot) {
941
- let adElement = DOMUtils.safeCreateElement('div');
942
- if (!adElement) {
943
- return this.createPlaceholder(slot, '텍스트 광고');
944
- }
945
- // 기본 컨테이너 스타일
946
- const containerStyles = {
947
- ...this.getBaseContainerStyles(slot),
948
- padding: '4px',
949
- background: 'transparent',
950
- display: 'flex',
951
- 'align-items': 'center',
952
- 'justify-content': 'center',
953
- // text-align은 사용자가 설정할 수 있도록 기본값에서 제외
954
- ...this.getBaseFontStyles(),
955
- };
956
- // 사용자가 크기를 지정하지 않은 경우 컨텐츠에 맞춤
957
- if (!slot.width || slot.width === 0) {
958
- containerStyles.display = 'inline-flex';
959
- containerStyles['white-space'] = 'nowrap';
960
- containerStyles['justify-content'] = 'flex-start'; // 좌측 정렬로 변경
961
- }
962
- // height만 자동인 경우 줄바꿈 허용
963
- if ((slot.width && slot.width !== 0) && (!slot.height || slot.height === 0)) {
964
- containerStyles['white-space'] = 'normal';
965
- containerStyles['min-height'] = 'auto';
966
- containerStyles['justify-content'] = 'flex-start'; // 좌측 정렬로 변경
967
- }
968
- this.applyStyles(adElement, containerStyles);
969
- // 텍스트 광고는 textContent만 표시
970
- if (!ad.textContent) {
971
- // 텍스트가 없는 경우 플레이스홀더 반환
972
- return this.createPlaceholder(slot, '텍스트 광고');
973
- }
974
- // 텍스트 콘텐츠 생성
975
- const textContent = this.createTextElement(ad.textContent, 'div', {
976
- 'font-size': '14px',
977
- 'font-weight': '500',
978
- color: '#212529',
979
- width: '100%', // 전체 너비 사용하여 텍스트 정렬이 적용되도록 함
980
- });
981
- if (textContent) {
982
- adElement.appendChild(textContent);
983
- }
984
- // 사용자가 text-align을 지정했는지 확인하고 레이아웃 조정
985
- setTimeout(() => {
986
- if (!adElement || typeof window === 'undefined')
987
- return;
988
- const computedStyle = window.getComputedStyle(adElement);
989
- const textAlign = computedStyle.textAlign;
990
- // 사용자가 text-align을 설정했고, width가 없는 경우
991
- if (textAlign && textAlign !== 'start' && textAlign !== 'left' && (!slot.width || slot.width === 0)) {
992
- // 블록 레벨로 변경하여 text-align이 제대로 작동하도록 함
993
- adElement.style.display = 'block';
994
- adElement.style.whiteSpace = 'normal';
995
- // 최소 너비 설정 (텍스트가 한 줄일 때를 위해)
996
- if (textContent) {
997
- const textRect = textContent.getBoundingClientRect();
998
- if (textRect.width > 0) {
999
- adElement.style.minWidth = `${textRect.width}px`;
1000
- }
1001
- }
1002
- }
1003
- }, 0);
1004
- // 클릭 이벤트 추가
1005
- this.addClickHandler(adElement, ad, slot);
1006
- return adElement;
1007
- }
1008
- }
1009
-
1010
- /**
1011
- * 네이티브 광고 렌더러 - 이미지 + textContent 표시
1012
- */
1013
- class NativeAdRenderer extends BaseAdRenderer {
1014
- render(ad, slot) {
1015
- const adElement = DOMUtils.safeCreateElement('div');
1016
- if (!adElement) {
1017
- return document.createElement('div');
1018
- }
1019
- // 컨테이너 스타일 적용 (불필요한 스타일 제거)
1020
- this.applyStyles(adElement, this.getBaseContainerStyles(slot));
1021
- // 네이티브 광고는 이미지만 표시
1022
- if (!ad.imageUrl) {
1023
- // 이미지가 없는 경우 플레이스홀더 반환
1024
- const placeholder = this.createPlaceholder(slot, '네이티브 광고');
1025
- return placeholder || adElement;
1026
- }
1027
- // 이미지 생성 (고유 사이즈 또는 사용자 지정 크기)
1028
- const img = this.createImageElement(ad.imageUrl, '', slot);
1029
- if (img) {
1030
- DOMUtils.safeAppendChild(adElement, img);
1031
- // 클릭 이벤트 추가
1032
- this.addClickHandler(adElement, ad, slot);
736
+ static trackInitialSlideViewable(advertisement, slot, trackEventCallback, debug = false) {
737
+ if (debug) {
738
+ console.log(`🎯 Triggering initial VIEWABLE event: ad ${advertisement._id} (index: 0) in slot: ${slot.id}`);
1033
739
  }
1034
- return adElement;
740
+ // 첫 번째 슬라이드도 동일하게 추적
741
+ trackEventCallback(advertisement._id, slot.id, AdEventType.VIEWABLE);
1035
742
  }
1036
743
  }
1037
744
 
1038
745
  /**
1039
- * 비디오 광고 렌더러 - 비디오 또는 이미지 표시
746
+ * 광고 클릭 이벤트 핸들러 유틸리티
747
+ * 모든 광고 타입에서 일관된 클릭 이벤트 처리를 위한 공통 컴포넌트
1040
748
  */
1041
- class VideoAdRenderer extends BaseAdRenderer {
1042
- render(ad, slot) {
1043
- let adElement = DOMUtils.safeCreateElement('div');
1044
- if (!adElement) {
1045
- return this.createPlaceholder(slot, '비디오 광고');
1046
- }
1047
- // 컨테이너 스타일 적용 (불필요한 스타일 제거)
1048
- this.applyStyles(adElement, {
1049
- ...this.getBaseContainerStyles(slot),
1050
- background: '#000',
1051
- });
1052
- // 비디오 광고는 비디오만 표시
1053
- if (!ad.videoUrl) {
1054
- // 비디오가 없는 경우 플레이스홀더 반환
1055
- return this.createPlaceholder(slot, '비디오 광고');
1056
- }
1057
- const video = this.createVideoElement(ad.videoUrl, ad, slot);
1058
- if (video) {
1059
- adElement.appendChild(video);
1060
- }
1061
- // 클릭 이벤트 추가
1062
- this.addClickHandler(adElement, ad, slot);
1063
- return adElement;
1064
- }
749
+ class AdClickHandler {
1065
750
  /**
1066
- * 비디오 요소 생성
751
+ * 광고 요소에 클릭 이벤트를 추가하는 공통 함수
752
+ * @param element - 클릭 이벤트를 추가할 DOM 요소
753
+ * @param advertisement - 광고 데이터
754
+ * @param slot - 광고 슬롯 정보
755
+ * @param trackEventCallback - 이벤트 추적 콜백 함수
756
+ * @param debug - 디버그 모드
757
+ * @param adTypeLabel - 광고 타입 라벨 (로그용, 선택사항)
1067
758
  */
1068
- createVideoElement(videoUrl, ad, slot) {
1069
- const video = DOMUtils.safeCreateElement('video');
1070
- if (!video)
1071
- return null;
1072
- video.src = videoUrl;
1073
- video.controls = true;
1074
- // 비디오도 이미지와 같은 스타일 적용
1075
- this.applyStyles(video, this.getImageStyles(slot));
1076
- // 비디오 이벤트 추적
1077
- video.addEventListener('play', () => {
1078
- this.trackEvent?.(ad._id, slot.id, 'VIDEO_START');
1079
- });
1080
- video.addEventListener('ended', () => {
1081
- this.trackEvent?.(ad._id, slot.id, 'VIDEO_COMPLETE');
1082
- });
1083
- return video;
1084
- }
1085
- }
1086
-
1087
- /**
1088
- * 전면/팝업 광고 렌더러 - 핵심 콘텐츠만 표시
1089
- */
1090
- class InterstitialAdRenderer extends BaseAdRenderer {
1091
- render(ad, slot) {
1092
- let adElement = DOMUtils.safeCreateElement('div');
1093
- if (!adElement) {
1094
- return this.createPlaceholder(slot, '전면 광고');
1095
- }
1096
- // 컨테이너 스타일 적용 (불필요한 스타일 제거)
1097
- this.applyStyles(adElement, {
1098
- ...this.getBaseContainerStyles(slot),
1099
- display: 'flex',
1100
- 'flex-direction': 'column',
1101
- });
1102
- // 우선순위: 1. 이미지, 2. 비디오, 3. 텍스트
1103
- if (ad.imageUrl) {
1104
- const img = this.createImageElement(ad.imageUrl, '', slot);
1105
- if (img) {
1106
- adElement.appendChild(img);
1107
- }
759
+ static addClickEvent(element, advertisement, slot, trackEventCallback, debug = false, adTypeLabel) {
760
+ // linkUrl이 없으면 클릭 이벤트 추가하지 않음
761
+ if (!advertisement.linkUrl) {
762
+ return;
1108
763
  }
1109
- else if (ad.videoUrl) {
1110
- // 이미지가 없고 비디오가 있는 경우
1111
- const video = this.createVideoElement(ad.videoUrl, ad, slot);
1112
- if (video) {
1113
- adElement.appendChild(video);
764
+ // 커서 스타일 설정
765
+ element.style.cursor = 'pointer';
766
+ // 클릭 이벤트 리스너 추가
767
+ element.addEventListener('click', (e) => {
768
+ e.preventDefault();
769
+ e.stopPropagation();
770
+ // 이벤트 추적
771
+ if (trackEventCallback) {
772
+ trackEventCallback(advertisement._id, slot.id, AdEventType.CLICK);
773
+ }
774
+ // 링크 이동
775
+ window.open(advertisement.linkUrl, '_blank');
776
+ // 디버그 로그
777
+ if (debug) {
778
+ const typeLabel = adTypeLabel || String(slot.adType).toLowerCase();
779
+ console.log(`🔗 ${typeLabel} ad clicked: ${advertisement._id} -> ${advertisement.linkUrl}`);
1114
780
  }
1115
- }
1116
- else {
1117
- // 모든 콘텐츠가 없는 경우
1118
- return this.createPlaceholder(slot, '전면 광고');
1119
- }
1120
- // 클릭 이벤트 추가
1121
- this.addClickHandler(adElement, ad, slot);
1122
- return adElement;
1123
- }
1124
- /**
1125
- * 비디오 요소 생성
1126
- */
1127
- createVideoElement(videoUrl, ad, slot) {
1128
- const video = DOMUtils.safeCreateElement('video');
1129
- if (!video)
1130
- return null;
1131
- video.src = videoUrl;
1132
- video.controls = true;
1133
- // 비디오도 이미지와 같은 스타일 적용
1134
- this.applyStyles(video, this.getImageStyles(slot));
1135
- // 비디오 이벤트 추적
1136
- video.addEventListener('play', () => {
1137
- this.trackEvent?.(ad._id, slot.id, 'VIDEO_START');
1138
- });
1139
- video.addEventListener('ended', () => {
1140
- this.trackEvent?.(ad._id, slot.id, 'VIDEO_COMPLETE');
1141
781
  });
1142
- return video;
1143
782
  }
1144
- }
1145
-
1146
- var _a;
1147
- /**
1148
- * 광고 렌더러 팩토리
1149
- * - 광고 타입에 따라 적절한 렌더러 인스턴스를 반환
1150
- */
1151
- class AdRendererFactory {
1152
783
  /**
1153
- * 광고 타입에 맞는 렌더러 생성
784
+ * 렌더러에서 사용할 있는 간편한 클릭 이벤트 추가 함수
785
+ * BaseAdRenderer를 상속받은 클래스에서 사용
786
+ * @param element - 클릭 이벤트를 추가할 DOM 요소
787
+ * @param advertisement - 광고 데이터
788
+ * @param slot - 광고 슬롯 정보
789
+ * @param createEventTrackingCallback - 이벤트 추적 콜백 생성 함수
790
+ * @param debug - 디버그 모드
791
+ * @param adTypeLabel - 광고 타입 라벨 (로그용, 선택사항)
1154
792
  */
1155
- static createRenderer(adType, trackEvent) {
1156
- const RendererClass = this.renderers.get(adType);
1157
- if (!RendererClass) {
1158
- console.warn(`No renderer found for ad type: ${adType}, falling back to Banner renderer`);
1159
- return new BannerAdRenderer(trackEvent);
793
+ static addClickEventForRenderer(element, advertisement, slot, createEventTrackingCallback, debug = false, adTypeLabel) {
794
+ // linkUrl이 없으면 클릭 이벤트 추가하지 않음
795
+ if (!advertisement.linkUrl) {
796
+ return;
1160
797
  }
1161
- return new RendererClass(trackEvent);
798
+ // 커서 스타일 설정
799
+ element.style.cursor = 'pointer';
800
+ // 클릭 이벤트 리스너 추가
801
+ element.addEventListener('click', (e) => {
802
+ e.preventDefault();
803
+ e.stopPropagation();
804
+ // 이벤트 추적 콜백 생성
805
+ const trackEventCallback = createEventTrackingCallback();
806
+ trackEventCallback(advertisement._id, slot.id, AdEventType.CLICK);
807
+ // 링크 이동
808
+ window.open(advertisement.linkUrl, '_blank');
809
+ // 디버그 로그
810
+ if (debug) {
811
+ const typeLabel = adTypeLabel || String(slot.adType).toLowerCase();
812
+ console.log(`🔗 ${typeLabel} ad clicked: ${advertisement._id} -> ${advertisement.linkUrl}`);
813
+ }
814
+ });
1162
815
  }
1163
816
  /**
1164
- * 광고 렌더링 (편의 메서드)
817
+ * 슬라이더/매니저에서 사용할 있는 클릭 이벤트 추가 함수
818
+ * 이미 trackEventCallback이 준비된 상황에서 사용
819
+ * @param element - 클릭 이벤트를 추가할 DOM 요소
820
+ * @param advertisement - 광고 데이터
821
+ * @param slot - 광고 슬롯 정보
822
+ * @param trackEventCallback - 준비된 이벤트 추적 콜백
823
+ * @param debug - 디버그 모드
824
+ * @param adTypeLabel - 광고 타입 라벨 (로그용, 선택사항)
1165
825
  */
1166
- static render(ad, slot, trackEvent) {
1167
- const renderer = this.createRenderer(slot.adType, trackEvent);
1168
- return renderer.render(ad, slot);
826
+ static addClickEventForSlider(element, advertisement, slot, trackEventCallback, debug = false, adTypeLabel) {
827
+ this.addClickEvent(element, advertisement, slot, trackEventCallback, debug, adTypeLabel);
1169
828
  }
1170
829
  /**
1171
- * 사용 가능한 렌더러 타입 목록
830
+ * 클릭 가능한 광고인지 확인하는 헬퍼 함수
831
+ * @param advertisement - 광고 데이터
832
+ * @returns linkUrl이 있으면 true, 없으면 false
1172
833
  */
1173
- static getSupportedAdTypes() {
1174
- return Array.from(this.renderers.keys());
834
+ static isClickable(advertisement) {
835
+ return Boolean(advertisement.linkUrl);
1175
836
  }
1176
837
  /**
1177
- * 커스텀 렌더러 등록
838
+ * 여러 요소에 대해 일괄적으로 클릭 이벤트를 추가하는 함수
839
+ * @param elements - 클릭 이벤트를 추가할 DOM 요소들
840
+ * @param advertisements - 광고 데이터 배열 (elements와 같은 순서)
841
+ * @param slot - 광고 슬롯 정보
842
+ * @param trackEventCallback - 이벤트 추적 콜백
843
+ * @param debug - 디버그 모드
844
+ * @param adTypeLabel - 광고 타입 라벨 (로그용, 선택사항)
1178
845
  */
1179
- static registerRenderer(adType, RendererClass) {
1180
- this.renderers.set(adType, RendererClass);
846
+ static addClickEventsBatch(elements, advertisements, slot, trackEventCallback, debug = false, adTypeLabel) {
847
+ elements.forEach((element, index) => {
848
+ const advertisement = advertisements[index];
849
+ if (advertisement) {
850
+ this.addClickEvent(element, advertisement, slot, trackEventCallback, debug, adTypeLabel);
851
+ }
852
+ });
1181
853
  }
1182
854
  }
1183
- _a = AdRendererFactory;
1184
- AdRendererFactory.renderers = new Map();
1185
- (() => {
1186
- // 렌더러 등록
1187
- _a.renderers.set(AdType.BANNER, BannerAdRenderer);
1188
- _a.renderers.set(AdType.TEXT, TextAdRenderer);
1189
- _a.renderers.set(AdType.NATIVE, NativeAdRenderer);
1190
- _a.renderers.set(AdType.VIDEO, VideoAdRenderer);
1191
- _a.renderers.set(AdType.INTERSTITIAL, InterstitialAdRenderer);
1192
- _a.renderers.set(AdType.POPUP, InterstitialAdRenderer); // POPUP은 INTERSTITIAL과 동일
1193
- })();
1194
855
 
1195
856
  /**
1196
857
  * 캐러셀 슬라이더 관리 클래스
@@ -1200,10 +861,78 @@ AdRendererFactory.renderers = new Map();
1200
861
  * - 도트 인디케이터 포함
1201
862
  */
1202
863
  class CarouselSliderManager {
864
+ /**
865
+ * 간단한 광고 요소 생성 (크기 측정용)
866
+ */
867
+ static createSimpleAdElement(slot, advertisement) {
868
+ const adElement = document.createElement('div');
869
+ adElement.className = `adstage-ad adstage-${String(slot.adType).toLowerCase()}`;
870
+ adElement.setAttribute('data-adstage-ad-id', advertisement._id);
871
+ adElement.setAttribute('data-adstage-slot-id', slot.id);
872
+ // 기본 스타일 설정
873
+ adElement.style.display = 'block';
874
+ adElement.style.width = '100%';
875
+ adElement.style.height = 'auto';
876
+ // 광고 타입별 기본 컨테이너 설정
877
+ switch (slot.adType) {
878
+ case AdType.BANNER:
879
+ if (advertisement.imageUrl) {
880
+ const img = document.createElement('img');
881
+ img.src = advertisement.imageUrl;
882
+ img.style.width = '100%';
883
+ img.style.height = 'auto';
884
+ img.style.objectFit = 'cover';
885
+ adElement.appendChild(img);
886
+ }
887
+ else {
888
+ adElement.style.height = '100px';
889
+ adElement.style.backgroundColor = '#f0f0f0';
890
+ adElement.style.border = '1px dashed #ccc';
891
+ adElement.textContent = 'Banner Ad';
892
+ }
893
+ break;
894
+ case AdType.VIDEO:
895
+ if (advertisement.videoUrl) {
896
+ const video = document.createElement('video');
897
+ video.src = advertisement.videoUrl;
898
+ video.style.width = '100%';
899
+ video.style.height = 'auto';
900
+ adElement.appendChild(video);
901
+ }
902
+ else {
903
+ adElement.style.height = '200px';
904
+ adElement.style.backgroundColor = '#000';
905
+ adElement.style.border = '1px solid #666';
906
+ adElement.textContent = 'Video Ad';
907
+ adElement.style.color = 'white';
908
+ }
909
+ break;
910
+ case AdType.TEXT:
911
+ if (advertisement.textContent) {
912
+ const textDiv = document.createElement('div');
913
+ textDiv.textContent = advertisement.textContent || '';
914
+ textDiv.style.padding = '8px';
915
+ textDiv.style.fontSize = '14px';
916
+ adElement.appendChild(textDiv);
917
+ }
918
+ else {
919
+ adElement.style.height = '50px';
920
+ adElement.style.padding = '8px';
921
+ adElement.textContent = 'Text Ad';
922
+ }
923
+ break;
924
+ default:
925
+ adElement.style.height = '100px';
926
+ adElement.style.border = '1px dashed #ccc';
927
+ adElement.style.backgroundColor = '#f9f9f9';
928
+ adElement.textContent = `${slot.adType} Ad`;
929
+ }
930
+ return adElement;
931
+ }
1203
932
  /**
1204
933
  * Create carousel slider container with dot indicators and navigation
1205
934
  */
1206
- static createSliderContainer(slot, advertisements, options, trackEventCallback) {
935
+ static createSliderContainer(slot, advertisements, options, trackEventCallback, debug = false) {
1207
936
  const sliderWrapper = document.createElement('div');
1208
937
  sliderWrapper.className = 'adstage-slider-wrapper';
1209
938
  // 사용자 지정 크기가 있으면 적용, 없으면 콘텐츠 크기에 맞춤
@@ -1266,7 +995,7 @@ class CarouselSliderManager {
1266
995
  let maxHeight = 0;
1267
996
  // 모든 광고의 크기를 측정하여 최대 크기 찾기
1268
997
  advertisements.forEach(ad => {
1269
- const measureAdElement = AdRendererFactory.render(ad, slot, trackEventCallback);
998
+ const measureAdElement = this.createSimpleAdElement(slot, ad);
1270
999
  measureContainer.appendChild(measureAdElement);
1271
1000
  const rect = measureAdElement.getBoundingClientRect();
1272
1001
  if (rect.width > maxWidth)
@@ -1324,7 +1053,9 @@ class CarouselSliderManager {
1324
1053
  slideElement.style.setProperty(key, value);
1325
1054
  });
1326
1055
  // 광고 렌더링
1327
- const adElement = AdRendererFactory.render(ad, slot, trackEventCallback);
1056
+ const adElement = this.createSimpleAdElement(slot, ad);
1057
+ // 클릭 이벤트 추가 (공통 컴포넌트 사용)
1058
+ AdClickHandler.addClickEventForSlider(adElement, ad, slot, trackEventCallback, debug, String(slot.adType).toLowerCase());
1328
1059
  slideElement.appendChild(adElement);
1329
1060
  slideContainer.appendChild(slideElement);
1330
1061
  });
@@ -1368,9 +1099,9 @@ class CarouselSliderManager {
1368
1099
  }
1369
1100
  });
1370
1101
  }
1371
- // 현재 슬라이드의 광고에 대해 노출 이벤트 추적 (모든 슬라이드 포함)
1372
- console.log(`🎯 Triggering VIEWABLE event for slide change: ad ${advertisements[actualIndex]._id} (index: ${actualIndex}) in slot: ${slot.id}`);
1373
- trackEventCallback(advertisements[actualIndex]._id, slot.id, AdEventType.VIEWABLE);
1102
+ // 🎯 공통 슬라이더 이벤트 추적 적용 (모든 슬라이드 포함)
1103
+ SliderEventTracker.trackSlideViewable(advertisements[actualIndex], slot, actualIndex, trackEventCallback, debug // debug 모드
1104
+ );
1374
1105
  };
1375
1106
  // 무한 루프 처리 함수
1376
1107
  const handleInfiniteLoop = () => {
@@ -1530,48 +1261,750 @@ class CarouselSliderManager {
1530
1261
  }
1531
1262
 
1532
1263
  /**
1533
- * 텍스트 전환 효과 관리 클래스
1534
- * - 텍스트 광고 전용 페이드 인/아웃 + 상하 움직임 효과
1535
- * - 부드러운 전환 애니메이션 (vertical transition)
1536
- * - 무한 루프 지원
1264
+ * 단순한 VIEWABLE 이벤트 중복 방지 관리 클래스
1265
+ * - 세션당 동일 광고 1회만 VIEWABLE 이벤트 허용
1266
+ * - 메모리 기반 추적으로 단순화
1537
1267
  */
1538
- class TextTransitionManager {
1268
+ class ViewableEventTracker {
1539
1269
  /**
1540
- * 텍스트 전환 슬라이더 컨테이너 생성
1270
+ * 중복 viewable 이벤트 여부 확인
1541
1271
  */
1542
- static createTextTransitionContainer(slot, advertisements, options, trackEventCallback) {
1543
- const sliderWrapper = document.createElement('div');
1544
- sliderWrapper.className = 'adstage-fade-slider-wrapper';
1545
- // 래퍼 스타일 설정
1546
- const containerStyles = {
1547
- position: 'relative',
1548
- overflow: 'hidden',
1549
- display: 'inline-block',
1550
- };
1551
- // 사용자가 크기를 지정한 경우
1552
- if (slot.width && slot.width !== 0) {
1553
- let width;
1554
- if (typeof slot.width === 'string') {
1555
- width = slot.width.includes('px') || slot.width.includes('%') ? slot.width : `${slot.width}px`;
1556
- }
1557
- else {
1558
- width = `${slot.width}px`;
1272
+ static isDuplicateViewable(adId, slotId, debug = false) {
1273
+ const key = `${adId}_${slotId}`;
1274
+ // 이미 VIEWABLE 이벤트가 발생한 광고인지 확인
1275
+ if (ViewableEventTracker.viewableTracker.has(key)) {
1276
+ if (debug) {
1277
+ console.log(`Duplicate viewable blocked for ad ${adId} in slot ${slotId}`);
1559
1278
  }
1560
- containerStyles.width = width;
1279
+ return true;
1561
1280
  }
1562
- if (slot.height && slot.height !== 0) {
1563
- let height;
1564
- if (typeof slot.height === 'string') {
1565
- height = slot.height.includes('px') || slot.height.includes('%') ? slot.height : `${slot.height}px`;
1566
- }
1567
- else {
1568
- height = `${slot.height}px`;
1569
- }
1570
- containerStyles.height = height;
1281
+ // 새로운 VIEWABLE 이벤트 기록
1282
+ ViewableEventTracker.viewableTracker.add(key);
1283
+ if (debug) {
1284
+ console.log(`✅ New viewable recorded for ad ${adId} in slot ${slotId}`);
1571
1285
  }
1572
- // 스타일 적용
1573
- Object.entries(containerStyles).forEach(([key, value]) => {
1574
- sliderWrapper.style.setProperty(key, value);
1286
+ return false;
1287
+ }
1288
+ /**
1289
+ * 모든 추적 데이터 정리 (디버그용)
1290
+ */
1291
+ static clear() {
1292
+ ViewableEventTracker.viewableTracker.clear();
1293
+ }
1294
+ /**
1295
+ * 특정 광고의 viewable 추적 초기화 (디버그용)
1296
+ */
1297
+ static clearAdViewable(adId, slotId) {
1298
+ const key = `${adId}_${slotId}`;
1299
+ ViewableEventTracker.viewableTracker.delete(key);
1300
+ }
1301
+ }
1302
+ ViewableEventTracker.viewableTracker = new Set();
1303
+
1304
+ /**
1305
+ * 베이스 광고 렌더러 - 공통 기능 구현
1306
+ */
1307
+ class BaseAdRenderer {
1308
+ constructor(adType, debug = false, advertisementEventTracker) {
1309
+ this.adType = adType;
1310
+ this.debug = debug;
1311
+ this.advertisementEventTracker = advertisementEventTracker || null;
1312
+ }
1313
+ /**
1314
+ * Placeholder(슬롯 컨테이너) 생성 - 공통 구현
1315
+ */
1316
+ createPlaceholder(container, slotId, options, config) {
1317
+ const adElement = document.createElement('div');
1318
+ adElement.id = slotId;
1319
+ adElement.className = `adstage-slot adstage-${String(this.adType).toLowerCase()}`;
1320
+ adElement.setAttribute('data-adstage-container', 'true');
1321
+ adElement.setAttribute('data-adstage-type', String(this.adType));
1322
+ adElement.setAttribute('data-adstage-slot', slotId);
1323
+ const { width, height } = this.calculateAdSize(container, options, config) || {
1324
+ width: '100%',
1325
+ height: this.getDefaultHeight()
1326
+ };
1327
+ adElement.style.width = width;
1328
+ adElement.style.height = height;
1329
+ // 플레이스홀더 스타일 모드 결정
1330
+ const placeholderMode = config?.placeholderMode || options.placeholderMode || 'invisible';
1331
+ this.applyPlaceholderStyle(adElement, placeholderMode);
1332
+ container.appendChild(adElement);
1333
+ if (this.debug) {
1334
+ console.log(`📦 Placeholder created for ${this.adType} slot: ${slotId} (${width} x ${height}) - Mode: ${placeholderMode}`);
1335
+ }
1336
+ }
1337
+ /**
1338
+ * 플레이스홀더 스타일 적용
1339
+ */
1340
+ applyPlaceholderStyle(element, mode) {
1341
+ switch (mode) {
1342
+ case 'invisible':
1343
+ // 완전히 투명한 플레이스홀더
1344
+ element.style.backgroundColor = 'transparent';
1345
+ element.style.border = 'none';
1346
+ element.style.opacity = '0';
1347
+ element.innerHTML = '';
1348
+ break;
1349
+ case 'transparent':
1350
+ // 투명하지만 공간은 차지
1351
+ element.style.backgroundColor = 'transparent';
1352
+ element.style.border = 'none';
1353
+ element.style.display = 'block';
1354
+ element.innerHTML = '';
1355
+ break;
1356
+ case 'subtle':
1357
+ // 매우 은은한 표시
1358
+ element.style.backgroundColor = 'rgba(0, 0, 0, 0.02)';
1359
+ element.style.border = 'none';
1360
+ element.style.borderRadius = '4px';
1361
+ element.style.display = 'flex';
1362
+ element.style.alignItems = 'center';
1363
+ element.style.justifyContent = 'center';
1364
+ element.innerHTML = '<span style="color: rgba(0, 0, 0, 0.3); font-size: 11px; font-family: sans-serif;">•••</span>';
1365
+ break;
1366
+ case 'minimal':
1367
+ // 최소한의 표시 (기본값)
1368
+ element.style.backgroundColor = 'rgba(248, 249, 250, 0.5)';
1369
+ element.style.border = '1px solid rgba(0, 0, 0, 0.08)';
1370
+ element.style.borderRadius = '6px';
1371
+ element.style.display = 'flex';
1372
+ element.style.alignItems = 'center';
1373
+ element.style.justifyContent = 'center';
1374
+ element.innerHTML = '<span style="color: rgba(0, 0, 0, 0.4); font-size: 12px; font-family: -apple-system, sans-serif;">•••</span>';
1375
+ break;
1376
+ case 'debug':
1377
+ // 개발/디버그용 명확한 표시
1378
+ element.style.border = '2px dashed #e74c3c';
1379
+ element.style.display = 'flex';
1380
+ element.style.alignItems = 'center';
1381
+ element.style.justifyContent = 'center';
1382
+ element.style.backgroundColor = 'rgba(231, 76, 60, 0.1)';
1383
+ element.style.color = '#e74c3c';
1384
+ element.style.fontFamily = 'monospace';
1385
+ element.style.fontSize = '11px';
1386
+ element.innerHTML = `<span>Loading ${this.adType} ad...</span>`;
1387
+ break;
1388
+ default:
1389
+ // 기존 스타일 (legacy)
1390
+ element.style.border = '1px dashed #ccc';
1391
+ element.style.display = 'flex';
1392
+ element.style.alignItems = 'center';
1393
+ element.style.justifyContent = 'center';
1394
+ element.style.backgroundColor = '#f9f9f9';
1395
+ element.style.color = '#666';
1396
+ element.innerHTML = `<span>Loading ${this.adType} ad...</span>`;
1397
+ }
1398
+ }
1399
+ /**
1400
+ * 광고 크기 계산 - 공통 구현
1401
+ */
1402
+ calculateAdSize(container, options, config) {
1403
+ // 사용자가 명시적으로 크기를 지정한 경우
1404
+ const explicitWidth = options.width;
1405
+ const explicitHeight = options.height;
1406
+ // 너비 처리
1407
+ let width;
1408
+ if (typeof explicitWidth === 'number') {
1409
+ width = `${explicitWidth}px`;
1410
+ }
1411
+ else if (typeof explicitWidth === 'string') {
1412
+ width = explicitWidth;
1413
+ }
1414
+ else {
1415
+ width = '100%'; // 기본값은 100%
1416
+ }
1417
+ // 높이 처리 - 핵심 로직
1418
+ let height;
1419
+ if (typeof explicitHeight === 'number') {
1420
+ height = `${explicitHeight}px`;
1421
+ }
1422
+ else if (typeof explicitHeight === 'string' && explicitHeight !== '100%' && explicitHeight !== 'auto') {
1423
+ // 명시적인 크기 문자열 (예: '200px', '50vh' 등)
1424
+ height = explicitHeight;
1425
+ }
1426
+ else {
1427
+ // 100%, auto이거나 높이가 지정되지 않은 경우 스마트 계산
1428
+ const containerHeight = this.getContainerHeight(container);
1429
+ if (containerHeight > 0) {
1430
+ // 컨테이너에 높이가 있으면 100% 사용
1431
+ height = '100%';
1432
+ if (config?.debug || this.debug) {
1433
+ console.log(`📏 Using 100% height (container: ${containerHeight}px)`);
1434
+ }
1435
+ }
1436
+ else {
1437
+ // 컨테이너에 높이가 없으면 타입별 기본값 사용
1438
+ height = this.getDefaultHeight();
1439
+ if (config?.debug || this.debug) {
1440
+ console.log(`📏 Using default height ${height} for ${this.adType}`);
1441
+ }
1442
+ }
1443
+ }
1444
+ return { width, height };
1445
+ }
1446
+ /**
1447
+ * 컨테이너의 실제 높이 계산 - 공통 구현
1448
+ */
1449
+ getContainerHeight(container) {
1450
+ const computedStyle = window.getComputedStyle(container);
1451
+ const height = parseFloat(computedStyle.height);
1452
+ if (!height || height === 0) {
1453
+ const minHeight = parseFloat(computedStyle.minHeight);
1454
+ if (minHeight > 0)
1455
+ return minHeight;
1456
+ if (container.style.height && container.style.height !== 'auto') {
1457
+ const styleHeight = parseFloat(container.style.height);
1458
+ if (styleHeight > 0)
1459
+ return styleHeight;
1460
+ }
1461
+ const heightAttr = container.getAttribute('height');
1462
+ if (heightAttr) {
1463
+ const attrHeight = parseFloat(heightAttr);
1464
+ if (attrHeight > 0)
1465
+ return attrHeight;
1466
+ }
1467
+ }
1468
+ return height || 0;
1469
+ }
1470
+ /**
1471
+ * 이벤트 트래킹 콜백 생성 - 공통 구현
1472
+ */
1473
+ createEventTrackingCallback() {
1474
+ return async (adId, slotId, eventType) => {
1475
+ if (eventType === AdEventType.VIEWABLE) {
1476
+ if (ViewableEventTracker.isDuplicateViewable(adId, slotId, this.debug)) {
1477
+ if (this.debug) {
1478
+ console.log(`🚫 Duplicate viewable blocked for ad ${adId} in slot ${slotId}`);
1479
+ }
1480
+ return;
1481
+ }
1482
+ if (this.debug) {
1483
+ console.log(`✅ New viewable recorded for ad ${adId} in slot ${slotId}`);
1484
+ }
1485
+ }
1486
+ if (this.advertisementEventTracker) {
1487
+ try {
1488
+ if (this.debug) {
1489
+ console.log(`🔄 Starting advertisement event tracking: ${eventType} for ad ${adId} in slot ${slotId}`);
1490
+ }
1491
+ await this.advertisementEventTracker.trackAdvertisementEvent(adId, slotId, eventType);
1492
+ if (this.debug) {
1493
+ console.log(`📊 Advertisement event tracked: ${eventType} for ad ${adId} in slot ${slotId}`);
1494
+ }
1495
+ }
1496
+ catch (error) {
1497
+ if (this.debug) {
1498
+ console.error(`❌ Failed to track ${eventType} event for ad ${adId}:`, error);
1499
+ }
1500
+ }
1501
+ }
1502
+ else {
1503
+ if (this.debug) {
1504
+ console.warn(`⚠️ AdvertisementEventTracker not available for ${eventType} event`);
1505
+ }
1506
+ }
1507
+ };
1508
+ }
1509
+ /**
1510
+ * Fallback 광고 렌더링 - 공통 구현
1511
+ */
1512
+ renderFallback(slot) {
1513
+ const element = document.getElementById(slot.id);
1514
+ if (element) {
1515
+ const adstageContainers = [
1516
+ element.querySelector('[data-adstage-container="true"]'),
1517
+ element.closest('[data-adstage-container="true"]'),
1518
+ element
1519
+ ].filter(el => el && el.hasAttribute('data-adstage-container'));
1520
+ const classBasedContainers = [
1521
+ element.closest('.adstage-slot'),
1522
+ element.closest(`.adstage-${String(this.adType).toLowerCase()}`),
1523
+ element.closest('[class*="ad"]'),
1524
+ element.closest('[class*="banner"]'),
1525
+ element.closest('[class*="container"]'),
1526
+ element.closest('div[style*="height"]'),
1527
+ element.closest('div[style*="min-height"]'),
1528
+ element.parentElement
1529
+ ].filter(Boolean);
1530
+ const possibleContainers = [...adstageContainers, ...classBasedContainers];
1531
+ const targetContainer = possibleContainers[0];
1532
+ if (targetContainer) {
1533
+ let containerType = 'unknown';
1534
+ if (targetContainer.hasAttribute('data-adstage-container')) {
1535
+ containerType = 'adstage-official';
1536
+ }
1537
+ else if (targetContainer.classList.contains('adstage-slot')) {
1538
+ containerType = 'adstage-class';
1539
+ }
1540
+ else {
1541
+ containerType = 'generic';
1542
+ }
1543
+ targetContainer.style.cssText += `
1544
+ height: 0px !important;
1545
+ min-height: 0px !important;
1546
+ padding: 0px !important;
1547
+ margin: 0px !important;
1548
+ border: none !important;
1549
+ overflow: hidden !important;
1550
+ display: block !important;
1551
+ `;
1552
+ targetContainer.innerHTML = '';
1553
+ targetContainer.setAttribute('data-adstage-empty', 'true');
1554
+ if (this.debug) {
1555
+ console.warn(`⚠️ ${this.adType} container collapsed (${containerType}): ${slot.id}`, targetContainer);
1556
+ }
1557
+ }
1558
+ else {
1559
+ this.createEmptyContainer(slot);
1560
+ }
1561
+ }
1562
+ slot.advertisement = undefined;
1563
+ slot.isEmpty = true;
1564
+ }
1565
+ /**
1566
+ * 빈 컨테이너 생성 - 공통 구현
1567
+ */
1568
+ createEmptyContainer(slot) {
1569
+ const originalContainer = document.getElementById(slot.containerId);
1570
+ if (originalContainer) {
1571
+ originalContainer.innerHTML = '';
1572
+ const emptyElement = document.createElement('div');
1573
+ emptyElement.id = slot.id;
1574
+ emptyElement.className = `adstage-slot adstage-empty adstage-${String(this.adType).toLowerCase()}`;
1575
+ emptyElement.setAttribute('data-adstage-container', 'true');
1576
+ emptyElement.setAttribute('data-adstage-empty', 'true');
1577
+ emptyElement.setAttribute('data-adstage-slot', slot.id);
1578
+ emptyElement.style.cssText = `
1579
+ height: 0px !important;
1580
+ min-height: 0px !important;
1581
+ padding: 0px !important;
1582
+ margin: 0px !important;
1583
+ border: none !important;
1584
+ overflow: hidden !important;
1585
+ display: block !important;
1586
+ `;
1587
+ originalContainer.appendChild(emptyElement);
1588
+ if (this.debug) {
1589
+ console.warn(`⚠️ Created empty ${this.adType} container: ${slot.id}`);
1590
+ }
1591
+ }
1592
+ }
1593
+ /**
1594
+ * 디버그 로그 출력 - 공통 구현
1595
+ */
1596
+ log(message, ...args) {
1597
+ if (this.debug) {
1598
+ console.log(`[${this.adType}] ${message}`, ...args);
1599
+ }
1600
+ }
1601
+ }
1602
+
1603
+ /**
1604
+ import { AdSlot, Advertisement, AdType } from '../../../types/advertisement';
1605
+ import { AdvertisementEventTracker } from '../../../managers/ads/advertisement-event-tracker';
1606
+ import { CarouselSliderManager } from '../../../managers/ads/carousel-slider-manager';
1607
+ import { BaseAdRenderer } from './base-ad-renderer';
1608
+ import { AdRenderOptions } from '../interfaces/i-ad-renderer'; 광고 전용 렌더러
1609
+ */
1610
+ class BannerAdRenderer extends BaseAdRenderer {
1611
+ constructor(debug = false, advertisementEventTracker) {
1612
+ super(AdType.BANNER, debug, advertisementEventTracker);
1613
+ }
1614
+ /**
1615
+ * 배너 광고 기본 높이
1616
+ */
1617
+ getDefaultHeight() {
1618
+ return '250px';
1619
+ }
1620
+ /**
1621
+ * 단일 배너 광고 렌더링
1622
+ */
1623
+ async renderAdElement(slot, advertisement) {
1624
+ const container = document.getElementById(slot.containerId);
1625
+ if (!container)
1626
+ return;
1627
+ const adElement = document.createElement('div');
1628
+ adElement.className = 'adstage-ad adstage-banner-ad';
1629
+ const optimizedHeight = slot.optimizedHeight;
1630
+ const containerElement = container.parentElement || container;
1631
+ if (optimizedHeight) {
1632
+ adElement.style.width = '100%';
1633
+ adElement.style.height = String(optimizedHeight);
1634
+ }
1635
+ else {
1636
+ const config = slot.config;
1637
+ const options = {
1638
+ width: config?.width,
1639
+ height: config?.height
1640
+ };
1641
+ const { width, height } = this.calculateAdSize(containerElement, options, { debug: this.debug });
1642
+ adElement.style.width = width;
1643
+ adElement.style.height = height;
1644
+ }
1645
+ if (advertisement.imageUrl) {
1646
+ await this.renderOptimizedBannerImage(adElement, advertisement, slot);
1647
+ }
1648
+ else {
1649
+ adElement.innerHTML = `<div>${advertisement.title || 'Banner Ad'}</div>`;
1650
+ }
1651
+ // 클릭 이벤트 추가 (공통 컴포넌트 사용)
1652
+ AdClickHandler.addClickEventForRenderer(adElement, advertisement, slot, () => this.createEventTrackingCallback(), this.debug, 'Banner');
1653
+ container.innerHTML = '';
1654
+ container.appendChild(adElement);
1655
+ }
1656
+ /**
1657
+ * 다중 배너 광고 렌더링 (슬라이더)
1658
+ */
1659
+ async renderMultipleAds(slot, advertisements) {
1660
+ const container = document.getElementById(slot.containerId);
1661
+ if (!container) {
1662
+ throw new Error(`Container not found: ${slot.containerId}`);
1663
+ }
1664
+ // 배너 광고를 위한 컨테이너 최적화
1665
+ await this.optimizeContainerForBannerAds(slot, advertisements);
1666
+ const trackEventCallback = this.createEventTrackingCallback();
1667
+ const optimizedSliderOptions = {
1668
+ autoSlideInterval: (slot.config?.slideInterval || 5000) / 1000,
1669
+ ...slot.config,
1670
+ optimizedHeight: slot.optimizedHeight,
1671
+ aspectRatio: slot.aspectRatio
1672
+ };
1673
+ const sliderElement = CarouselSliderManager.createSliderContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback, this.debug);
1674
+ if (sliderElement) {
1675
+ container.innerHTML = '';
1676
+ container.appendChild(sliderElement);
1677
+ if (this.debug) {
1678
+ console.log(`🎠 Banner carousel created for slot: ${slot.id} with ${advertisements.length} ads (optimized: ${slot.optimizedHeight || 'default'})`);
1679
+ }
1680
+ }
1681
+ }
1682
+ /**
1683
+ * 여러 광고의 최적 컨테이너 크기 계산
1684
+ */
1685
+ async calculateOptimalContainerSize(advertisements, containerWidth) {
1686
+ if (!advertisements.length) {
1687
+ return {
1688
+ width: '100%',
1689
+ height: this.getDefaultHeight(),
1690
+ aspectRatio: 16 / 9
1691
+ };
1692
+ }
1693
+ try {
1694
+ const imageDimensions = await Promise.allSettled(advertisements
1695
+ .filter(ad => ad.imageUrl)
1696
+ .map(ad => this.loadImageDimensions(ad.imageUrl)));
1697
+ const validDimensions = imageDimensions
1698
+ .filter((result) => result.status === 'fulfilled')
1699
+ .map(result => result.value);
1700
+ if (validDimensions.length === 0) {
1701
+ return {
1702
+ width: '100%',
1703
+ height: this.getDefaultHeight(),
1704
+ aspectRatio: 16 / 9
1705
+ };
1706
+ }
1707
+ const strategy = this.selectOptimalSizeStrategy(validDimensions);
1708
+ const optimalHeight = this.calculateOptimalHeight(validDimensions, containerWidth, strategy);
1709
+ if (this.debug) {
1710
+ console.log(`📐 Optimal banner container calculated: ${containerWidth}x${optimalHeight} (strategy: ${strategy})`);
1711
+ }
1712
+ return {
1713
+ width: '100%',
1714
+ height: `${optimalHeight}px`,
1715
+ aspectRatio: containerWidth / optimalHeight
1716
+ };
1717
+ }
1718
+ catch (error) {
1719
+ console.warn('Failed to calculate optimal banner size, using defaults:', error);
1720
+ return {
1721
+ width: '100%',
1722
+ height: this.getDefaultHeight(),
1723
+ aspectRatio: 16 / 9
1724
+ };
1725
+ }
1726
+ }
1727
+ /**
1728
+ * 배너 광고를 위한 컨테이너 최적화
1729
+ */
1730
+ async optimizeContainerForBannerAds(slot, advertisements) {
1731
+ try {
1732
+ const container = document.getElementById(slot.containerId);
1733
+ const adElement = document.getElementById(slot.id);
1734
+ if (!container || !adElement)
1735
+ return;
1736
+ const containerWidth = container.getBoundingClientRect().width || 300;
1737
+ const optimalSize = await this.calculateOptimalContainerSize(advertisements, containerWidth);
1738
+ adElement.style.height = optimalSize.height;
1739
+ slot.optimizedHeight = optimalSize.height;
1740
+ slot.aspectRatio = optimalSize.aspectRatio;
1741
+ if (this.debug) {
1742
+ console.log(`🔧 Banner container optimized for ${advertisements.length} ads: ${optimalSize.height}`);
1743
+ }
1744
+ }
1745
+ catch (error) {
1746
+ console.warn('Banner container optimization failed, using default size:', error);
1747
+ }
1748
+ }
1749
+ /**
1750
+ * 최적 크기 조정 전략 선택
1751
+ */
1752
+ selectOptimalSizeStrategy(dimensions) {
1753
+ const aspectRatios = dimensions.map(d => d.width / d.height);
1754
+ const ratioGroups = new Map();
1755
+ aspectRatios.forEach(ratio => {
1756
+ const roundedRatio = Math.round(ratio * 10) / 10;
1757
+ const key = roundedRatio.toString();
1758
+ ratioGroups.set(key, (ratioGroups.get(key) || 0) + 1);
1759
+ });
1760
+ const maxGroup = Math.max(...ratioGroups.values());
1761
+ const totalImages = dimensions.length;
1762
+ if (maxGroup / totalImages >= 0.7) {
1763
+ return 'dominant';
1764
+ }
1765
+ const standardRatios = [16 / 9, 4 / 3, 1 / 1, 3 / 2];
1766
+ const standardCount = aspectRatios.filter(ratio => standardRatios.some(standard => Math.abs(ratio - standard) < 0.1)).length;
1767
+ if (standardCount / totalImages >= 0.5) {
1768
+ return 'common';
1769
+ }
1770
+ return 'average';
1771
+ }
1772
+ /**
1773
+ * 전략에 따른 최적 높이 계산
1774
+ */
1775
+ calculateOptimalHeight(dimensions, containerWidth, strategy) {
1776
+ const aspectRatios = dimensions.map(d => d.width / d.height);
1777
+ switch (strategy) {
1778
+ case 'dominant': {
1779
+ const ratioGroups = new Map();
1780
+ aspectRatios.forEach(ratio => {
1781
+ const roundedRatio = Math.round(ratio * 10) / 10;
1782
+ const key = roundedRatio.toString();
1783
+ const existing = ratioGroups.get(key);
1784
+ if (existing) {
1785
+ existing.count++;
1786
+ }
1787
+ else {
1788
+ ratioGroups.set(key, { ratio: roundedRatio, count: 1 });
1789
+ }
1790
+ });
1791
+ const dominantGroup = Array.from(ratioGroups.values()).reduce((max, current) => current.count > max.count ? current : max);
1792
+ return Math.round(containerWidth / dominantGroup.ratio);
1793
+ }
1794
+ case 'common': {
1795
+ const standardRatios = [
1796
+ { ratio: 16 / 9, name: '16:9' },
1797
+ { ratio: 4 / 3, name: '4:3' },
1798
+ { ratio: 1 / 1, name: '1:1' },
1799
+ { ratio: 3 / 2, name: '3:2' }
1800
+ ];
1801
+ const avgRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
1802
+ const bestStandard = standardRatios.reduce((best, current) => Math.abs(current.ratio - avgRatio) < Math.abs(best.ratio - avgRatio) ? current : best);
1803
+ if (this.debug) {
1804
+ console.log(`📊 Using standard ratio: ${bestStandard.name} (avg: ${avgRatio.toFixed(2)})`);
1805
+ }
1806
+ return Math.round(containerWidth / bestStandard.ratio);
1807
+ }
1808
+ case 'average':
1809
+ default: {
1810
+ const averageRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
1811
+ return Math.round(containerWidth / averageRatio);
1812
+ }
1813
+ }
1814
+ }
1815
+ /**
1816
+ * 이미지 로드 및 실제 크기 획득
1817
+ */
1818
+ loadImageDimensions(imageUrl) {
1819
+ return new Promise((resolve, reject) => {
1820
+ const img = new Image();
1821
+ img.onload = () => {
1822
+ resolve({ width: img.naturalWidth, height: img.naturalHeight });
1823
+ };
1824
+ img.onerror = () => {
1825
+ reject(new Error(`Failed to load image: ${imageUrl}`));
1826
+ };
1827
+ img.src = imageUrl;
1828
+ });
1829
+ }
1830
+ /**
1831
+ * 이미지와 컨테이너 비율을 고려한 최적화 스타일 적용
1832
+ */
1833
+ applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio) {
1834
+ const ratio = imageAspectRatio / containerAspectRatio;
1835
+ if (Math.abs(ratio - 1) < 0.1) {
1836
+ img.style.objectFit = 'cover';
1837
+ img.style.objectPosition = 'center';
1838
+ }
1839
+ else if (ratio > 1.3) {
1840
+ img.style.objectFit = 'contain';
1841
+ img.style.objectPosition = 'center';
1842
+ img.style.backgroundColor = '#f0f0f0';
1843
+ }
1844
+ else if (ratio < 0.7) {
1845
+ img.style.objectFit = 'cover';
1846
+ img.style.objectPosition = 'center';
1847
+ }
1848
+ else {
1849
+ img.style.objectFit = 'cover';
1850
+ img.style.objectPosition = 'center';
1851
+ }
1852
+ if (this.debug) {
1853
+ console.log(`🎨 Banner image style applied: objectFit=${img.style.objectFit}, ratio=${ratio.toFixed(2)}`);
1854
+ }
1855
+ }
1856
+ /**
1857
+ * 배너 이미지 최적화 렌더링 - public으로 변경
1858
+ */
1859
+ async renderOptimizedBannerImage(container, advertisement, slot) {
1860
+ const img = document.createElement('img');
1861
+ img.style.width = '100%';
1862
+ img.style.height = '100%';
1863
+ img.style.display = 'block';
1864
+ img.style.borderRadius = '8px';
1865
+ img.alt = advertisement.title || 'Banner Advertisement';
1866
+ container.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 100%; color: #999;">Loading...</div>';
1867
+ try {
1868
+ if (!advertisement.imageUrl) {
1869
+ throw new Error('Image URL is not provided');
1870
+ }
1871
+ const imageDimensions = await this.loadImageDimensions(advertisement.imageUrl);
1872
+ const containerRect = container.getBoundingClientRect();
1873
+ const containerWidth = containerRect.width;
1874
+ const containerHeight = containerRect.height;
1875
+ if (this.debug) {
1876
+ console.log(`📸 Banner image dimensions: ${imageDimensions.width}x${imageDimensions.height}`);
1877
+ console.log(`📦 Banner container dimensions: ${containerWidth}x${containerHeight}`);
1878
+ }
1879
+ const imageAspectRatio = imageDimensions.width / imageDimensions.height;
1880
+ const containerAspectRatio = containerWidth / containerHeight;
1881
+ this.applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio);
1882
+ img.src = advertisement.imageUrl;
1883
+ container.innerHTML = '';
1884
+ container.appendChild(img);
1885
+ // 클릭 이벤트 추가 (공통 컴포넌트 사용)
1886
+ AdClickHandler.addClickEventForRenderer(img, advertisement, slot, () => this.createEventTrackingCallback(), this.debug, 'Banner');
1887
+ if (this.debug) {
1888
+ console.log(`✅ Optimized banner image rendered for ad: ${advertisement._id}`);
1889
+ }
1890
+ return img;
1891
+ }
1892
+ catch (error) {
1893
+ console.error('❌ Failed to load optimized banner image:', error);
1894
+ if (advertisement.imageUrl) {
1895
+ img.src = advertisement.imageUrl;
1896
+ img.style.objectFit = 'cover';
1897
+ img.style.objectPosition = 'center';
1898
+ container.innerHTML = '';
1899
+ container.appendChild(img);
1900
+ // 클릭 이벤트 추가 (공통 컴포넌트 사용)
1901
+ AdClickHandler.addClickEventForRenderer(img, advertisement, slot, () => this.createEventTrackingCallback(), this.debug, 'Banner');
1902
+ }
1903
+ return img;
1904
+ }
1905
+ }
1906
+ }
1907
+
1908
+ /**
1909
+ * 텍스트 광고 공통 유틸리티 함수들
1910
+ */
1911
+ class TextAdUtils {
1912
+ /**
1913
+ * 텍스트 광고의 기본 스타일을 생성
1914
+ * @param isSimple 간단한 스타일 여부
1915
+ * @returns CSS 스타일 문자열
1916
+ */
1917
+ static createTextAdStyles(isSimple = false) {
1918
+ const baseStyles = `
1919
+ font-family: 'Arial', sans-serif;
1920
+ text-decoration: none;
1921
+ display: block;
1922
+ text-align: left;
1923
+ transition: color 0.3s ease;
1924
+ width: 100%;
1925
+ box-sizing: border-box;
1926
+ overflow: visible;
1927
+ padding-right: 2px;
1928
+ padding-left: 2px;
1929
+ white-space: nowrap;
1930
+ `;
1931
+ return baseStyles;
1932
+ }
1933
+ /**
1934
+ * 텍스트 광고의 콘텐츠를 설정 (textContent 우선, 없으면 title)
1935
+ * @param element 설정할 HTML 요소
1936
+ * @param adData 광고 데이터
1937
+ */
1938
+ static setTextAdContent(element, adData) {
1939
+ const content = adData.textContent || adData.title || '';
1940
+ element.textContent = content;
1941
+ }
1942
+ }
1943
+
1944
+ /**
1945
+ * 텍스트 전환 효과 관리 클래스
1946
+ * - 텍스트 광고 전용 페이드 인/아웃 + 상하 움직임 효과
1947
+ * - 부드러운 전환 애니메이션 (vertical transition)
1948
+ * - 무한 루프 지원
1949
+ */
1950
+ class TextTransitionManager {
1951
+ /**
1952
+ * 간단한 광고 요소 생성 (크기 측정용)
1953
+ */
1954
+ static createSimpleAdElement(slot, advertisement) {
1955
+ const adElement = document.createElement('div');
1956
+ adElement.className = `adstage-ad adstage-${String(slot.adType).toLowerCase()}`;
1957
+ adElement.setAttribute('data-adstage-ad-id', advertisement._id);
1958
+ adElement.setAttribute('data-adstage-slot-id', slot.id);
1959
+ // 🎯 공통 스타일 및 콘텐츠 적용 (중복 제거)
1960
+ adElement.style.cssText = TextAdUtils.createTextAdStyles(true);
1961
+ TextAdUtils.setTextAdContent(adElement, advertisement);
1962
+ return adElement;
1963
+ }
1964
+ /**
1965
+ * 텍스트 전환 컨테이너 생성
1966
+ */
1967
+ static createTextTransitionContainer(slot, advertisements, options, trackEventCallback, debug = false) {
1968
+ // 사용자가 높이를 지정했는지 미리 확인 ('auto'나 undefined면 자동 높이)
1969
+ const hasUserDefinedHeight = slot.height && slot.height !== 0 && slot.height !== 'auto';
1970
+ const sliderWrapper = document.createElement('div');
1971
+ sliderWrapper.className = 'adstage-fade-slider-wrapper';
1972
+ // 래퍼 스타일 설정
1973
+ const containerStyles = {
1974
+ position: 'relative',
1975
+ overflow: 'hidden',
1976
+ display: 'block',
1977
+ };
1978
+ // 높이가 지정되지 않은 경우 자동 높이 사용
1979
+ if (!hasUserDefinedHeight) {
1980
+ containerStyles.height = 'auto';
1981
+ containerStyles.minHeight = 'fit-content';
1982
+ }
1983
+ // 사용자가 크기를 지정한 경우
1984
+ if (slot.width && slot.width !== 0) {
1985
+ let width;
1986
+ if (typeof slot.width === 'string') {
1987
+ width = slot.width.includes('px') || slot.width.includes('%') ? slot.width : `${slot.width}px`;
1988
+ }
1989
+ else {
1990
+ width = `${slot.width}px`;
1991
+ }
1992
+ containerStyles.width = width;
1993
+ }
1994
+ // 사용자가 높이를 명시적으로 지정한 경우에만 적용 ('auto'는 제외)
1995
+ if (slot.height && slot.height !== 0 && slot.height !== 'auto' && hasUserDefinedHeight) {
1996
+ let height;
1997
+ if (typeof slot.height === 'string') {
1998
+ height = slot.height.includes('px') || slot.height.includes('%') ? slot.height : `${slot.height}px`;
1999
+ }
2000
+ else {
2001
+ height = `${slot.height}px`;
2002
+ }
2003
+ containerStyles.height = height;
2004
+ }
2005
+ // 스타일 적용
2006
+ Object.entries(containerStyles).forEach(([key, value]) => {
2007
+ sliderWrapper.style.setProperty(key, value);
1575
2008
  });
1576
2009
  // 슬라이드 컨테이너
1577
2010
  const slideContainer = document.createElement('div');
@@ -1579,13 +2012,14 @@ class TextTransitionManager {
1579
2012
  slideContainer.style.cssText = `
1580
2013
  position: relative;
1581
2014
  width: 100%;
1582
- height: 100%;
2015
+ ${hasUserDefinedHeight ? 'height: 100%;' : 'height: auto; min-height: fit-content;'}
1583
2016
  `;
1584
2017
  // 크기 측정을 위한 임시 컨테이너 (자동 크기 계산이 필요한 경우)
1585
2018
  let measureContainer = null;
1586
2019
  const needsWidthMeasurement = !slot.width || slot.width === 0;
1587
- const needsHeightMeasurement = !slot.height || slot.height === 0;
1588
- if (needsWidthMeasurement || needsHeightMeasurement) {
2020
+ const needsHeightMeasurement = !slot.height || slot.height === 0 || slot.height === undefined || slot.height === 'auto';
2021
+ // 너비 측정만 필요한 경우 (높이는 자동으로 유지)
2022
+ if (needsWidthMeasurement || (needsHeightMeasurement && hasUserDefinedHeight)) {
1589
2023
  measureContainer = document.createElement('div');
1590
2024
  measureContainer.style.cssText = `
1591
2025
  position: absolute;
@@ -1611,7 +2045,7 @@ class TextTransitionManager {
1611
2045
  let maxHeight = 0;
1612
2046
  // 모든 광고의 크기를 측정하여 최대 크기 찾기
1613
2047
  advertisements.forEach(ad => {
1614
- const measureAdElement = AdRendererFactory.render(ad, slot, trackEventCallback);
2048
+ const measureAdElement = this.createSimpleAdElement(slot, ad);
1615
2049
  measureContainer.appendChild(measureAdElement);
1616
2050
  const rect = measureAdElement.getBoundingClientRect();
1617
2051
  if (rect.width > maxWidth)
@@ -1625,7 +2059,8 @@ class TextTransitionManager {
1625
2059
  if (needsWidthMeasurement && maxWidth > 0) {
1626
2060
  sliderWrapper.style.width = `${maxWidth}px`;
1627
2061
  }
1628
- if (needsHeightMeasurement && maxHeight > 0) {
2062
+ // 사용자가 높이를 지정하지 않은 경우 auto 높이 유지 (측정된 높이 적용하지 않음)
2063
+ if (needsHeightMeasurement && maxHeight > 0 && hasUserDefinedHeight) {
1629
2064
  sliderWrapper.style.height = `${maxHeight}px`;
1630
2065
  }
1631
2066
  // 측정 컨테이너 제거
@@ -1636,22 +2071,27 @@ class TextTransitionManager {
1636
2071
  advertisements.forEach((ad, index) => {
1637
2072
  const slideElement = document.createElement('div');
1638
2073
  slideElement.className = 'adstage-fade-slide';
2074
+ // 자동 높이일 때는 첫 번째 슬라이드만 relative로 높이 확보
2075
+ const isFirstSlide = index === 0;
2076
+ const positionStyle = hasUserDefinedHeight ? 'absolute' : (isFirstSlide ? 'relative' : 'absolute');
1639
2077
  slideElement.style.cssText = `
1640
- position: absolute;
1641
- top: 0;
1642
- left: 0;
2078
+ position: ${positionStyle};
2079
+ top: ${positionStyle === 'absolute' ? '0' : 'auto'};
2080
+ left: ${positionStyle === 'absolute' ? '0' : 'auto'};
1643
2081
  width: 100%;
1644
- height: 100%;
2082
+ ${hasUserDefinedHeight ? 'height: 100%;' : 'height: auto;'}
1645
2083
  display: flex;
1646
2084
  align-items: center;
1647
- justify-content: center;
2085
+ justify-content: flex-start;
1648
2086
  opacity: ${index === 0 ? '1' : '0'};
1649
2087
  transform: translateY(${index === 0 ? '0' : '20px'});
1650
2088
  transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
1651
2089
  z-index: ${index === 0 ? '2' : '1'};
1652
2090
  `;
1653
- // 광고 렌더링
1654
- const adElement = AdRendererFactory.render(ad, slot, trackEventCallback);
2091
+ // 광고 렌더링 - 공통 함수 사용으로 일관성 유지
2092
+ const adElement = this.createSimpleAdElement(slot, ad);
2093
+ // 클릭 이벤트 추가 (공통 컴포넌트 사용)
2094
+ AdClickHandler.addClickEventForSlider(adElement, ad, slot, trackEventCallback, debug, 'Text');
1655
2095
  slideElement.appendChild(adElement);
1656
2096
  slideContainer.appendChild(slideElement);
1657
2097
  slideElements.push(slideElement);
@@ -1670,6 +2110,19 @@ class TextTransitionManager {
1670
2110
  }
1671
2111
  const previousSlide = slideElements[currentSlide];
1672
2112
  const nextSlide = slideElements[index];
2113
+ // 자동 높이 모드일 때는 위치 변경
2114
+ if (!hasUserDefinedHeight) {
2115
+ // 이전 슬라이드를 absolute로 변경
2116
+ if (previousSlide.style.position === 'relative') {
2117
+ previousSlide.style.position = 'absolute';
2118
+ previousSlide.style.top = '0';
2119
+ previousSlide.style.left = '0';
2120
+ }
2121
+ // 다음 슬라이드를 relative로 변경하여 높이 확보
2122
+ nextSlide.style.position = 'relative';
2123
+ nextSlide.style.top = 'auto';
2124
+ nextSlide.style.left = 'auto';
2125
+ }
1673
2126
  // 이전 슬라이드 페이드 아웃 (아래로)
1674
2127
  previousSlide.style.opacity = '0';
1675
2128
  previousSlide.style.transform = 'translateY(-20px)';
@@ -1684,13 +2137,18 @@ class TextTransitionManager {
1684
2137
  slide.style.opacity = '0';
1685
2138
  slide.style.transform = 'translateY(20px)';
1686
2139
  slide.style.zIndex = '1';
2140
+ // 자동 높이 모드일 때는 다른 슬라이드들을 absolute로
2141
+ if (!hasUserDefinedHeight && slide.style.position === 'relative') {
2142
+ slide.style.position = 'absolute';
2143
+ slide.style.top = '0';
2144
+ slide.style.left = '0';
2145
+ }
1687
2146
  }
1688
2147
  });
1689
2148
  currentSlide = index;
1690
- // 현재 슬라이드의 광고에 대해 노출 이벤트 추적
1691
- if (currentSlide > 0) { // 번째는 이미 loadSlot에서 추적됨
1692
- trackEventCallback(advertisements[currentSlide]._id, slot.id, AdEventType.VIEWABLE);
1693
- }
2149
+ // 🎯 공통 슬라이더 이벤트 추적 적용 (모든 슬라이드 포함)
2150
+ SliderEventTracker.trackSlideViewable(advertisements[currentSlide], slot, currentSlide, trackEventCallback, debug // debug 모드 상속
2151
+ );
1694
2152
  };
1695
2153
  // 자동 슬라이드
1696
2154
  let autoSlideTimer = setInterval(() => {
@@ -1755,496 +2213,975 @@ class TextTransitionManager {
1755
2213
  }
1756
2214
 
1757
2215
  /**
1758
- * AdRenderer - 광고 렌더링 전용 클래스
1759
- * AdsModule에서 렌더링 관련 기능을 분리
2216
+ * 텍스트 광고 전용 렌더러
1760
2217
  */
1761
- class AdRenderer {
2218
+ class TextAdRenderer extends BaseAdRenderer {
1762
2219
  constructor(debug = false, advertisementEventTracker) {
1763
- this.debug = debug;
1764
- this.advertisementEventTracker = advertisementEventTracker || null;
2220
+ super(AdType.TEXT, debug, advertisementEventTracker);
1765
2221
  }
1766
2222
  /**
1767
- * Placeholder(슬롯 컨테이너) 생성
2223
+ * 텍스트 광고 기본 높이
2224
+ */
2225
+ getDefaultHeight() {
2226
+ return '60px';
2227
+ }
2228
+ /**
2229
+ * 단일 텍스트 광고 렌더링
1768
2230
  */
1769
- createPlaceholder(container, slotId, type, options, _config) {
2231
+ async renderAdElement(slot, advertisement) {
2232
+ const container = document.getElementById(slot.containerId);
2233
+ if (!container)
2234
+ return;
1770
2235
  const adElement = document.createElement('div');
1771
- adElement.id = slotId;
1772
- adElement.className = `adstage-slot adstage-${String(type).toLowerCase()}`;
1773
- adElement.setAttribute('data-adstage-container', 'true');
1774
- adElement.setAttribute('data-adstage-type', String(type));
1775
- adElement.setAttribute('data-adstage-slot', slotId);
1776
- const { width, height } = this.calculateAdSize(container, type, options, _config) || {
1777
- width: '100%',
1778
- height: '250px'
1779
- };
1780
- adElement.style.width = width;
1781
- adElement.style.height = height;
1782
- adElement.style.border = '1px dashed #ccc';
1783
- adElement.style.display = 'flex';
1784
- adElement.style.alignItems = 'center';
1785
- adElement.style.justifyContent = 'center';
1786
- adElement.style.backgroundColor = '#f9f9f9';
1787
- adElement.style.color = '#666';
1788
- adElement.innerHTML = `<span>Loading ${type} ad...</span>`;
2236
+ adElement.className = 'adstage-ad adstage-text-ad';
2237
+ const optimizedHeight = slot.optimizedHeight;
2238
+ const containerElement = container.parentElement || container;
2239
+ if (optimizedHeight) {
2240
+ adElement.style.width = '100%';
2241
+ adElement.style.height = String(optimizedHeight);
2242
+ }
2243
+ else {
2244
+ const config = slot.config;
2245
+ const options = {
2246
+ width: config?.width,
2247
+ height: config?.height
2248
+ };
2249
+ const { width, height } = this.calculateAdSize(containerElement, options, { debug: this.debug });
2250
+ adElement.style.width = width;
2251
+ adElement.style.height = height;
2252
+ }
2253
+ // 텍스트 콘텐츠 렌더링
2254
+ const textDiv = document.createElement('div');
2255
+ textDiv.className = 'adstage-text-content';
2256
+ textDiv.style.cssText = TextAdUtils.createTextAdStyles(false);
2257
+ TextAdUtils.setTextAdContent(textDiv, advertisement); // 최대 라인 수 제한
2258
+ const maxLines = slot.config?.maxLines;
2259
+ if (maxLines && typeof maxLines === 'number') {
2260
+ textDiv.style.display = '-webkit-box';
2261
+ textDiv.style.webkitLineClamp = String(maxLines);
2262
+ textDiv.style.webkitBoxOrient = 'vertical';
2263
+ textDiv.style.overflow = 'hidden';
2264
+ }
2265
+ adElement.appendChild(textDiv);
2266
+ // 클릭 이벤트 추가 (공통 컴포넌트 사용)
2267
+ AdClickHandler.addClickEventForRenderer(adElement, advertisement, slot, () => this.createEventTrackingCallback(), this.debug, 'Text');
2268
+ container.innerHTML = '';
1789
2269
  container.appendChild(adElement);
1790
2270
  if (this.debug) {
1791
- console.log(`📦 Placeholder created for slot: ${slotId} (${width} x ${height})`);
2271
+ console.log(`✨ Single text ad rendered: ${advertisement._id}`);
1792
2272
  }
1793
2273
  }
1794
2274
  /**
1795
- * 여러 광고의 최적 컨테이너 크기 계산 (동적 크기 조정)
2275
+ * 다중 텍스트 광고 렌더링 (전환 효과)
1796
2276
  */
1797
- async calculateOptimalContainerSize(advertisements, containerWidth, adType) {
1798
- if (!advertisements.length || adType !== AdType.BANNER) {
1799
- return {
1800
- width: '100%',
1801
- height: this.getDefaultHeightForAdType(adType) || '250px',
1802
- aspectRatio: 16 / 9
1803
- };
2277
+ async renderMultipleAds(slot, advertisements) {
2278
+ const container = document.getElementById(slot.containerId);
2279
+ if (!container) {
2280
+ throw new Error(`Container not found: ${slot.containerId}`);
1804
2281
  }
1805
- try {
1806
- const imageDimensions = await Promise.allSettled(advertisements
1807
- .filter(ad => ad.imageUrl)
1808
- .map(ad => this.loadImageDimensions(ad.imageUrl)));
1809
- const validDimensions = imageDimensions
1810
- .filter((result) => result.status === 'fulfilled')
1811
- .map(result => result.value);
1812
- if (validDimensions.length === 0) {
1813
- return {
1814
- width: '100%',
1815
- height: this.getDefaultHeightForAdType(adType) || '250px',
1816
- aspectRatio: 16 / 9
1817
- };
2282
+ const trackEventCallback = this.createEventTrackingCallback();
2283
+ const optimizedSliderOptions = {
2284
+ autoSlideInterval: (slot.config?.slideInterval || 5000) / 1000,
2285
+ ...slot.config,
2286
+ optimizedHeight: slot.optimizedHeight,
2287
+ aspectRatio: slot.aspectRatio
2288
+ };
2289
+ const sliderElement = TextTransitionManager.createTextTransitionContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback, this.debug);
2290
+ if (sliderElement) {
2291
+ container.innerHTML = '';
2292
+ container.appendChild(sliderElement);
2293
+ if (this.debug) {
2294
+ console.log(`✨ Text transition created for slot: ${slot.id} with ${advertisements.length} ads`);
1818
2295
  }
1819
- const strategy = this.selectOptimalSizeStrategy(validDimensions);
1820
- const optimalHeight = this.calculateOptimalHeight(validDimensions, containerWidth, strategy);
2296
+ }
2297
+ }
2298
+ }
2299
+
2300
+ /**
2301
+ * 비디오 광고 전용 렌더러
2302
+ */
2303
+ class VideoAdRenderer extends BaseAdRenderer {
2304
+ constructor(debug = false, advertisementEventTracker) {
2305
+ super(AdType.VIDEO, debug, advertisementEventTracker);
2306
+ }
2307
+ /**
2308
+ * 비디오 광고 기본 높이 (16:9 비율 고려)
2309
+ */
2310
+ getDefaultHeight() {
2311
+ return '360px';
2312
+ }
2313
+ /**
2314
+ * 단일 비디오 광고 렌더링
2315
+ */
2316
+ async renderAdElement(slot, advertisement) {
2317
+ const container = document.getElementById(slot.containerId);
2318
+ if (!container)
2319
+ return;
2320
+ // 비디오 전용 컨테이너 생성
2321
+ const videoContainer = document.createElement('div');
2322
+ videoContainer.className = 'adstage-video-container';
2323
+ videoContainer.style.cssText = `
2324
+ width: 100%;
2325
+ height: 100%;
2326
+ display: flex;
2327
+ align-items: center;
2328
+ justify-content: center;
2329
+ background: #000;
2330
+ border-radius: 8px;
2331
+ overflow: hidden;
2332
+ `;
2333
+ // 비디오 요소 렌더링
2334
+ this.renderVideoElementDirect(videoContainer, advertisement, slot);
2335
+ container.innerHTML = '';
2336
+ container.appendChild(videoContainer);
2337
+ if (this.debug) {
2338
+ console.log(`🎬 Single video ad rendered: ${advertisement._id}`);
2339
+ }
2340
+ }
2341
+ /**
2342
+ * 다중 비디오 광고 렌더링 - 비디오는 단일 렌더링만 지원
2343
+ */
2344
+ async renderMultipleAds(slot, advertisements) {
2345
+ const container = document.getElementById(slot.containerId);
2346
+ if (!container) {
2347
+ throw new Error(`Container not found: ${slot.containerId}`);
2348
+ }
2349
+ if (advertisements.length > 0) {
2350
+ const videoAd = advertisements[0]; // 첫 번째 비디오만 사용
2351
+ // 비디오 전용 컨테이너 생성
2352
+ const videoContainer = document.createElement('div');
2353
+ videoContainer.className = 'adstage-video-container';
2354
+ videoContainer.style.cssText = `
2355
+ width: 100%;
2356
+ height: 100%;
2357
+ display: flex;
2358
+ align-items: center;
2359
+ justify-content: center;
2360
+ background: #000;
2361
+ border-radius: 8px;
2362
+ overflow: hidden;
2363
+ `;
2364
+ // 비디오 요소 렌더링
2365
+ this.renderVideoElementDirect(videoContainer, videoAd, slot);
2366
+ // 컨테이너에 추가
2367
+ container.innerHTML = '';
2368
+ container.appendChild(videoContainer);
2369
+ // VIEWABLE 이벤트 추적
2370
+ const trackEventCallback = this.createEventTrackingCallback();
2371
+ setTimeout(() => {
2372
+ trackEventCallback(videoAd._id, slot.id, AdEventType.VIEWABLE);
2373
+ }, 100);
1821
2374
  if (this.debug) {
1822
- console.log(`📐 Optimal container calculated: ${containerWidth}x${optimalHeight} (strategy: ${strategy})`);
2375
+ console.log(`🎬 Single video rendered for VIDEO slot: ${slot.id} (${videoAd._id})`);
1823
2376
  }
1824
- return {
1825
- width: '100%',
1826
- height: `${optimalHeight}px`,
1827
- aspectRatio: containerWidth / optimalHeight
1828
- };
1829
2377
  }
1830
- catch (error) {
1831
- console.warn('Failed to calculate optimal size, using defaults:', error);
1832
- return {
1833
- width: '100%',
1834
- height: this.getDefaultHeightForAdType(adType) || '250px',
1835
- aspectRatio: 16 / 9
1836
- };
2378
+ else {
2379
+ if (this.debug) {
2380
+ console.warn(`⚠️ No video advertisements available for slot: ${slot.id}`);
2381
+ }
1837
2382
  }
1838
2383
  }
1839
2384
  /**
1840
- * 최적 크기 조정 전략 선택
2385
+ * 비디오 요소 직접 렌더링
1841
2386
  */
1842
- selectOptimalSizeStrategy(dimensions) {
1843
- const aspectRatios = dimensions.map(d => d.width / d.height);
1844
- const ratioGroups = new Map();
1845
- aspectRatios.forEach(ratio => {
1846
- const roundedRatio = Math.round(ratio * 10) / 10;
1847
- const key = roundedRatio.toString();
1848
- ratioGroups.set(key, (ratioGroups.get(key) || 0) + 1);
2387
+ renderVideoElementDirect(container, advertisement, slot) {
2388
+ // 비디오 컨테이너를 relative로 설정
2389
+ container.style.position = 'relative';
2390
+ const video = document.createElement('video');
2391
+ // 비디오 기본 설정
2392
+ video.style.width = '100%';
2393
+ video.style.height = '100%';
2394
+ video.style.objectFit = 'contain';
2395
+ video.preload = 'metadata';
2396
+ // 슬롯 설정에서 비디오 옵션들 확인 (기본값 적용)
2397
+ const config = slot.config;
2398
+ // 디버깅: config 내용 확인
2399
+ if (this.debug) {
2400
+ console.log('🎬 Video config received:', config);
2401
+ }
2402
+ // 기본 설정: 모든 컨트롤 숨김 (사용자 요구사항 - config에 상관없이 기본값 적용)
2403
+ video.controls = false;
2404
+ // 기본 설정: 자동 재생 true (config에 상관없이 기본값 적용, 단 사용자가 명시적으로 false 설정시 존중)
2405
+ video.autoplay = config?.autoplay === false ? false : true;
2406
+ // 기본 설정: 음소거 true (기본값 강제 적용)
2407
+ video.muted = true;
2408
+ // 기본 설정: 반복 재생 true (config에 상관없이 기본값 적용, 단 사용자가 명시적으로 false 설정시 존중)
2409
+ video.loop = config?.loop === false ? false : true;
2410
+ // 디버깅: 최종 비디오 설정 확인
2411
+ if (this.debug) {
2412
+ console.log('🎬 Final video settings:', {
2413
+ autoplay: video.autoplay,
2414
+ muted: video.muted,
2415
+ loop: video.loop,
2416
+ controls: video.controls
2417
+ });
2418
+ }
2419
+ // playsinline 설정 (모바일에서 전체화면 방지)
2420
+ if (config?.playsinline !== false) {
2421
+ video.setAttribute('playsinline', '');
2422
+ }
2423
+ // 사용자가 명시적으로 controls=true를 설정한 경우에만 오버라이드 (첫 번째 비디오는 기본값 유지)
2424
+ if (config?.controls === true) {
2425
+ video.controls = true;
2426
+ if (this.debug) {
2427
+ console.log('🎬 User explicitly enabled controls, overriding default');
2428
+ }
2429
+ }
2430
+ // 특별한 컨트롤 설정 처리
2431
+ if (config?.hideControls) {
2432
+ // 완전히 모든 컨트롤 숨김 (pointer-events까지 차단)
2433
+ video.controls = false;
2434
+ video.style.cssText += `
2435
+ pointer-events: none;
2436
+ `;
2437
+ }
2438
+ else if (config?.customControls) {
2439
+ // controls가 true일 때만 특정 컨트롤 숨기기 (CSS로 처리)
2440
+ if (video.controls) {
2441
+ const customControlsStyle = document.createElement('style');
2442
+ customControlsStyle.textContent = `
2443
+ video::-webkit-media-controls-play-button {
2444
+ display: ${config.customControls.hidePlayButton ? 'none' : 'block'} !important;
2445
+ }
2446
+ video::-webkit-media-controls-timeline {
2447
+ display: ${config.customControls.hideProgressBar ? 'none' : 'block'} !important;
2448
+ }
2449
+ video::-webkit-media-controls-current-time-display {
2450
+ display: ${config.customControls.hideCurrentTime ? 'none' : 'block'} !important;
2451
+ }
2452
+ video::-webkit-media-controls-time-remaining-display {
2453
+ display: ${config.customControls.hideRemainingTime ? 'none' : 'block'} !important;
2454
+ }
2455
+ video::-webkit-media-controls-volume-slider {
2456
+ display: ${config.customControls.hideVolumeSlider ? 'none' : 'block'} !important;
2457
+ }
2458
+ video::-webkit-media-controls-mute-button {
2459
+ display: ${config.customControls.hideMuteButton ? 'none' : 'block'} !important;
2460
+ }
2461
+ video::-webkit-media-controls-fullscreen-button {
2462
+ display: ${config.customControls.hideFullscreenButton ? 'none' : 'block'} !important;
2463
+ }
2464
+ `;
2465
+ document.head.appendChild(customControlsStyle);
2466
+ }
2467
+ }
2468
+ else if (video.controls) {
2469
+ // controls=true이지만 특별한 설정이 없을 때, 기본 스타일 적용 (시간만 표시)
2470
+ const defaultControlsStyle = document.createElement('style');
2471
+ defaultControlsStyle.id = 'adstage-video-default-controls';
2472
+ defaultControlsStyle.textContent = `
2473
+ .adstage-video-container video::-webkit-media-controls-mute-button {
2474
+ display: none !important;
2475
+ }
2476
+ .adstage-video-container video::-webkit-media-controls-fullscreen-button {
2477
+ display: none !important;
2478
+ }
2479
+ .adstage-video-container video::-webkit-media-controls-toggle-closed-captions-button {
2480
+ display: none !important;
2481
+ }
2482
+ .adstage-video-container video::-webkit-media-controls-volume-slider {
2483
+ display: none !important;
2484
+ }
2485
+ .adstage-video-container video::-webkit-media-controls-overflow-button {
2486
+ display: none !important;
2487
+ }
2488
+ .adstage-video-container video::-webkit-media-controls-picture-in-picture-button {
2489
+ display: none !important;
2490
+ }
2491
+ video::-webkit-media-controls-mute-button {
2492
+ display: none !important;
2493
+ }
2494
+ video::-webkit-media-controls-fullscreen-button {
2495
+ display: none !important;
2496
+ }
2497
+ video::-webkit-media-controls-toggle-closed-captions-button {
2498
+ display: none !important;
2499
+ }
2500
+ video::-webkit-media-controls-volume-slider {
2501
+ display: none !important;
2502
+ }
2503
+ video::-webkit-media-controls-overflow-button {
2504
+ display: none !important;
2505
+ }
2506
+ video::-webkit-media-controls-picture-in-picture-button {
2507
+ display: none !important;
2508
+ }
2509
+ `;
2510
+ // 스타일이 이미 존재하지 않으면 추가
2511
+ if (!document.getElementById('adstage-video-default-controls')) {
2512
+ document.head.appendChild(defaultControlsStyle);
2513
+ }
2514
+ }
2515
+ // 기본값이 controls=false이므로 아무것도 표시하지 않음
2516
+ if (this.debug) {
2517
+ console.log('🎬 Video controls setting:', video.controls ? 'enabled' : 'disabled (default)');
2518
+ }
2519
+ // 커스텀 음소거 토글 버튼 생성 (기본적으로 항상 표시)
2520
+ const muteButton = document.createElement('button');
2521
+ muteButton.className = 'adstage-video-mute-button';
2522
+ muteButton.style.cssText = `
2523
+ position: absolute;
2524
+ top: 12px;
2525
+ left: 12px;
2526
+ width: 40px;
2527
+ height: 40px;
2528
+ border: none;
2529
+ border-radius: 50%;
2530
+ background: rgba(0, 0, 0, 0.7);
2531
+ color: white;
2532
+ font-size: 16px;
2533
+ cursor: pointer;
2534
+ display: flex;
2535
+ align-items: center;
2536
+ justify-content: center;
2537
+ z-index: 10;
2538
+ transition: all 0.3s ease;
2539
+ backdrop-filter: blur(4px);
2540
+ `;
2541
+ // hideControls가 true면 음소거 버튼도 숨김
2542
+ if (config?.hideControls) {
2543
+ muteButton.style.display = 'none';
2544
+ }
2545
+ // 음소거 상태에 따른 아이콘 업데이트
2546
+ const updateMuteButtonIcon = () => {
2547
+ const mutedIcon = `
2548
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="white">
2549
+ <path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"/>
2550
+ </svg>
2551
+ `;
2552
+ const unmutedIcon = `
2553
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="white">
2554
+ <path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/>
2555
+ </svg>
2556
+ `;
2557
+ muteButton.innerHTML = video.muted ? mutedIcon : unmutedIcon;
2558
+ muteButton.title = video.muted ? 'Click to unmute' : 'Click to mute';
2559
+ };
2560
+ // 초기 아이콘 설정
2561
+ updateMuteButtonIcon();
2562
+ // 음소거 버튼 클릭 이벤트
2563
+ muteButton.addEventListener('click', (e) => {
2564
+ e.stopPropagation(); // 비디오 클릭 이벤트 방지
2565
+ video.muted = !video.muted;
2566
+ updateMuteButtonIcon();
2567
+ if (this.debug) {
2568
+ console.log(`🔊 Video mute toggled: ${video.muted ? 'muted' : 'unmuted'}`);
2569
+ }
1849
2570
  });
1850
- const maxGroup = Math.max(...ratioGroups.values());
1851
- const totalImages = dimensions.length;
1852
- if (maxGroup / totalImages >= 0.7) {
1853
- return 'dominant';
2571
+ // 마우스 호버 효과
2572
+ muteButton.addEventListener('mouseenter', () => {
2573
+ muteButton.style.background = 'rgba(0, 0, 0, 0.9)';
2574
+ muteButton.style.transform = 'scale(1.1)';
2575
+ });
2576
+ muteButton.addEventListener('mouseleave', () => {
2577
+ muteButton.style.background = 'rgba(0, 0, 0, 0.7)';
2578
+ muteButton.style.transform = 'scale(1)';
2579
+ });
2580
+ // 비디오 URL 설정
2581
+ if (advertisement.videoUrl) {
2582
+ video.src = advertisement.videoUrl;
2583
+ // 자동 재생을 위한 다단계 시도
2584
+ const attemptAutoplay = () => {
2585
+ if (video.autoplay && video.muted && video.paused) {
2586
+ video.play().catch(error => {
2587
+ if (this.debug) {
2588
+ console.warn('🎬 Auto-play was prevented:', error);
2589
+ console.warn('🎬 Trying muted autoplay fallback...');
2590
+ }
2591
+ // 음소거 상태에서 다시 시도
2592
+ video.muted = true;
2593
+ video.play().catch(fallbackError => {
2594
+ if (this.debug) {
2595
+ console.error('🎬 Autoplay completely failed:', fallbackError);
2596
+ }
2597
+ });
2598
+ });
2599
+ }
2600
+ };
2601
+ // 다양한 이벤트에서 자동 재생 시도
2602
+ video.addEventListener('loadedmetadata', () => {
2603
+ if (this.debug) {
2604
+ console.log('🎬 Video metadata loaded, attempting autoplay...');
2605
+ }
2606
+ attemptAutoplay();
2607
+ });
2608
+ video.addEventListener('canplay', () => {
2609
+ if (this.debug) {
2610
+ console.log('🎬 Video can play, attempting autoplay...');
2611
+ }
2612
+ attemptAutoplay();
2613
+ });
2614
+ video.addEventListener('loadeddata', () => {
2615
+ if (this.debug) {
2616
+ console.log('🎬 Video data loaded, attempting autoplay...');
2617
+ }
2618
+ attemptAutoplay();
2619
+ });
2620
+ // 비디오 로드 시작 즉시 한 번 시도
2621
+ setTimeout(() => {
2622
+ if (this.debug) {
2623
+ console.log('🎬 Initial autoplay attempt after timeout...');
2624
+ }
2625
+ attemptAutoplay();
2626
+ }, 100);
2627
+ }
2628
+ else if (advertisement.imageUrl) {
2629
+ // 비디오 URL이 없으면 이미지를 대체 표시
2630
+ const img = document.createElement('img');
2631
+ img.src = advertisement.imageUrl;
2632
+ img.style.width = '100%';
2633
+ img.style.height = '100%';
2634
+ img.style.objectFit = 'contain';
2635
+ img.alt = advertisement.title || 'Video thumbnail';
2636
+ container.appendChild(img);
2637
+ return;
2638
+ }
2639
+ // 클릭 이벤트 추가 (공통 컴포넌트 사용)
2640
+ AdClickHandler.addClickEventForRenderer(video, advertisement, slot, () => this.createEventTrackingCallback(), this.debug, 'Video');
2641
+ // 비디오 로드 에러 처리
2642
+ video.addEventListener('error', (e) => {
2643
+ console.error('Video load failed:', e);
2644
+ // 대체 이미지 표시
2645
+ if (advertisement.imageUrl) {
2646
+ const img = document.createElement('img');
2647
+ img.src = advertisement.imageUrl;
2648
+ img.style.width = '100%';
2649
+ img.style.height = '100%';
2650
+ img.style.objectFit = 'contain';
2651
+ img.alt = advertisement.title || 'Video thumbnail';
2652
+ // 클릭 이벤트 추가 (공통 컴포넌트 사용)
2653
+ AdClickHandler.addClickEventForRenderer(img, advertisement, slot, () => this.createEventTrackingCallback(), this.debug, 'Video fallback');
2654
+ container.innerHTML = '';
2655
+ container.appendChild(img);
2656
+ }
2657
+ });
2658
+ // 비디오와 음소거 버튼을 컨테이너에 추가
2659
+ container.appendChild(video);
2660
+ container.appendChild(muteButton);
2661
+ if (this.debug) {
2662
+ console.log(`🎬 Video element created for ad: ${advertisement._id} (autoplay: ${video.autoplay}, muted: ${video.muted}, loop: ${video.loop})`);
2663
+ }
2664
+ }
2665
+ }
2666
+
2667
+ /**
2668
+ * 네이티브 광고 전용 렌더러
2669
+ */
2670
+ class NativeAdRenderer extends BaseAdRenderer {
2671
+ constructor(debug = false, advertisementEventTracker) {
2672
+ super(AdType.NATIVE, debug, advertisementEventTracker);
2673
+ }
2674
+ /**
2675
+ * 네이티브 광고 기본 높이
2676
+ */
2677
+ getDefaultHeight() {
2678
+ return '200px';
2679
+ }
2680
+ /**
2681
+ * 단일 네이티브 광고 렌더링
2682
+ */
2683
+ async renderAdElement(slot, advertisement) {
2684
+ const container = document.getElementById(slot.containerId);
2685
+ if (!container)
2686
+ return;
2687
+ const adElement = document.createElement('div');
2688
+ adElement.className = 'adstage-ad adstage-native-ad';
2689
+ adElement.style.cssText = `
2690
+ width: 100%;
2691
+ height: 100%;
2692
+ display: flex;
2693
+ flex-direction: column;
2694
+ padding: 16px;
2695
+ background: #fff;
2696
+ border: 1px solid #e5e7eb;
2697
+ border-radius: 8px;
2698
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
2699
+ `;
2700
+ // 제목
2701
+ if (advertisement.title) {
2702
+ const title = document.createElement('h3');
2703
+ title.textContent = advertisement.title;
2704
+ title.style.cssText = `
2705
+ margin: 0 0 8px 0;
2706
+ font-size: 16px;
2707
+ font-weight: 600;
2708
+ color: #111827;
2709
+ line-height: 1.3;
2710
+ `;
2711
+ adElement.appendChild(title);
2712
+ }
2713
+ // 설명
2714
+ if (advertisement.textContent) {
2715
+ const description = document.createElement('p');
2716
+ description.textContent = advertisement.textContent;
2717
+ description.style.cssText = `
2718
+ margin: 0 0 12px 0;
2719
+ font-size: 14px;
2720
+ color: #6b7280;
2721
+ line-height: 1.4;
2722
+ flex: 1;
2723
+ `;
2724
+ adElement.appendChild(description);
2725
+ }
2726
+ // 이미지 (있는 경우)
2727
+ if (advertisement.imageUrl) {
2728
+ const imageContainer = document.createElement('div');
2729
+ imageContainer.style.cssText = `
2730
+ width: 100%;
2731
+ height: 120px;
2732
+ margin-bottom: 12px;
2733
+ border-radius: 6px;
2734
+ overflow: hidden;
2735
+ background: #f3f4f6;
2736
+ `;
2737
+ const img = document.createElement('img');
2738
+ img.src = advertisement.imageUrl;
2739
+ img.alt = advertisement.title || 'Native Advertisement';
2740
+ img.style.cssText = `
2741
+ width: 100%;
2742
+ height: 100%;
2743
+ object-fit: cover;
2744
+ `;
2745
+ imageContainer.appendChild(img);
2746
+ adElement.appendChild(imageContainer);
2747
+ }
2748
+ // CTA 버튼 (링크가 있는 경우)
2749
+ if (advertisement.linkUrl) {
2750
+ const ctaButton = document.createElement('button');
2751
+ ctaButton.textContent = 'Learn More';
2752
+ ctaButton.style.cssText = `
2753
+ padding: 8px 16px;
2754
+ background: #3b82f6;
2755
+ color: white;
2756
+ border: none;
2757
+ border-radius: 6px;
2758
+ font-size: 14px;
2759
+ font-weight: 500;
2760
+ cursor: pointer;
2761
+ align-self: flex-start;
2762
+ transition: background-color 0.2s;
2763
+ `;
2764
+ ctaButton.addEventListener('click', () => {
2765
+ if (this.advertisementEventTracker) {
2766
+ console.log(`Native click tracked for ad: ${advertisement._id}`);
2767
+ }
2768
+ window.open(advertisement.linkUrl, '_blank');
2769
+ });
2770
+ ctaButton.addEventListener('mouseenter', () => {
2771
+ ctaButton.style.backgroundColor = '#2563eb';
2772
+ });
2773
+ ctaButton.addEventListener('mouseleave', () => {
2774
+ ctaButton.style.backgroundColor = '#3b82f6';
2775
+ });
2776
+ adElement.appendChild(ctaButton);
1854
2777
  }
1855
- const standardRatios = [16 / 9, 4 / 3, 1 / 1, 3 / 2];
1856
- const standardCount = aspectRatios.filter(ratio => standardRatios.some(standard => Math.abs(ratio - standard) < 0.1)).length;
1857
- if (standardCount / totalImages >= 0.5) {
1858
- return 'common';
2778
+ container.innerHTML = '';
2779
+ container.appendChild(adElement);
2780
+ if (this.debug) {
2781
+ console.log(`🏠 Single native ad rendered: ${advertisement._id}`);
1859
2782
  }
1860
- return 'average';
1861
2783
  }
1862
2784
  /**
1863
- * 전략에 따른 최적 높이 계산
2785
+ * 다중 네이티브 광고 렌더링 - 현재는 단일 렌더링만 지원
1864
2786
  */
1865
- calculateOptimalHeight(dimensions, containerWidth, strategy) {
1866
- const aspectRatios = dimensions.map(d => d.width / d.height);
1867
- switch (strategy) {
1868
- case 'dominant': {
1869
- const ratioGroups = new Map();
1870
- aspectRatios.forEach(ratio => {
1871
- const roundedRatio = Math.round(ratio * 10) / 10;
1872
- const key = roundedRatio.toString();
1873
- const existing = ratioGroups.get(key);
1874
- if (existing) {
1875
- existing.count++;
1876
- }
1877
- else {
1878
- ratioGroups.set(key, { ratio: roundedRatio, count: 1 });
1879
- }
1880
- });
1881
- const dominantGroup = Array.from(ratioGroups.values()).reduce((max, current) => current.count > max.count ? current : max);
1882
- return Math.round(containerWidth / dominantGroup.ratio);
1883
- }
1884
- case 'common': {
1885
- const standardRatios = [
1886
- { ratio: 16 / 9, name: '16:9' },
1887
- { ratio: 4 / 3, name: '4:3' },
1888
- { ratio: 1 / 1, name: '1:1' },
1889
- { ratio: 3 / 2, name: '3:2' }
1890
- ];
1891
- const avgRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
1892
- const bestStandard = standardRatios.reduce((best, current) => Math.abs(current.ratio - avgRatio) < Math.abs(best.ratio - avgRatio) ? current : best);
1893
- if (this.debug) {
1894
- console.log(`📊 Using standard ratio: ${bestStandard.name} (avg: ${avgRatio.toFixed(2)})`);
1895
- }
1896
- return Math.round(containerWidth / bestStandard.ratio);
2787
+ async renderMultipleAds(slot, advertisements) {
2788
+ if (advertisements.length > 0) {
2789
+ await this.renderAdElement(slot, advertisements[0]);
2790
+ if (this.debug) {
2791
+ console.log(`🏠 Native ad rendered (first of ${advertisements.length}): ${slot.id}`);
1897
2792
  }
1898
- case 'average':
1899
- default: {
1900
- const averageRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
1901
- return Math.round(containerWidth / averageRatio);
2793
+ }
2794
+ else {
2795
+ if (this.debug) {
2796
+ console.warn(`⚠️ No native advertisements available for slot: ${slot.id}`);
1902
2797
  }
1903
2798
  }
1904
2799
  }
2800
+ }
2801
+
2802
+ /**
2803
+ * 전면광고 전용 렌더러
2804
+ */
2805
+ class InterstitialAdRenderer extends BaseAdRenderer {
2806
+ constructor(debug = false, advertisementEventTracker) {
2807
+ super(AdType.INTERSTITIAL, debug, advertisementEventTracker);
2808
+ }
1905
2809
  /**
1906
- * 배너 광고를 위한 컨테이너 최적화
2810
+ * 전면광고 기본 높이 (크게 설정)
1907
2811
  */
1908
- async optimizeContainerForBannerAds(slot, advertisements) {
1909
- try {
1910
- const container = document.getElementById(slot.containerId);
1911
- const adElement = document.getElementById(slot.id);
1912
- if (!container || !adElement)
1913
- return;
1914
- const containerWidth = container.getBoundingClientRect().width || 300;
1915
- const optimalSize = await this.calculateOptimalContainerSize(advertisements, containerWidth, slot.adType);
1916
- adElement.style.height = optimalSize.height;
1917
- slot.optimizedHeight = optimalSize.height;
1918
- slot.aspectRatio = optimalSize.aspectRatio;
1919
- if (this.debug) {
1920
- console.log(`🔧 Container optimized for ${advertisements.length} banner ads: ${optimalSize.height}`);
1921
- }
1922
- }
1923
- catch (error) {
1924
- console.warn('Container optimization failed, using default size:', error);
1925
- }
2812
+ getDefaultHeight() {
2813
+ return '400px';
1926
2814
  }
1927
2815
  /**
1928
- * 광고 슬라이더 렌더링 (여러 광고 또는 autoSlide 옵션)
2816
+ * 단일 전면광고 렌더링
1929
2817
  */
1930
- async renderAdSlider(slot, advertisements) {
2818
+ async renderAdElement(slot, advertisement) {
1931
2819
  const container = document.getElementById(slot.containerId);
1932
- if (!container) {
1933
- throw new Error(`Container not found: ${slot.containerId}`);
2820
+ if (!container)
2821
+ return;
2822
+ // 전면광고 오버레이 생성
2823
+ const overlay = document.createElement('div');
2824
+ overlay.className = 'adstage-interstitial-overlay';
2825
+ overlay.style.cssText = `
2826
+ position: fixed;
2827
+ top: 0;
2828
+ left: 0;
2829
+ width: 100vw;
2830
+ height: 100vh;
2831
+ background: rgba(0, 0, 0, 0.8);
2832
+ display: flex;
2833
+ align-items: center;
2834
+ justify-content: center;
2835
+ z-index: 10000;
2836
+ animation: fadeIn 0.3s ease-out;
2837
+ `;
2838
+ // 전면광고 콘텐츠
2839
+ const adContent = document.createElement('div');
2840
+ adContent.className = 'adstage-interstitial-content';
2841
+ adContent.style.cssText = `
2842
+ position: relative;
2843
+ max-width: 90vw;
2844
+ max-height: 90vh;
2845
+ background: white;
2846
+ border-radius: 12px;
2847
+ padding: 24px;
2848
+ box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
2849
+ animation: slideUp 0.3s ease-out;
2850
+ overflow: auto;
2851
+ `;
2852
+ // 닫기 버튼
2853
+ const closeButton = document.createElement('button');
2854
+ closeButton.innerHTML = '×';
2855
+ closeButton.style.cssText = `
2856
+ position: absolute;
2857
+ top: 12px;
2858
+ right: 12px;
2859
+ width: 32px;
2860
+ height: 32px;
2861
+ border: none;
2862
+ background: #f3f4f6;
2863
+ color: #6b7280;
2864
+ font-size: 20px;
2865
+ font-weight: bold;
2866
+ border-radius: 50%;
2867
+ cursor: pointer;
2868
+ display: flex;
2869
+ align-items: center;
2870
+ justify-content: center;
2871
+ transition: all 0.2s;
2872
+ `;
2873
+ closeButton.addEventListener('click', () => {
2874
+ this.closeInterstitial(overlay);
2875
+ });
2876
+ closeButton.addEventListener('mouseenter', () => {
2877
+ closeButton.style.backgroundColor = '#e5e7eb';
2878
+ closeButton.style.color = '#374151';
2879
+ });
2880
+ closeButton.addEventListener('mouseleave', () => {
2881
+ closeButton.style.backgroundColor = '#f3f4f6';
2882
+ closeButton.style.color = '#6b7280';
2883
+ });
2884
+ // 이미지 (있는 경우)
2885
+ if (advertisement.imageUrl) {
2886
+ const img = document.createElement('img');
2887
+ img.src = advertisement.imageUrl;
2888
+ img.alt = advertisement.title || 'Interstitial Advertisement';
2889
+ img.style.cssText = `
2890
+ width: 100%;
2891
+ max-height: 300px;
2892
+ object-fit: cover;
2893
+ border-radius: 8px;
2894
+ margin-bottom: 16px;
2895
+ `;
2896
+ adContent.appendChild(img);
2897
+ }
2898
+ // 제목
2899
+ if (advertisement.title) {
2900
+ const title = document.createElement('h2');
2901
+ title.textContent = advertisement.title;
2902
+ title.style.cssText = `
2903
+ margin: 0 0 12px 0;
2904
+ font-size: 24px;
2905
+ font-weight: 700;
2906
+ color: #111827;
2907
+ line-height: 1.3;
2908
+ `;
2909
+ adContent.appendChild(title);
2910
+ }
2911
+ // 설명
2912
+ if (advertisement.textContent) {
2913
+ const description = document.createElement('p');
2914
+ description.textContent = advertisement.textContent;
2915
+ description.style.cssText = `
2916
+ margin: 0 0 20px 0;
2917
+ font-size: 16px;
2918
+ color: #6b7280;
2919
+ line-height: 1.5;
2920
+ `;
2921
+ adContent.appendChild(description);
1934
2922
  }
1935
- const trackEventCallback = async (adId, slotId, eventType) => {
1936
- if (eventType === AdEventType.VIEWABLE) {
1937
- if (ViewableEventTracker.isDuplicateViewable(adId, slotId, this.debug)) {
1938
- if (this.debug) {
1939
- console.log(`🚫 Duplicate viewable blocked for ad ${adId} in slot ${slotId}`);
1940
- }
1941
- return;
1942
- }
1943
- if (this.debug) {
1944
- console.log(`✅ New viewable recorded for ad ${adId} in slot ${slotId}`);
1945
- }
1946
- }
1947
- if (this.advertisementEventTracker) {
1948
- try {
1949
- if (this.debug) {
1950
- console.log(`🔄 Starting advertisement event tracking: ${eventType} for ad ${adId} in slot ${slotId}`);
1951
- }
1952
- await this.advertisementEventTracker.trackAdvertisementEvent(adId, slotId, eventType);
1953
- if (this.debug) {
1954
- console.log(`📊 Advertisement event tracked: ${eventType} for ad ${adId} in slot ${slotId}`);
1955
- }
1956
- }
1957
- catch (error) {
1958
- if (this.debug) {
1959
- console.error(`❌ Failed to track ${eventType} event for ad ${adId}:`, error);
1960
- }
1961
- }
1962
- }
1963
- else {
1964
- if (this.debug) {
1965
- console.warn(`⚠️ AdvertisementEventTracker not available for ${eventType} event`);
2923
+ // CTA 버튼 (링크가 있는 경우)
2924
+ if (advertisement.linkUrl) {
2925
+ const ctaButton = document.createElement('button');
2926
+ ctaButton.textContent = 'Get Started';
2927
+ ctaButton.style.cssText = `
2928
+ width: 100%;
2929
+ padding: 12px 24px;
2930
+ background: #3b82f6;
2931
+ color: white;
2932
+ border: none;
2933
+ border-radius: 8px;
2934
+ font-size: 16px;
2935
+ font-weight: 600;
2936
+ cursor: pointer;
2937
+ transition: background-color 0.2s;
2938
+ `;
2939
+ ctaButton.addEventListener('click', () => {
2940
+ if (this.advertisementEventTracker) {
2941
+ console.log(`Interstitial click tracked for ad: ${advertisement._id}`);
1966
2942
  }
2943
+ window.open(advertisement.linkUrl, '_blank');
2944
+ this.closeInterstitial(overlay);
2945
+ });
2946
+ ctaButton.addEventListener('mouseenter', () => {
2947
+ ctaButton.style.backgroundColor = '#2563eb';
2948
+ });
2949
+ ctaButton.addEventListener('mouseleave', () => {
2950
+ ctaButton.style.backgroundColor = '#3b82f6';
2951
+ });
2952
+ adContent.appendChild(ctaButton);
2953
+ }
2954
+ // ESC 키로 닫기
2955
+ const handleEscape = (event) => {
2956
+ if (event.key === 'Escape') {
2957
+ this.closeInterstitial(overlay);
2958
+ document.removeEventListener('keydown', handleEscape);
1967
2959
  }
1968
2960
  };
1969
- let sliderElement;
1970
- const optimizedSliderOptions = {
1971
- autoSlideInterval: (slot.config?.slideInterval || 5000) / 1000,
1972
- ...slot.config,
1973
- optimizedHeight: slot.optimizedHeight,
1974
- aspectRatio: slot.aspectRatio
1975
- };
1976
- if (slot.adType === AdType.TEXT) {
1977
- sliderElement = TextTransitionManager.createTextTransitionContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback);
2961
+ document.addEventListener('keydown', handleEscape);
2962
+ // 오버레이 클릭으로 닫기
2963
+ overlay.addEventListener('click', (event) => {
2964
+ if (event.target === overlay) {
2965
+ this.closeInterstitial(overlay);
2966
+ }
2967
+ });
2968
+ // CSS 애니메이션 추가
2969
+ if (!document.getElementById('adstage-interstitial-styles')) {
2970
+ const styles = document.createElement('style');
2971
+ styles.id = 'adstage-interstitial-styles';
2972
+ styles.textContent = `
2973
+ @keyframes fadeIn {
2974
+ from { opacity: 0; }
2975
+ to { opacity: 1; }
2976
+ }
2977
+ @keyframes slideUp {
2978
+ from {
2979
+ opacity: 0;
2980
+ transform: translateY(20px);
2981
+ }
2982
+ to {
2983
+ opacity: 1;
2984
+ transform: translateY(0);
2985
+ }
2986
+ }
2987
+ `;
2988
+ document.head.appendChild(styles);
2989
+ }
2990
+ adContent.appendChild(closeButton);
2991
+ overlay.appendChild(adContent);
2992
+ document.body.appendChild(overlay);
2993
+ if (this.debug) {
2994
+ console.log(`🖼️ Interstitial ad rendered: ${advertisement._id}`);
2995
+ }
2996
+ }
2997
+ /**
2998
+ * 다중 전면광고 렌더링 - 현재는 단일 렌더링만 지원
2999
+ */
3000
+ async renderMultipleAds(slot, advertisements) {
3001
+ if (advertisements.length > 0) {
3002
+ await this.renderAdElement(slot, advertisements[0]);
1978
3003
  if (this.debug) {
1979
- console.log(`✨ Text transition created for TEXT slot: ${slot.id} with ${advertisements.length} ads`);
3004
+ console.log(`🖼️ Interstitial ad rendered (first of ${advertisements.length}): ${slot.id}`);
1980
3005
  }
1981
3006
  }
1982
3007
  else {
1983
- sliderElement = CarouselSliderManager.createSliderContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback);
1984
3008
  if (this.debug) {
1985
- console.log(`🎠 Carousel slider created for ${slot.adType} slot: ${slot.id} with ${advertisements.length} ads (optimized: ${slot.optimizedHeight || 'default'})`);
3009
+ console.warn(`⚠️ No interstitial advertisements available for slot: ${slot.id}`);
1986
3010
  }
1987
3011
  }
1988
- container.innerHTML = '';
1989
- container.appendChild(sliderElement);
3012
+ }
3013
+ /**
3014
+ * 전면광고 닫기
3015
+ */
3016
+ closeInterstitial(overlay) {
3017
+ overlay.style.animation = 'fadeOut 0.3s ease-out forwards';
3018
+ // CSS 애니메이션이 없으면 즉시 제거
3019
+ setTimeout(() => {
3020
+ if (overlay.parentNode) {
3021
+ overlay.parentNode.removeChild(overlay);
3022
+ }
3023
+ }, 300);
1990
3024
  if (this.debug) {
1991
- console.log(`� Slider uses manual VIEWABLE event tracking for ${advertisements.length} ads`);
3025
+ console.log('🖼️ Interstitial ad closed');
1992
3026
  }
1993
3027
  }
3028
+ }
3029
+
3030
+ /**
3031
+ * AdRenderer - 광고 렌더링 팩토리 클래스
3032
+ * 광고 타입별로 적절한 렌더러를 생성하고 관리
3033
+ */
3034
+ class AdRenderer {
3035
+ constructor(debug = false, advertisementEventTracker) {
3036
+ this.renderers = new Map();
3037
+ this.debug = debug;
3038
+ this.advertisementEventTracker = advertisementEventTracker || null;
3039
+ // 각 광고 타입별 렌더러 초기화
3040
+ this.initializeRenderers();
3041
+ }
1994
3042
  /**
1995
- * 광고 렌더링 (단일 광고용)
3043
+ * 광고 타입별 렌더러 초기화
1996
3044
  */
1997
- async renderAd(slot) {
1998
- if (!slot.advertisement) {
1999
- throw new Error('No advertisement to render');
3045
+ initializeRenderers() {
3046
+ this.renderers.set(AdType.BANNER, new BannerAdRenderer(this.debug, this.advertisementEventTracker));
3047
+ this.renderers.set(AdType.TEXT, new TextAdRenderer(this.debug, this.advertisementEventTracker));
3048
+ this.renderers.set(AdType.VIDEO, new VideoAdRenderer(this.debug, this.advertisementEventTracker));
3049
+ this.renderers.set(AdType.NATIVE, new NativeAdRenderer(this.debug, this.advertisementEventTracker));
3050
+ this.renderers.set(AdType.INTERSTITIAL, new InterstitialAdRenderer(this.debug, this.advertisementEventTracker));
3051
+ if (this.debug) {
3052
+ console.log(`🏭 AdRenderer factory initialized with ${this.renderers.size} renderers`);
2000
3053
  }
2001
- await this.renderAdElement(slot, slot.advertisement);
2002
- slot.isLoaded = true;
2003
3054
  }
2004
3055
  /**
2005
- * 광고 요소 렌더링 (기본 구현)
3056
+ * 광고 요소를 동기적으로 생성해서 반환 (크기 측정 등을 위한 helper)
2006
3057
  */
2007
- async renderAdElement(slot, ad) {
2008
- const container = document.getElementById(slot.containerId);
2009
- if (!container)
2010
- return;
3058
+ createAdElement(slot, advertisement) {
3059
+ const renderer = this.getRenderer(slot.adType);
3060
+ // 기본 광고 요소 생성
2011
3061
  const adElement = document.createElement('div');
2012
- adElement.className = 'adstage-ad';
2013
- const optimizedHeight = slot.optimizedHeight;
2014
- const containerElement = container.parentElement || container;
2015
- if (optimizedHeight) {
2016
- adElement.style.width = '100%';
2017
- adElement.style.height = String(optimizedHeight);
2018
- }
2019
- else {
2020
- const { width, height } = this.calculateAdSize(containerElement, slot.adType, slot.config || {}, { debug: this.debug }) ||
2021
- { width: '100%', height: '250px' };
2022
- adElement.style.width = width;
2023
- adElement.style.height = height;
2024
- }
3062
+ adElement.className = `adstage-ad adstage-${String(slot.adType).toLowerCase()}`;
3063
+ adElement.setAttribute('data-adstage-ad-id', advertisement._id);
3064
+ adElement.setAttribute('data-adstage-slot-id', slot.id);
3065
+ // 광고 타입별 기본 컨테이너 설정
3066
+ const { width, height } = renderer.calculateAdSize(adElement, slot.config || {}, advertisement);
3067
+ adElement.style.width = width;
3068
+ adElement.style.height = height;
3069
+ adElement.style.display = 'block';
3070
+ // 간단한 내용 설정 (크기 측정용)
2025
3071
  switch (slot.adType) {
2026
3072
  case AdType.BANNER:
2027
- if (ad.imageUrl) {
2028
- await this.renderOptimizedBannerImage(adElement, ad, slot);
3073
+ if (advertisement.imageUrl) {
3074
+ const img = document.createElement('img');
3075
+ img.src = advertisement.imageUrl;
3076
+ img.style.width = '100%';
3077
+ img.style.height = '100%';
3078
+ img.style.objectFit = 'cover';
3079
+ adElement.appendChild(img);
2029
3080
  }
2030
3081
  break;
2031
- case AdType.TEXT: {
2032
- const textDiv = document.createElement('div');
2033
- textDiv.innerHTML = `
2034
- ${ad.textContent ? `<div>${ad.textContent}</div>` : ''}
2035
- `;
2036
- adElement.appendChild(textDiv);
2037
- break;
2038
- }
2039
3082
  case AdType.VIDEO:
2040
- if (ad.videoUrl) {
3083
+ if (advertisement.videoUrl) {
2041
3084
  const video = document.createElement('video');
2042
- video.src = ad.videoUrl;
2043
- video.controls = true;
3085
+ video.src = advertisement.videoUrl;
2044
3086
  video.style.width = '100%';
2045
3087
  video.style.height = '100%';
2046
3088
  adElement.appendChild(video);
2047
3089
  }
2048
3090
  break;
3091
+ case AdType.TEXT:
3092
+ if (advertisement.textContent) {
3093
+ const textDiv = document.createElement('div');
3094
+ textDiv.textContent = advertisement.textContent || '';
3095
+ textDiv.style.padding = '8px';
3096
+ adElement.appendChild(textDiv);
3097
+ }
3098
+ break;
2049
3099
  default:
2050
- adElement.innerHTML = `<div>${ad.title}</div>`;
2051
- }
2052
- if (ad.linkUrl) {
2053
- adElement.style.cursor = 'pointer';
2054
- adElement.addEventListener('click', () => {
2055
- window.open(ad.linkUrl, '_blank');
2056
- });
3100
+ // 기본 placeholder
3101
+ adElement.style.border = '1px dashed #ccc';
3102
+ adElement.style.backgroundColor = '#f9f9f9';
3103
+ adElement.textContent = `${slot.adType} Ad`;
2057
3104
  }
2058
- container.innerHTML = '';
2059
- container.appendChild(adElement);
3105
+ return adElement;
2060
3106
  }
2061
3107
  /**
2062
- * Fallback 광고 렌더링 - 컨테이너 접기/생성
3108
+ * 광고 타입에 따른 렌더러 획득
2063
3109
  */
2064
- renderFallback(slot) {
2065
- const element = document.getElementById(slot.id);
2066
- if (element) {
2067
- const adstageContainers = [
2068
- element.querySelector('[data-adstage-container="true"]'),
2069
- element.closest('[data-adstage-container="true"]'),
2070
- element
2071
- ].filter(el => el && el.hasAttribute('data-adstage-container'));
2072
- const classBasedContainers = [
2073
- element.closest('.adstage-slot'),
2074
- element.closest('.adstage-banner'),
2075
- element.closest('.adstage-text'),
2076
- element.closest('.adstage-video'),
2077
- element.closest('.adstage-native'),
2078
- element.closest('.adstage-interstitial')
2079
- ].filter(Boolean);
2080
- const generalContainers = [
2081
- element.closest('[class*="ad"]'),
2082
- element.closest('[class*="banner"]'),
2083
- element.closest('[class*="container"]'),
2084
- element.closest('div[style*="height"]'),
2085
- element.closest('div[style*="min-height"]'),
2086
- element.parentElement
2087
- ].filter(Boolean);
2088
- const possibleContainers = [...adstageContainers, ...classBasedContainers, ...generalContainers];
2089
- const targetContainer = possibleContainers[0];
2090
- if (targetContainer) {
2091
- let containerType = 'unknown';
2092
- if (targetContainer.hasAttribute('data-adstage-container')) {
2093
- containerType = 'adstage-official';
2094
- }
2095
- else if (targetContainer.classList.contains('adstage-slot')) {
2096
- containerType = 'adstage-class';
2097
- }
2098
- else {
2099
- containerType = 'generic';
2100
- }
2101
- targetContainer.style.cssText += `
2102
- height: 0px !important;
2103
- min-height: 0px !important;
2104
- padding: 0px !important;
2105
- margin: 0px !important;
2106
- border: none !important;
2107
- overflow: hidden !important;
2108
- display: block !important;
2109
- `;
2110
- targetContainer.innerHTML = '';
2111
- targetContainer.setAttribute('data-adstage-empty', 'true');
2112
- if (this.debug) {
2113
- console.warn(`⚠️ Ad container collapsed (${containerType}): ${slot.id}`, targetContainer);
2114
- }
2115
- }
2116
- else {
2117
- this.createEmptyContainer(slot);
2118
- }
3110
+ getRenderer(adType) {
3111
+ const renderer = this.renderers.get(adType);
3112
+ if (!renderer) {
3113
+ throw new Error(`No renderer found for ad type: ${adType}`);
2119
3114
  }
2120
- slot.advertisement = undefined;
2121
- slot.isEmpty = true;
3115
+ return renderer;
3116
+ }
3117
+ /**
3118
+ * Placeholder(슬롯 컨테이너) 생성
3119
+ */
3120
+ createPlaceholder(container, slotId, type, options, config) {
3121
+ const renderer = this.getRenderer(type);
3122
+ renderer.createPlaceholder(container, slotId, options, config);
2122
3123
  }
2123
3124
  /**
2124
- * 컨테이너 생성 (컨테이너를 찾지 못한 경우)
3125
+ * 배너 광고를 위한 컨테이너 최적화 (배너 전용)
2125
3126
  */
2126
- createEmptyContainer(slot) {
2127
- const originalContainer = document.getElementById(slot.containerId);
2128
- if (originalContainer) {
2129
- originalContainer.innerHTML = '';
2130
- const emptyElement = document.createElement('div');
2131
- emptyElement.id = slot.id;
2132
- emptyElement.className = 'adstage-slot adstage-empty';
2133
- emptyElement.setAttribute('data-adstage-container', 'true');
2134
- emptyElement.setAttribute('data-adstage-empty', 'true');
2135
- emptyElement.setAttribute('data-adstage-slot', slot.id);
2136
- emptyElement.style.cssText = `
2137
- height: 0px !important;
2138
- min-height: 0px !important;
2139
- padding: 0px !important;
2140
- margin: 0px !important;
2141
- border: none !important;
2142
- overflow: hidden !important;
2143
- display: block !important;
2144
- `;
2145
- originalContainer.appendChild(emptyElement);
3127
+ async optimizeContainerForBannerAds(slot, advertisements) {
3128
+ if (slot.adType !== AdType.BANNER) {
2146
3129
  if (this.debug) {
2147
- console.warn(`⚠️ Created empty AdStage container: ${slot.id}`);
3130
+ console.warn(`⚠️ Container optimization is only supported for BANNER ads, got: ${slot.adType}`);
2148
3131
  }
3132
+ return;
2149
3133
  }
3134
+ const bannerRenderer = this.getRenderer(AdType.BANNER);
3135
+ await bannerRenderer.optimizeContainerForBannerAds(slot, advertisements);
2150
3136
  }
2151
3137
  /**
2152
- * 광고 타입별 기본 높이 반환
3138
+ * 광고 슬라이더 렌더링 (여러 광고 또는 autoSlide 옵션)
2153
3139
  */
2154
- getDefaultHeightForAdType(type) {
2155
- switch (type) {
2156
- case AdType.BANNER:
2157
- return '250px'; // 일반 배너
2158
- case AdType.TEXT:
2159
- return '60px'; // 텍스트는 좀 더 작게
2160
- case AdType.VIDEO:
2161
- return '360px'; // 비디오는 16:9 비율 고려
2162
- case AdType.NATIVE:
2163
- return '200px'; // 네이티브는 중간 크기
2164
- case AdType.INTERSTITIAL:
2165
- return '400px'; // 전면광고는 크게
2166
- default:
2167
- return '250px';
2168
- }
3140
+ async renderAdSlider(slot, advertisements) {
3141
+ const renderer = this.getRenderer(slot.adType);
3142
+ await renderer.renderMultipleAds(slot, advertisements);
2169
3143
  }
2170
3144
  /**
2171
- * 컨테이너와 광고 타입에 따른 스마트한 크기 계산
3145
+ * 광고 렌더링 (단일 광고용)
2172
3146
  */
2173
- calculateAdSize(container, type, options, config) {
2174
- // 사용자가 명시적으로 크기를 지정한 경우
2175
- const explicitWidth = options.width;
2176
- const explicitHeight = options.height;
2177
- // 너비 처리
2178
- let width;
2179
- if (typeof explicitWidth === 'number') {
2180
- width = `${explicitWidth}px`;
2181
- }
2182
- else if (typeof explicitWidth === 'string') {
2183
- width = explicitWidth;
2184
- }
2185
- else {
2186
- width = '100%'; // 기본값은 100%
2187
- }
2188
- // 높이 처리 - 핵심 로직
2189
- let height;
2190
- if (typeof explicitHeight === 'number') {
2191
- height = `${explicitHeight}px`;
2192
- }
2193
- else if (typeof explicitHeight === 'string' && explicitHeight !== '100%' && explicitHeight !== 'auto') {
2194
- // 명시적인 크기 문자열 (예: '200px', '50vh' 등)
2195
- height = explicitHeight;
2196
- }
2197
- else {
2198
- // 100%, auto이거나 높이가 지정되지 않은 경우 스마트 계산
2199
- const containerHeight = this.getContainerHeight(container);
2200
- if (containerHeight > 0) {
2201
- // 컨테이너에 높이가 있으면 100% 사용
2202
- height = '100%';
2203
- if (config?.debug) {
2204
- console.log(`📏 Using 100% height (container: ${containerHeight}px)`);
2205
- }
2206
- }
2207
- else {
2208
- // 컨테이너에 높이가 없으면 타입별 기본값 사용 (나중에 동적 조정됨)
2209
- height = this.getDefaultHeightForAdType(type);
2210
- if (config?.debug) {
2211
- console.log(`📏 Using default height ${height} (will be optimized for ${type})`);
2212
- }
2213
- }
3147
+ async renderAd(slot) {
3148
+ if (!slot.advertisement) {
3149
+ throw new Error('No advertisement to render');
2214
3150
  }
2215
- return { width, height };
3151
+ const renderer = this.getRenderer(slot.adType);
3152
+ await renderer.renderAdElement(slot, slot.advertisement);
3153
+ slot.isLoaded = true;
2216
3154
  }
2217
3155
  /**
2218
- * 컨테이너의 실제 높이 계산
3156
+ * 광고 요소 렌더링 (기본 구현) - 호환성을 위해 유지
2219
3157
  */
2220
- getContainerHeight(container) {
2221
- // 현재 계산된 스타일에서 높이 확인
2222
- const computedStyle = window.getComputedStyle(container);
2223
- const height = parseFloat(computedStyle.height);
2224
- // height가 auto이거나 0이면 다른 방법들 시도
2225
- if (!height || height === 0) {
2226
- // min-height 확인
2227
- const minHeight = parseFloat(computedStyle.minHeight);
2228
- if (minHeight > 0)
2229
- return minHeight;
2230
- // CSS로 설정된 고정 높이 확인
2231
- if (container.style.height && container.style.height !== 'auto') {
2232
- const styleHeight = parseFloat(container.style.height);
2233
- if (styleHeight > 0)
2234
- return styleHeight;
2235
- }
2236
- // 속성으로 설정된 높이 확인
2237
- const heightAttr = container.getAttribute('height');
2238
- if (heightAttr) {
2239
- const attrHeight = parseFloat(heightAttr);
2240
- if (attrHeight > 0)
2241
- return attrHeight;
2242
- }
2243
- }
2244
- return height || 0;
3158
+ async renderAdElement(slot, ad) {
3159
+ const renderer = this.getRenderer(slot.adType);
3160
+ await renderer.renderAdElement(slot, ad);
3161
+ }
3162
+ /**
3163
+ * Fallback 광고 렌더링 - 컨테이너 접기/생성
3164
+ */
3165
+ renderFallback(slot) {
3166
+ const renderer = this.getRenderer(slot.adType);
3167
+ renderer.renderFallback(slot);
3168
+ }
3169
+ /**
3170
+ * 광고 타입별 기본 높이 반환
3171
+ */
3172
+ getDefaultHeightForAdType(type) {
3173
+ const renderer = this.getRenderer(type);
3174
+ return renderer.getDefaultHeight();
3175
+ }
3176
+ /**
3177
+ * 컨테이너와 광고 타입에 따른 스마트한 크기 계산
3178
+ */
3179
+ calculateAdSize(container, type, options, config) {
3180
+ const renderer = this.getRenderer(type);
3181
+ return renderer.calculateAdSize(container, options, config);
2245
3182
  }
2246
3183
  /**
2247
- * 이미지 로드 및 실제 크기 획득 (Promise 기반)
3184
+ * 이미지 로드 및 실제 크기 획득 (배너 전용)
2248
3185
  */
2249
3186
  loadImageDimensions(imageUrl) {
2250
3187
  return new Promise((resolve, reject) => {
@@ -2259,118 +3196,36 @@ class AdRenderer {
2259
3196
  });
2260
3197
  }
2261
3198
  /**
2262
- * 이미지와 컨테이너 비율을 고려한 최적화 스타일 적용
3199
+ * 배너 이미지 최적화 렌더링 (배너 전용)
2263
3200
  */
2264
- applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio) {
2265
- const ratio = imageAspectRatio / containerAspectRatio;
2266
- if (Math.abs(ratio - 1) < 0.1) {
2267
- // 비율이 거의 같으면 cover 사용
2268
- img.style.objectFit = 'cover';
2269
- img.style.objectPosition = 'center';
2270
- }
2271
- else if (ratio > 1.3) {
2272
- // 이미지가 훨씬 가로형이면 contain으로 전체 보이기
2273
- img.style.objectFit = 'contain';
2274
- img.style.objectPosition = 'center';
2275
- img.style.backgroundColor = '#f0f0f0'; // 빈 공간 배경색
2276
- }
2277
- else if (ratio < 0.7) {
2278
- // 이미지가 훨씬 세로형이면 cover로 채우기
2279
- img.style.objectFit = 'cover';
2280
- img.style.objectPosition = 'center';
2281
- }
2282
- else {
2283
- // 적당한 차이면 스마트 cover
2284
- img.style.objectFit = 'cover';
2285
- img.style.objectPosition = 'center';
2286
- }
2287
- if (this.debug) {
2288
- console.log(`🎨 Image style applied: objectFit=${img.style.objectFit}, ratio=${ratio.toFixed(2)}`);
3201
+ async renderOptimizedBannerImage(container, advertisement, slot) {
3202
+ if (slot.adType !== AdType.BANNER) {
3203
+ throw new Error('renderOptimizedBannerImage is only supported for BANNER ads');
2289
3204
  }
3205
+ const bannerRenderer = this.getRenderer(AdType.BANNER);
3206
+ return await bannerRenderer.renderOptimizedBannerImage(container, advertisement, slot);
2290
3207
  }
2291
3208
  /**
2292
- * 배너 이미지 최적화 렌더링
2293
- * 이미지 실제 크기를 로드한 후 컨테이너와 비율을 맞춤
3209
+ * 여러 광고의 최적 컨테이너 크기 계산 (배너 전용)
2294
3210
  */
2295
- async renderOptimizedBannerImage(container, advertisement, slot) {
2296
- const img = document.createElement('img');
2297
- // 기본 스타일 설정
2298
- img.style.width = '100%';
2299
- img.style.height = '100%';
2300
- img.style.display = 'block';
2301
- img.style.borderRadius = '8px';
2302
- img.alt = advertisement.title || 'Advertisement';
2303
- // 이미지 로딩 상태 표시
2304
- container.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 100%; color: #999;">Loading...</div>';
2305
- try {
2306
- // 이미지 URL 체크
2307
- if (!advertisement.imageUrl) {
2308
- throw new Error('Image URL is not provided');
2309
- }
2310
- // 🆕 이미지 실제 크기 로드
2311
- const imageDimensions = await this.loadImageDimensions(advertisement.imageUrl);
2312
- // 컨테이너 크기 정보
2313
- const containerRect = container.getBoundingClientRect();
2314
- const containerWidth = containerRect.width;
2315
- const containerHeight = containerRect.height;
2316
- if (this.debug) {
2317
- console.log(`📸 Image dimensions: ${imageDimensions.width}x${imageDimensions.height}`);
2318
- console.log(`📦 Container dimensions: ${containerWidth}x${containerHeight}`);
2319
- }
2320
- // 비율 계산
2321
- const imageAspectRatio = imageDimensions.width / imageDimensions.height;
2322
- const containerAspectRatio = containerWidth / containerHeight;
2323
- // 🆕 스마트 스타일 적용
2324
- this.applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio);
2325
- // 이미지 설정 및 추가
2326
- img.src = advertisement.imageUrl;
2327
- // 컨테이너 클리어 후 이미지 추가
2328
- container.innerHTML = '';
2329
- container.appendChild(img);
2330
- // 클릭 이벤트 등록
2331
- if (advertisement.linkUrl) {
2332
- img.style.cursor = 'pointer';
2333
- img.addEventListener('click', () => {
2334
- if (this.advertisementEventTracker) {
2335
- // AdvertisementEventTracker의 실제 메소드명을 확인해야 함
2336
- console.log(`Click tracked for ad: ${advertisement._id}`);
2337
- }
2338
- window.open(advertisement.linkUrl, '_blank');
2339
- });
2340
- }
2341
- if (this.debug) {
2342
- console.log(`✅ Optimized banner image rendered for ad: ${advertisement._id}`);
2343
- }
2344
- return img;
2345
- }
2346
- catch (error) {
2347
- console.error('❌ Failed to load optimized banner image:', error);
2348
- // 폴백: 일반 이미지 렌더링
2349
- if (advertisement.imageUrl) {
2350
- img.src = advertisement.imageUrl;
2351
- img.style.objectFit = 'cover';
2352
- img.style.objectPosition = 'center';
2353
- container.innerHTML = '';
2354
- container.appendChild(img);
2355
- if (advertisement.linkUrl) {
2356
- img.style.cursor = 'pointer';
2357
- img.addEventListener('click', () => {
2358
- if (this.advertisementEventTracker) {
2359
- console.log(`Click tracked for ad: ${advertisement._id}`);
2360
- }
2361
- window.open(advertisement.linkUrl, '_blank');
2362
- });
2363
- }
2364
- }
2365
- return img;
3211
+ async calculateOptimalContainerSize(advertisements, containerWidth, adType) {
3212
+ if (adType !== AdType.BANNER) {
3213
+ const renderer = this.getRenderer(adType);
3214
+ return {
3215
+ width: '100%',
3216
+ height: renderer.getDefaultHeight(),
3217
+ aspectRatio: 16 / 9
3218
+ };
2366
3219
  }
3220
+ const bannerRenderer = this.getRenderer(AdType.BANNER);
3221
+ return await bannerRenderer.calculateOptimalContainerSize(advertisements, containerWidth);
2367
3222
  }
2368
3223
  /**
2369
3224
  * 디버그 로그 출력
2370
3225
  */
2371
3226
  log(message, ...args) {
2372
3227
  if (this.debug) {
2373
- console.log(message, ...args);
3228
+ console.log(`[AdRenderer] ${message}`, ...args);
2374
3229
  }
2375
3230
  }
2376
3231
  }
@@ -2388,6 +3243,8 @@ class AdsModule {
2388
3243
  this.advertisementEventTracker = null;
2389
3244
  // 렌더링 관련
2390
3245
  this.adRenderer = null;
3246
+ // DOM 변화 감지를 위한 MutationObserver
3247
+ this.mutationObserver = null;
2391
3248
  }
2392
3249
  /**
2393
3250
  * Ads 모듈 초기화 (동기)
@@ -2398,9 +3255,11 @@ class AdsModule {
2398
3255
  this.advertisementEventTracker = new AdvertisementEventTracker(endpoints.getBaseUrl(), config.apiKey, config.debug || false, this.slots);
2399
3256
  // AdRenderer 초기화
2400
3257
  this.adRenderer = new AdRenderer(config.debug || false, this.advertisementEventTracker);
3258
+ // DOM 변화 감지를 위한 MutationObserver 설정
3259
+ this.setupAutoCleanup();
2401
3260
  this._isReady = true;
2402
3261
  if (config.debug) {
2403
- console.log('🎯 Ads module initialized (sync mode)');
3262
+ console.log('🎯 Ads module initialized (sync mode) with auto-cleanup');
2404
3263
  }
2405
3264
  }
2406
3265
  /**
@@ -2454,16 +3313,24 @@ class AdsModule {
2454
3313
  return this.createAd(containerId, AdType.TEXT, adstageOptions);
2455
3314
  }
2456
3315
  /**
2457
- * 비디오 광고 생성 (동기)
3316
+ * 비디오 광고 생성 (동기) - 단일 비디오만 지원
2458
3317
  */
2459
3318
  video(containerId, options) {
2460
3319
  this.ensureReady();
2461
3320
  const adstageOptions = {
2462
3321
  width: options?.width || 640,
2463
3322
  height: options?.height || 360,
2464
- autoplay: options?.autoplay || false,
2465
- muted: options?.muted || true,
2466
- onClick: options?.onClick
3323
+ autoplay: options?.autoplay !== undefined ? options.autoplay : true, // 기본값 true (사용자 요구사항)
3324
+ muted: options?.muted !== undefined ? options.muted : true, // 기본값 true
3325
+ loop: options?.loop !== undefined ? options.loop : true, // 기본값 true (사용자 요구사항)
3326
+ playsinline: options?.playsinline !== false, // 기본값 true
3327
+ controls: options?.controls !== undefined ? options.controls : false, // 기본값 false (사용자 요구사항)
3328
+ hideControls: options?.hideControls || false,
3329
+ customControls: options?.customControls,
3330
+ autoSlide: false, // 비디오는 슬라이드 비활성화
3331
+ maxAds: 1, // 하나의 비디오만 가져오기
3332
+ onClick: options?.onClick,
3333
+ ...(options?.adId && { adId: options.adId }) // 특정 비디오 ID가 있으면 사용
2467
3334
  };
2468
3335
  return this.createAd(containerId, AdType.VIDEO, adstageOptions);
2469
3336
  }
@@ -2541,12 +3408,58 @@ class AdsModule {
2541
3408
  if (!this._config?.apiKey) {
2542
3409
  throw new Error('API key not configured');
2543
3410
  }
2544
- const container = document.getElementById(containerId);
2545
- if (!container) {
2546
- throw new Error(`Container not found: ${containerId}`);
2547
- }
2548
- // 고유한 슬롯 ID 생성
3411
+ // 즉시 슬롯 ID 생성 (개발자에게 바로 반환)
2549
3412
  const slotId = `adstage-${type}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
3413
+ // 비동기로 광고 생성 처리 (디바운싱 및 재시도 로직 포함)
3414
+ this.createAdWithRetry(containerId, type, options, slotId, 0);
3415
+ return slotId;
3416
+ }
3417
+ async createAdWithRetry(containerId, type, options, slotId, attempt) {
3418
+ const maxAttempts = 5;
3419
+ const delays = [0, 50, 100, 200, 500]; // 점진적 지연
3420
+ let container = null;
3421
+ let containerIdString;
3422
+ // HTMLElement인지 string인지 구분
3423
+ if (typeof containerId === 'string') {
3424
+ // string인 경우 DOM에서 찾기
3425
+ containerIdString = containerId;
3426
+ container = document.getElementById(containerId);
3427
+ if (!container) {
3428
+ if (attempt < maxAttempts - 1) {
3429
+ if (this._config?.debug) {
3430
+ console.warn(`Container not found: ${containerId}. Retrying in ${delays[attempt + 1]}ms... (attempt ${attempt + 1}/${maxAttempts})`);
3431
+ }
3432
+ setTimeout(() => {
3433
+ this.createAdWithRetry(containerId, type, options, slotId, attempt + 1);
3434
+ }, delays[attempt + 1]);
3435
+ return;
3436
+ }
3437
+ else {
3438
+ console.error(`Container not found after ${maxAttempts} attempts: ${containerId}`);
3439
+ return;
3440
+ }
3441
+ }
3442
+ }
3443
+ else {
3444
+ // HTMLElement인 경우 직접 사용
3445
+ container = containerId;
3446
+ containerIdString = container.id || `auto-${slotId}`;
3447
+ // ID가 없으면 자동 생성
3448
+ if (!container.id) {
3449
+ container.id = containerIdString;
3450
+ }
3451
+ }
3452
+ // 컨테이너를 찾았으면 광고 생성
3453
+ try {
3454
+ this.createAdInternal(containerIdString, type, options, slotId, container);
3455
+ }
3456
+ catch (error) {
3457
+ console.error('광고 생성 중 오류 발생:', error);
3458
+ }
3459
+ }
3460
+ createAdInternal(containerId, type, options, slotId, container) {
3461
+ // 컨테이너에 슬롯 ID 속성 추가 (MutationObserver가 감지할 수 있도록)
3462
+ container.setAttribute('data-adstage-slot-id', slotId);
2550
3463
  // 즉시 placeholder 생성 (AdRenderer 위임)
2551
3464
  this.adRenderer?.createPlaceholder(container, slotId, type, options, this._config);
2552
3465
  // 광고 슬롯 정보 저장
@@ -2555,7 +3468,7 @@ class AdsModule {
2555
3468
  containerId,
2556
3469
  adType: type,
2557
3470
  width: options.width || '100%',
2558
- height: options.height || 250,
3471
+ height: options.height || (type === AdType.TEXT ? 'auto' : 250), // 텍스트 광고는 콘텐츠 높이에 맞춤
2559
3472
  isLoaded: false,
2560
3473
  isVisible: false,
2561
3474
  refreshRate: 0,
@@ -2576,7 +3489,6 @@ class AdsModule {
2576
3489
  if (this.advertisementEventTracker && this._config?.debug) {
2577
3490
  console.log(`📊 Advertisement event tracking enabled for slot: ${slotId}`);
2578
3491
  }
2579
- return slotId;
2580
3492
  }
2581
3493
  /**
2582
3494
  * 백그라운드에서 광고 콘텐츠 로드
@@ -2757,6 +3669,98 @@ class AdsModule {
2757
3669
  throw new Error('Ads module not initialized. Call AdStage.init() first.');
2758
3670
  }
2759
3671
  }
3672
+ /**
3673
+ * DOM 변화 감지를 통한 자동 정리 설정
3674
+ */
3675
+ setupAutoCleanup() {
3676
+ // 브라우저 환경에서만 실행
3677
+ if (typeof window === 'undefined' || typeof document === 'undefined') {
3678
+ return;
3679
+ }
3680
+ // 기존 observer가 있으면 해제
3681
+ if (this.mutationObserver) {
3682
+ this.mutationObserver.disconnect();
3683
+ }
3684
+ // 새로운 MutationObserver 생성
3685
+ this.mutationObserver = new MutationObserver((mutations) => {
3686
+ mutations.forEach((mutation) => {
3687
+ // 제거된 노드들 확인
3688
+ mutation.removedNodes.forEach((node) => {
3689
+ if (node.nodeType === Node.ELEMENT_NODE) {
3690
+ this.handleRemovedElement(node);
3691
+ }
3692
+ });
3693
+ });
3694
+ });
3695
+ // document 전체를 관찰 (childList와 subtree 옵션 사용)
3696
+ this.mutationObserver.observe(document.body, {
3697
+ childList: true,
3698
+ subtree: true
3699
+ });
3700
+ if (this._config?.debug) {
3701
+ console.log('🔍 Auto-cleanup MutationObserver enabled');
3702
+ }
3703
+ }
3704
+ /**
3705
+ * 제거된 요소에서 광고 슬롯 정리
3706
+ */
3707
+ handleRemovedElement(element) {
3708
+ // 제거된 요소가 광고 컨테이너인지 확인
3709
+ const slotId = element.getAttribute('data-adstage-slot-id');
3710
+ if (slotId) {
3711
+ this.autoDestroy(slotId);
3712
+ return;
3713
+ }
3714
+ // 제거된 요소의 하위에 광고 컨테이너가 있는지 확인
3715
+ const adContainers = element.querySelectorAll('[data-adstage-slot-id]');
3716
+ adContainers.forEach((container) => {
3717
+ const containerSlotId = container.getAttribute('data-adstage-slot-id');
3718
+ if (containerSlotId) {
3719
+ this.autoDestroy(containerSlotId);
3720
+ }
3721
+ });
3722
+ }
3723
+ /**
3724
+ * 자동 정리 (로그 없이 조용히 정리)
3725
+ */
3726
+ autoDestroy(slotId) {
3727
+ const slot = this.slots.get(slotId);
3728
+ if (slot) {
3729
+ try {
3730
+ // 슬롯 정리 (로그 출력 최소화)
3731
+ this.slots.delete(slotId);
3732
+ if (this._config?.debug) {
3733
+ console.log(`🧹 Auto-cleanup: slot ${slotId} removed`);
3734
+ }
3735
+ }
3736
+ catch (error) {
3737
+ if (this._config?.debug) {
3738
+ console.warn(`Auto-cleanup failed for slot ${slotId}:`, error);
3739
+ }
3740
+ }
3741
+ }
3742
+ }
3743
+ /**
3744
+ * 모듈 종료 시 정리
3745
+ */
3746
+ destroyModule() {
3747
+ const debugMode = this._config?.debug;
3748
+ // MutationObserver 해제
3749
+ if (this.mutationObserver) {
3750
+ this.mutationObserver.disconnect();
3751
+ this.mutationObserver = null;
3752
+ }
3753
+ // 모든 슬롯 정리
3754
+ this.slots.clear();
3755
+ // 다른 리소스들 정리
3756
+ this.advertisementEventTracker = null;
3757
+ this.adRenderer = null;
3758
+ this._isReady = false;
3759
+ this._config = null;
3760
+ if (debugMode) {
3761
+ console.log('🗑️ Ads module destroyed');
3762
+ }
3763
+ }
2760
3764
  }
2761
3765
 
2762
3766
  /**
@@ -2778,10 +3782,6 @@ class ConfigModule {
2778
3782
  timeout: 30000,
2779
3783
  debug: false,
2780
3784
  modules: ['ads', 'events', 'config'],
2781
- validateOnInit: false,
2782
- fallbackMode: true,
2783
- offlineMode: false,
2784
- productionMode: false,
2785
3785
  ...config
2786
3786
  };
2787
3787
  // 사용자가 baseUrl을 제공한 경우 endpoints에 설정
@@ -2793,7 +3793,7 @@ class ConfigModule {
2793
3793
  console.log('✅ Config module initialized (sync mode)', {
2794
3794
  modules: this._config.modules,
2795
3795
  endpoint: endpoints.getBaseUrl(),
2796
- mode: config.productionMode ? 'production' : 'development'
3796
+ mode: 'development'
2797
3797
  });
2798
3798
  }
2799
3799
  }
@@ -2979,10 +3979,6 @@ class AdStage {
2979
3979
  timeout: 30000,
2980
3980
  debug: false,
2981
3981
  modules: ['ads', 'events', 'config'],
2982
- validateOnInit: false,
2983
- fallbackMode: true,
2984
- offlineMode: false,
2985
- productionMode: false,
2986
3982
  ...config
2987
3983
  };
2988
3984
  // 🔧 baseUrl이 설정된 경우 전역 endpoints 객체 업데이트
@@ -3006,7 +4002,7 @@ class AdStage {
3006
4002
  version: '2.0.0',
3007
4003
  modules: enabledModules,
3008
4004
  apiKey: config.apiKey.substring(0, 8) + '...',
3009
- mode: config.productionMode ? 'production' : 'development'
4005
+ mode: 'development'
3010
4006
  });
3011
4007
  }
3012
4008
  }
@@ -3053,6 +4049,34 @@ class AdStage {
3053
4049
  }
3054
4050
  }
3055
4051
  }
4052
+ /**
4053
+ * 디버그용 메서드들
4054
+ */
4055
+ AdStage.debug = {
4056
+ /**
4057
+ * 모든 viewable 추적 데이터 초기화
4058
+ */
4059
+ clearAllViewable: () => {
4060
+ ViewableEventTracker.clear();
4061
+ console.log('✅ AdStage Debug: 모든 viewable 추적 데이터 초기화됨');
4062
+ },
4063
+ /**
4064
+ * 특정 광고의 viewable 추적 초기화
4065
+ */
4066
+ clearAdViewable: (adId, slotId) => {
4067
+ ViewableEventTracker.clearAdViewable(adId, slotId);
4068
+ console.log(`✅ AdStage Debug: 광고 ${adId}(${slotId})의 viewable 추적 초기화됨`);
4069
+ },
4070
+ /**
4071
+ * 현재 추적 중인 viewable 상태 확인
4072
+ */
4073
+ getViewableStatus: () => {
4074
+ console.log('📊 AdStage Debug: 현재 viewable 추적 상태', {
4075
+ trackedCount: ViewableEventTracker.viewableTracker.size,
4076
+ trackedItems: Array.from(ViewableEventTracker.viewableTracker)
4077
+ });
4078
+ }
4079
+ };
3056
4080
 
3057
4081
  const AdStageContext = createContext(null);
3058
4082
  function AdStageProvider({ children, config }) {
@@ -3139,5 +4163,9 @@ function useAdStageInstance() {
3139
4163
  // 버전 정보
3140
4164
  const SDK_VERSION = '2.0.0';
3141
4165
  const SUPPORTED_MODULES = ['ads', 'events', 'config'];
4166
+ // 브라우저 환경에서 전역 객체로 노출 (디버깅용)
4167
+ if (typeof window !== 'undefined') {
4168
+ window.AdStage = AdStage;
4169
+ }
3142
4170
 
3143
4171
  export { AdStage, AdStageProvider, SDK_VERSION, SUPPORTED_MODULES, useAdStageContext, useAdStageInstance };