<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CutieBell - 알림 서비스</title>
    
    <meta name="theme-color" content="#ff7aa2">
    <link rel="icon" href="/favicon/favicon.ico">

	<!-- Bootstrap 5.3 -->
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

	<!-- Google Font (Pretendard & Noto Sans KR) -->
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard/dist/web/static/pretendard.css">
	<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;500;700;900&display=swap" rel="stylesheet">

	<!-- Font Awesome -->
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
	
	<link rel="stylesheet" href="/css/dangolmoaCommon.css?v=">

	<!-- PWA -->
	<link rel="manifest" href="/manifest/manifest.json">
	<link rel="icon" href="/images/cutiebell_logo_192.png">
	<link rel="apple-touch-icon" href="/images/cutiebell_logo_192.png">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="default">
	
    <style>
	
        :root {
            --primary-color: #E4B7C0;
            --primary-gradient: linear-gradient(135deg, #D8A0AD 0%, #C993A0 100%);
            --bg-color: #fff5f7;
            --text-main: #2b2b2b;
            --text-muted: #777777;
        }

        body {
            margin: 0;
            background-color: var(--bg-color);
            font-family: 'Pretendard', -apple-system, BlinkMacSystemFont, system-ui, Roboto, 'Helvetica Neue', 'Segoe UI', 'Apple SD Gothic Neo', 'Noto Sans KR', 'Malgun Gothic', sans-serif;
            color: var(--text-main);
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
        }

        .wrap {
            width: 100%;
            max-width: 440px;
            margin: 20px;
            padding: 40px 30px;
            background: #ffffff;
            border-radius: 28px;
            box-shadow: 0 10px 30px rgba(255, 122, 162, 0.12);
            text-align: center;
        }

        .browser-notice {
            background-color: #fff0f3;
            color: #d63384;
            font-size: 13px;
            padding: 10px 14px;
            border-radius: 12px;
            margin-bottom: 25px;
            font-weight: 500;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }

        .title {
            font-size: 28px;
            font-weight: 800;
            letter-spacing: -0.5px;
            color: #111;
			margin-top: 10px;;
        }

        .shop {
            color: #d63384;
            font-size: 20px;
            font-weight: 600;
        }

        .desc-box {
            margin: 20px 0 10px 0;
            background: #faf8f9;
            padding: 16px;
            border-radius: 16px;
            color: var(--text-muted);
            font-size: 15px;
            line-height: 1.6;
        }

        .desc-highlight {
            color: var(--text-main);
            font-weight: 600;
        }

        .form-label {
            font-size: 14px;
            color: #444;
            text-align: left;
            display: block;
            margin-bottom: 0px;
			margin-top: 10px;
        }

        .form-control {
            border-radius: 14px;
            padding: 8px 18px;
            border: 1.5px solid #eaeaea;
            background-color: #fcfcfc;
            font-size: 15px;
            transition: all 0.2s ease;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(255, 122, 162, 0.15);
            background-color: #fff;
        }

        .form-text {
            font-size: 15px;
            color: #333;
            text-align: left;
            margin-top: 5px;
        }
		
		.btn-rouge{
			background: #E4B7C0;
			color: #faf4f6;
		}
		
		.btn-rouge:hover {
			background:#C993A0;
			color: #9d4865;
		    filter: brightness(0.95);
			transform: translateY(-1px);
		}
		
    </style>
</head>
<body>

	<div class="wrap">

	    <!-- 로고 및 상점 정보 -->
	    <div class="logo-box">
	        <img src="/images/cutiebell_weblogo_210x192.png" 
				style="width: 100px; height: auto; border-radius: 50%; margin-top: 20px;"/> 
		</div>

	    <div class="title" style="margin-top: 10px;">CutieBell</div>

	    <!-- 안내 문구 박스 -->
	    <div class="desc-box">
	        <span class="desc-highlight">예약, 쿠폰, 이벤트</span> 소식을<br>가장 먼저 받아보세요!
	    </div>

		<!-- 브라우저 안내 배너 -->
		<div class="browser-notice">
		    <i class="fa-solid fa-circle-info"></i>
		    원활한 알림을 위해 Chrome, Edge, Safari를 이용해 주세요.
		</div>

	    <!-- 이메일 입력폼 -->
	    <div class="mb-4 text-start">

			<form id="adminForm">

				<label for="userEmail" class="form-label fw-bold">
				    📧 이메일 주소
				</label>
								
		        <input type="email" id="userEmail" name="userEmail" class="form-control"
		            placeholder="myemail@email.com" maxlength="32" required
		            autocomplete="email">
					
				<label for="userMobile" class="form-label fw-bold">
				    📱 핸드폰 번호
				</label>	
					
				<input type="tel" id="userMobile" name="userMobile" class="form-control"
				    placeholder="01012345678" maxlength="11"
				    inputmode="numeric" pattern="[0-9]{10,11}"
				    autocomplete="tel" required
				    oninput="this.value=this.value.replace(/[^0-9]/g,'')">
					
			</form>	

	        <div class="form-text">
	            알림 및 혜택 안내를 전송해 드립니다.
	        </div>
    	</div>

	    <!-- 액션 버튼 -->
	    <div>
			<button id="btnPush" type="button" class="btn btn-rouge" onclick="enablePush()">
			    알림 받기 신청
			</button>
	    </div>

	</div>

	<script>

	/**
	 * Web Push 등록
	 */
	async function enablePush() {

	    const button = document.getElementById("btnPush");

	    // 이미 처리 중이면 종료
	    if (button.disabled) {
	        return;
	    }

	    button.disabled = true;

	    const oldText = button.innerHTML;
	    button.innerHTML = "가입 중...";

	    try {

	        // validate input
	        const input = validateInput();

	        if (!input) {
	            return;
	        }

	        const userEmail = input.userEmail;
	        const userMobile = input.userMobile;

	        // Notification 지원 여부
	        if (!("Notification" in window)) {
	            await diagnosis("Notification 미지원");
	            return;
	        }

	        // Service Worker 지원 여부
	        if (!("serviceWorker" in navigator)) {
	            await diagnosis("ServiceWorker 미지원");
	            return;
	        }

	        // 알림 권한 요청
	        const permission = await Notification.requestPermission();

	        if (permission !== "granted") {
	            await diagnosis("Permission : " + permission);
	            return;
	        }

	        // Service Worker 준비
	        const registration = await navigator.serviceWorker.ready;

	        // VAPID Public Key
	        const publicKey = "BBfVwlsWCWV5W46LaMXA2BYf5eBkg4Sm31WrRQ-WshLYaCVnaeGl5naJPcxuSxM4mEb0TQRcw8ojIsY6AZ9bMxc";

	        // 기존 Push 구독 확인
	        let subscription =
	            await registration.pushManager.getSubscription();

	        // 구독 생성
	        if (!subscription) {

	            try {

	                subscription =
	                    await registration.pushManager.subscribe({

	                        userVisibleOnly: true,

	                        applicationServerKey:
	                            urlBase64ToUint8Array(publicKey)

	                    });

	            } catch (e) {

	                await diagnosis(e);
	                return;

	            }

	        }

	        const push = subscription.toJSON();

	        if (location.hostname === "localhost") {
	            console.log(push);
	        }

	        // 서버 전송 데이터
	        const request = {

	            userEmail: userEmail,
	            userMobile: userMobile,
	            endpoint: push.endpoint,

	            keys: {
	                p256dh: push.keys.p256dh,
	                auth: push.keys.auth
	            }

	        };

	        // 서버 저장
	        const response =
	            await fetch("/api/push/subscribe", {

	                method: "POST",

	                headers: {
	                    "Content-Type": "application/json"
	                },

	                body: JSON.stringify(request)

	            });

	        if (!response.ok) {
	            throw new Error("Push 구독 저장 실패");
	        }

	        // DB 저장 결과
	        const result = await response.json();

	        if (result.result === "INSERT") {

	            alert("알림 등록이 완료되었습니다.");

	        } else if (result.result === "UPDATE") {

	            alert("이미 등록되어 있어 정보를 갱신했습니다.");

	        } else {

	            alert("알림 등록이 완료되었습니다.");

	        }

	    } catch (e) {

	        console.error(e);

	        await diagnosis(e);

	    } finally {

	        button.disabled = false;
	        button.innerHTML = oldText;

	    }

	}

	</script>
	
<script>

	/** 입력값 검사 */
	function validateInput() {

	    const emailInput = document.getElementById("userEmail");
	    const userEmail = emailInput.value.trim();

	    if (userEmail === "") {
	        alert("이메일을 입력하세요.");
	        emailInput.focus();
	        return null;
	    }

	    const emailRegex =
	        /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;

	    if (!emailRegex.test(userEmail)) {
	        alert("올바른 이메일 주소를 입력하세요.");
	        emailInput.focus();
	        return null;
	    }

	    const mobileInput = document.getElementById("userMobile");

	    mobileInput.value =
	        mobileInput.value.replace(/[^0-9]/g, "");

	    const userMobile = mobileInput.value;

	    if (userMobile === "") {
	        alert("휴대폰 번호를 입력하세요.");
	        mobileInput.focus();
	        return null;
	    }

	    if (!/^01[016789]\d{7,8}$/.test(userMobile)) {
	        alert("올바른 휴대폰 번호를 입력하세요. (예: 01012345678)");
	        mobileInput.value = "";
	        mobileInput.focus();
	        return null;
	    }

	    return {
	        userEmail,
	        userMobile
	    };
	}	
</script>

<script>
	/** VAPID Key 변환  */
    function urlBase64ToUint8Array(base64String) {

        const padding = "=".repeat((4 - base64String.length % 4) % 4);
        const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
        const rawData = window.atob(base64);

        return Uint8Array.from([...rawData].map(c => c.charCodeAt(0)));
    }
</script>

<script>
	
	/** Service Worker 등록 */
	if ("serviceWorker" in navigator) {
	    window.addEventListener("load", async () => {
	        try {
	            const registration = await navigator.serviceWorker.register("/sw.js");
	            console.log("SW 등록 성공", registration);
				 
	        } catch (e) {
	            console.error("SW 등록 실패", e);
	        }
	    });
	}
</script>

<script>
	
	async function diagnosis(error) {

	    let msg = "";

	    msg += "Notification : " + ("Notification" in window) + "\n";
	    msg += "ServiceWorker : " + ("serviceWorker" in navigator) + "\n";
	    msg += "PushManager : " + ("PushManager" in window) + "\n";

	    if ("Notification" in window) {
	        msg += "Permission : " + Notification.permission + "\n";
	    }

	    // ===== 브라우저 정보 =====
	    msg += "\nBrowser\n";
	    msg += navigator.userAgent + "\n";

	    msg += "Vendor : " + navigator.vendor + "\n";
	    msg += "Platform : " + navigator.platform + "\n";

	    // ===== 접속 정보 =====
	    msg += "\nURL\n";
	    msg += "URL : " + location.href + "\n";
	    msg += "Origin : " + location.origin + "\n";
	    msg += "Referrer : " + document.referrer + "\n";

	    try {

	        const reg = await navigator.serviceWorker.ready;

	        msg += "\nSW : OK\n";

	        if ("PushManager" in window && reg.pushManager) {

	            const sub = await reg.pushManager.getSubscription();

	            msg += "Subscription : " + (sub ? "YES" : "NO") + "\n";

	        } else {

	            msg += "Subscription : PushManager 미지원\n";

	        }

	    } catch (e) {

	        msg += "SW : FAIL\n";
	        msg += e.toString() + "\n";

	    }

	    msg += "\nError\n";
	    msg += error.toString();

	    console.log(msg);
	    alert(msg);

	}

</script>

</body>
</html>