summaryrefslogtreecommitdiff
path: root/src/lib/home/components/PopupBannerPromotion.jsx
blob: 1ef166f2fca1ede8902500a380663ed8340e879a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import { useRouter } from 'next/router';
import { useEffect, useState, useRef } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { getAuth } from '~/libs/auth';
import { X } from 'lucide-react';
import useDevice from '@/core/hooks/useDevice';

const PagePopupInformation = () => {
  const router = useRouter();
  const isHomePage = router.pathname === '/';
  const auth = getAuth();

  const [active, setActive] = useState(false);
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  const popupRef = useRef(null);
  const [position, setPosition] = useState({ x: 20, y: window.innerHeight - 170 });
  const dragStartPos = useRef({ x: 0, y: 0 });
  const isDragging = useRef(false);
  const isTouching = useRef(false);
  const { isDesktop } = useDevice();

  const [isSnapping, setIsSnapping] = useState(false); // 🔥 Penanda kapan transisi diaktifkan

  const [containerLeft, setContainerLeft] = useState(0);

  const updateContainerLeft = () => {
    const container = document.querySelector('.container');
    if (container) {
      const left = container.getBoundingClientRect().left;
      setContainerLeft(left);
    }
  };

  useEffect(() => {
    updateContainerLeft();

    window.addEventListener('resize', updateContainerLeft);
    window.addEventListener('scroll', updateContainerLeft);

    return () => {
      window.removeEventListener('resize', updateContainerLeft);
      window.removeEventListener('scroll', updateContainerLeft);
    };
  }, []);

  useEffect(() => {
    const getData = async () => {
      try {
        const res = await fetch(`/api/hero-banner?type=dragable-banner`);
        const { data } = await res.json();
        if (Array.isArray(data) && data.length > 0 && data[0]?.image) {
          setData(data);
        } else {
          setActive(false);
        }
      } catch (error) {
        console.error('Failed to fetch popup banner:', error);
      }
      setLoading(false);
    };

    if (isHomePage && !auth) {
      setActive(true);
      getData();
    }
  }, [isHomePage, auth]);

  useEffect(() => {
    const handleGlobalTouchMove = (e) => {
      if (isTouching.current) {
        e.preventDefault();
        isDragging.current = true;
        setIsSnapping(false); // 🔥 Matikan transisi saat drag

        let newX = e.touches[0].clientX - dragStartPos.current.x;
        let newY = e.touches[0].clientY - dragStartPos.current.y;

        const popupWidth = popupRef.current?.offsetWidth || 0;
        const popupHeight = popupRef.current?.offsetHeight || 0;
        const maxX = window.innerWidth - popupWidth - 20;
        const maxY = window.innerHeight - popupHeight - 20;
        const minX = -containerLeft;

        newX = Math.max(minX, Math.min(newX, maxX));
        newY = Math.max(0, Math.min(newY, maxY));

        setPosition({ x: newX, y: newY });
      }
    };

    const handleGlobalTouchEnd = () => {
      if (isDragging.current) {
        const popupWidth = popupRef.current?.offsetWidth || 0;
        const screenMiddle = window.innerWidth / 2;

        setIsSnapping(true); // 🔥 Aktifkan transisi saat snap

        if (position.x + popupWidth / 2 < screenMiddle) {
          // Snap ke kiri
          setPosition({ x: 20, y: position.y });
        } else {
          // Snap ke kanan
          setPosition({ x: window.innerWidth - popupWidth - 20, y: position.y });
        }
      }

      isTouching.current = false;
      isDragging.current = false;
    };

    window.addEventListener('touchmove', handleGlobalTouchMove, { passive: false });
    window.addEventListener('touchend', handleGlobalTouchEnd);

    return () => {
      window.removeEventListener('touchmove', handleGlobalTouchMove);
      window.removeEventListener('touchend', handleGlobalTouchEnd);
    };
  }, [position]);

  const handleMouseDown = (e) => {
    e.preventDefault();
    dragStartPos.current = { x: e.clientX - position.x, y: e.clientY - position.y };
    isDragging.current = false;
    setIsSnapping(false); // 🔥 Matikan transisi saat drag

    window.addEventListener('mousemove', handleMouseMove);
    window.addEventListener('mouseup', handleMouseUp);
  };

  const handleMouseMove = (e) => {
    isDragging.current = true;

    let newX = e.clientX - dragStartPos.current.x;
    let newY = e.clientY - dragStartPos.current.y;

    const popupWidth = popupRef.current?.offsetWidth || 0;
    const popupHeight = popupRef.current?.offsetHeight || 0;
    const maxX = window.innerWidth - popupWidth - 20;
    const maxY = window.innerHeight - popupHeight - 20;
    const minX = -containerLeft;

    newX = Math.max(minX, Math.min(newX, maxX));
    newY = Math.max(0, Math.min(newY, maxY));

    setPosition({ x: newX, y: newY });
  };

  const handleMouseUp = () => {
    if (isDragging.current) {
      const popupWidth = popupRef.current?.offsetWidth || 0;
      const screenMiddle = window.innerWidth / 2;

      setIsSnapping(true); // 🔥 Aktifkan transisi saat snap

      if (position.x + popupWidth / 2 < screenMiddle) {
        // Snap ke kiri
        setPosition({ x: 20, y: position.y });
      } else {
        // Snap ke kanan
        setPosition({ x: window.innerWidth - popupWidth - 20, y: position.y });
      }
    }

    window.removeEventListener('mousemove', handleMouseMove);
    window.removeEventListener('mouseup', handleMouseUp);

    isDragging.current = false;
  };

  const handleTouchStart = (e) => {
    if (e.touches.length === 1) {
      dragStartPos.current = { x: e.touches[0].clientX - position.x, y: e.touches[0].clientY - position.y };
      isDragging.current = false;
      isTouching.current = true;
      setIsSnapping(false); // 🔥 Matikan transisi saat drag
    }
  };

  if (!active || !data || loading || !Array.isArray(data) || !data[0]?.image) return null;

  const banner = data[0];

  if (isDesktop) {
    // ✅ RENDER UNTUK DESKTOP
    return (
      <div
        className="fixed z-[9999] pointer-events-none"
        style={{
          top: '40px',
          left: `${Math.max(containerLeft - 120, 0)}px`
        }}
      >
        <div
          ref={popupRef}
          className="relative pointer-events-auto"
          style={{
            transform: `translate(${position.x}px, ${position.y}px)`,
            cursor: 'grab',
            width: '85px',
          }}
          onMouseDown={handleMouseDown}
          onTouchStart={handleTouchStart}
        >
          <Link
            href={typeof banner.url === 'boolean' && banner.url === false ? '/' : banner.url}
            onClick={(e) => {
              if (isDragging.current) {
                e.preventDefault();
                isDragging.current = false;
              } else {
                setActive(false);
              }
            }}
            draggable="false"
          >
            <Image
              src={banner.image}
              alt={banner.name || 'popup'}
              width={85}
              height={85}
              className="w-full h-auto select-none"
              draggable="false"
            />
          </Link>

          <button
            onClick={() => setActive(false)}
            className="absolute -top-2 -right-2 z-10 p-1 bg-red-500 rounded-full hover:bg-red-600 transition-colors"
            aria-label="Close popup"
          >
            <X className="w-3 h-3 text-white" />
          </button>
        </div>
      </div>
    );
  }

  // ✅ RENDER UNTUK MOBILE
  return (
    <div className="fixed z-[9999] pointer-events-none"
      style={{
            top: '40px',
          }}>
      <div
        ref={popupRef}
        className={`absolute pointer-events-auto ${isSnapping ? 'transition-transform duration-300 ease-out' : ''}`}
        style={{
          transform: `translate(${position.x}px, ${position.y}px)`,
          cursor: 'grab',
          width: '85px',
        }}
        onMouseDown={handleMouseDown}
        onTouchStart={handleTouchStart}
      >
        <Link
          href={typeof banner.url === 'boolean' && banner.url === false ? '/' : banner.url}
          onClick={(e) => {
            if (isDragging.current) {
              e.preventDefault();
              isDragging.current = false;
            } else {
              setActive(false);
            }
          }}
          draggable="false"
        >
          <Image
            src={banner.image}
            alt={banner.name || 'popup'}
            width={85}
            height={85}
            className="w-full h-auto select-none"
            draggable="false"
          />
        </Link>

        <button
          onClick={() => setActive(false)}
          className="absolute -top-2 -right-2 z-10 p-1 bg-red-500 rounded-full hover:bg-red-600 transition-colors"
          aria-label="Close popup"
        >
          <X className="w-3 h-3 text-white" />
        </button>
      </div>
    </div>
  );

};

export default PagePopupInformation;