<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="#6366f1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="청춘약국">
    <link rel="manifest" href="/static/manifest.json">
    <link rel="apple-touch-icon" href="/static/icons/icon-192.png">
    <link rel="icon" type="image/png" sizes="192x192" href="/static/icons/icon-192.png">
    <title>포인트 적립 - 청춘약국</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Noto Sans KR', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: #f5f7fa;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 16px;
            -webkit-font-smoothing: antialiased;
        }

        .app-container {
            background: #ffffff;
            border-radius: 24px;
            max-width: 420px;
            width: 100%;
            box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            padding: 32px 24px 140px 24px;
            position: relative;
        }

        .header::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 120px;
            background: #ffffff;
            border-radius: 32px 32px 0 0;
        }

        .header-content {
            position: relative;
            z-index: 2;
        }

        .pharmacy-name {
            color: rgba(255, 255, 255, 0.9);
            font-size: 15px;
            font-weight: 500;
            letter-spacing: -0.2px;
            margin-bottom: 4px;
        }

        .header-title {
            color: #ffffff;
            font-size: 26px;
            font-weight: 700;
            letter-spacing: -0.5px;
        }

        .card {
            background: #ffffff;
            border-radius: 20px;
            padding: 24px;
            margin: -100px 24px 24px 24px;
            position: relative;
            z-index: 3;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
        }

        .receipt-amount {
            text-align: center;
            padding: 24px 0;
            border-bottom: 1px solid #f1f3f5;
            margin-bottom: 24px;
        }

        .amount-label {
            color: #868e96;
            font-size: 13px;
            font-weight: 500;
            margin-bottom: 8px;
            letter-spacing: -0.2px;
        }

        .amount-value {
            color: #212529;
            font-size: 32px;
            font-weight: 700;
            letter-spacing: -1px;
            margin-bottom: 16px;
        }

        .points-badge {
            display: inline-flex;
            align-items: center;
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: #ffffff;
            padding: 10px 20px;
            border-radius: 100px;
            font-size: 15px;
            font-weight: 600;
            letter-spacing: -0.3px;
        }

        .points-badge::before {
            content: '+ ';
            margin-right: 2px;
        }

        /* 구매 품목 리스트 */
        .items-section {
            margin-bottom: 20px;
        }

        .items-toggle {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px 0;
            cursor: pointer;
            border: none;
            background: none;
            width: 100%;
            color: #495057;
            font-size: 14px;
            font-weight: 600;
            letter-spacing: -0.2px;
        }

        .items-toggle .arrow {
            transition: transform 0.2s ease;
            font-size: 12px;
            color: #adb5bd;
        }

        .items-toggle.open .arrow {
            transform: rotate(180deg);
        }

        .items-list {
            display: none;
            border-top: 1px solid #f1f3f5;
        }

        .items-list.open {
            display: block;
        }

        .item-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #f8f9fa;
            font-size: 13px;
        }

        .item-row:last-child {
            border-bottom: none;
        }

        .item-name {
            color: #495057;
            flex: 1;
            font-weight: 500;
            letter-spacing: -0.2px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-right: 8px;
        }

        .item-qty {
            color: #868e96;
            margin-right: 12px;
            white-space: nowrap;
        }

        .item-price {
            color: #212529;
            font-weight: 600;
            white-space: nowrap;
        }

        .form-section {
            padding: 8px 0;
        }

        .input-group {
            margin-bottom: 20px;
        }

        .input-group label {
            display: block;
            color: #495057;
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 10px;
            letter-spacing: -0.2px;
        }

        .input-wrapper {
            position: relative;
        }

        .input-wrapper input {
            width: 100%;
            padding: 16px 18px;
            border: 2px solid #e9ecef;
            border-radius: 14px;
            font-size: 16px;
            font-weight: 500;
            transition: all 0.2s ease;
            letter-spacing: -0.3px;
            background: #f8f9fa;
        }

        .input-wrapper input:focus {
            outline: none;
            border-color: #6366f1;
            background: #ffffff;
            box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.08);
        }

        .input-wrapper input::placeholder {
            color: #adb5bd;
            font-weight: 400;
        }

        .privacy-consent {
            margin: 24px 0 8px 0;
        }

        .checkbox-container {
            display: flex;
            align-items: center;
            cursor: pointer;
            user-select: none;
            padding: 4px 0;
        }

        .checkbox-container input[type="checkbox"] {
            position: absolute;
            opacity: 0;
            cursor: pointer;
            height: 0;
            width: 0;
        }

        .checkmark {
            position: relative;
            height: 24px;
            width: 24px;
            background-color: #f8f9fa;
            border: 2px solid #e9ecef;
            border-radius: 6px;
            transition: all 0.2s ease;
            flex-shrink: 0;
        }

        .checkbox-container:hover .checkmark {
            border-color: #6366f1;
            background-color: #ffffff;
        }

        .checkbox-container input:checked ~ .checkmark {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            border-color: #6366f1;
        }

        .checkmark::after {
            content: "";
            position: absolute;
            display: none;
            left: 7px;
            top: 3px;
            width: 6px;
            height: 11px;
            border: solid white;
            border-width: 0 2px 2px 0;
            transform: rotate(45deg);
        }

        .checkbox-container input:checked ~ .checkmark::after {
            display: block;
        }

        .consent-text {
            margin-left: 12px;
            color: #495057;
            font-size: 14px;
            font-weight: 500;
            letter-spacing: -0.2px;
        }

        .btn-submit {
            width: 100%;
            padding: 18px;
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: #ffffff;
            border: none;
            border-radius: 14px;
            font-size: 17px;
            font-weight: 700;
            cursor: pointer;
            margin-top: 12px;
            letter-spacing: -0.3px;
            transition: all 0.2s ease;
            box-shadow: 0 4px 16px rgba(99, 102, 241, 0.24);
        }

        .btn-submit:active {
            transform: scale(0.98);
        }

        .btn-submit:disabled {
            background: #dee2e6;
            box-shadow: none;
            cursor: not-allowed;
        }

        .alert {
            margin-top: 16px;
            padding: 14px 16px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 500;
            display: none;
            letter-spacing: -0.2px;
        }

        .alert.error {
            background: #ffe3e3;
            color: #c92a2a;
        }

        /* 성공 화면 */
        .success-screen {
            display: none;
            padding: 24px;
            text-align: center;
        }

        .success-icon-wrap {
            width: 96px;
            height: 96px;
            margin: 40px auto 24px auto;
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            animation: scaleIn 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }

        .success-icon-wrap svg {
            width: 48px;
            height: 48px;
            stroke: #ffffff;
            stroke-width: 3;
            stroke-linecap: round;
            stroke-linejoin: round;
            fill: none;
            animation: checkmark 0.6s ease-in-out 0.2s both;
        }

        @keyframes scaleIn {
            0% { transform: scale(0); opacity: 0; }
            100% { transform: scale(1); opacity: 1; }
        }

        @keyframes checkmark {
            0% { stroke-dashoffset: 100; }
            100% { stroke-dashoffset: 0; }
        }

        .success-title {
            color: #212529;
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 12px;
            letter-spacing: -0.5px;
        }

        .success-points {
            color: #6366f1;
            font-size: 48px;
            font-weight: 700;
            margin: 24px 0 16px 0;
            letter-spacing: -1.5px;
        }

        .success-balance {
            color: #868e96;
            font-size: 15px;
            font-weight: 500;
            margin-bottom: 32px;
            letter-spacing: -0.2px;
        }

        .success-balance strong {
            color: #495057;
            font-weight: 700;
        }

        .button-group {
            display: flex;
            gap: 12px;
            margin-top: 24px;
        }

        .btn-secondary {
            flex: 1;
            padding: 16px;
            background: #f8f9fa;
            color: #495057;
            border: 2px solid #e9ecef;
            border-radius: 14px;
            font-size: 15px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            letter-spacing: -0.2px;
        }

        .btn-secondary:active {
            transform: scale(0.98);
            background: #e9ecef;
        }

        .btn-primary {
            flex: 1;
            padding: 16px;
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: #ffffff;
            border: none;
            border-radius: 14px;
            font-size: 15px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            letter-spacing: -0.2px;
        }

        .btn-primary:active {
            transform: scale(0.98);
        }

        /* 모바일 최적화 */
        @media (max-width: 480px) {
            body {
                padding: 0;
            }

            .app-container {
                border-radius: 0;
                min-height: 100vh;
            }

            .header {
                padding-top: 48px;
            }
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="header">
            <div class="header-content">
                <div class="pharmacy-name">청춘약국</div>
                <div class="header-title">포인트 적립</div>
            </div>
        </div>

        <!-- 적립 폼 -->
        <div id="claimForm">
            <div class="card">
                <div class="receipt-amount">
                    <div class="amount-label">구매 금액</div>
                    <div class="amount-value">{{ "{:,}".format(token_info.total_amount) }}원</div>
                    <div class="points-badge">{{ "{:,}".format(token_info.claimable_points) }}P 적립</div>
                </div>

                {% if sale_items %}
                <div class="items-section">
                    <button type="button" class="items-toggle" id="itemsToggle" onclick="toggleItems()">
                        <span>구매 품목 ({{ sale_items|length }}건)</span>
                        <span class="arrow">▼</span>
                    </button>
                    <div class="items-list" id="itemsList">
                        {% for item in sale_items %}
                        <div class="item-row">
                            <span class="item-name">{{ item.name }}</span>
                            <span class="item-qty">{{ item.qty }}개</span>
                            <span class="item-price">{{ "{:,}".format(item.total) }}원</span>
                        </div>
                        {% endfor %}
                    </div>
                </div>
                {% endif %}

                <form id="formClaim" class="form-section">
                    <div class="input-group">
                        <label for="phone">전화번호</label>
                        <div class="input-wrapper" style="display: flex; align-items: center; gap: 8px;">
                            <span style="font-size: 18px; font-weight: 600; color: #495057; white-space: nowrap; padding: 16px 0 16px 4px;">010 -</span>
                            <input type="tel" id="phone" name="phone"
                                   placeholder="0000-0000"
                                   inputmode="numeric"
                                   maxlength="9"
                                   autocomplete="tel"
                                   required
                                   style="flex: 1;">
                        </div>
                    </div>

                    <div class="input-group">
                        <label for="name">이름</label>
                        <div class="input-wrapper">
                            <input type="text" id="name" name="name"
                                   placeholder="이름을 입력하세요"
                                   autocomplete="name"
                                   required>
                        </div>
                    </div>

                    <div class="privacy-consent">
                        <label class="checkbox-container">
                            <input type="checkbox" id="privacyConsent" required>
                            <span class="checkmark"></span>
                            <span class="consent-text"><a href="/privacy" target="_blank" style="color: #6366f1; text-decoration: underline;">개인정보 수집·이용</a> 동의</span>
                        </label>
                    </div>

                    <button type="submit" class="btn-submit" id="btnSubmit">
                        포인트 적립하기
                    </button>
                </form>

                <div style="text-align: center; margin: 20px 0 16px 0; position: relative;">
                    <span style="background: #fff; padding: 0 16px; color: #adb5bd; font-size: 13px; font-weight: 500; position: relative; z-index: 1;">또는</span>
                    <div style="position: absolute; top: 50%; left: 0; right: 0; height: 1px; background: #e9ecef; z-index: 0;"></div>
                </div>

                <button type="button" onclick="kakaoLogin()"
                   style="display: flex; align-items: center; justify-content: center; gap: 8px;
                          width: 100%; padding: 16px; background: #FEE500; color: #191919;
                          border: none; border-radius: 14px; font-size: 16px; font-weight: 600;
                          letter-spacing: -0.3px; transition: all 0.2s ease; cursor: pointer;
                          box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                        <path d="M10 1C4.477 1 0 4.477 0 8.5c0 2.58 1.693 4.847 4.243 6.134l-1.084 3.97a.3.3 0 00.457.338L7.7 16.392c.75.112 1.52.17 2.3.17 5.523 0 10-3.477 10-7.562C20 4.477 15.523 1 10 1z" fill="#191919"/>
                    </svg>
                    카카오로 적립하기
                </button>

                <div class="alert error" id="alertMsg"></div>

                <div style="text-align: center; padding: 16px 0 8px;">
                    <a href="/privacy" target="_blank"
                       style="color: #adb5bd; font-size: 12px; text-decoration: none; letter-spacing: -0.2px;">
                        개인정보 처리방침
                    </a>
                </div>
            </div>
        </div>

        <!-- 성공 화면 -->
        <div id="successScreen" class="success-screen">
            <div class="success-icon-wrap">
                <svg viewBox="0 0 52 52" style="stroke-dasharray: 100; stroke-dashoffset: 100;">
                    <path d="M14.1 27.2l7.1 7.2 16.7-16.8"/>
                </svg>
            </div>
            <div class="success-title">적립 완료!</div>
            <div class="success-points" id="successPoints">0P</div>
            <div class="success-balance">
                총 포인트 <strong id="successBalance">0P</strong>
            </div>
            <div class="button-group">
                <a href="/" class="btn-secondary">홈으로</a>
                <a href="#" class="btn-primary" id="btnMyPage">내역 보기</a>
            </div>

            <!-- PWA 설치 유도 배너 -->
            <div id="installBanner" style="display:none; margin-top:24px; padding:16px 20px; background:#f8f9fa; border-radius:14px; text-align:left;">
                <div style="font-size:14px; font-weight:700; color:#212529; margin-bottom:6px; letter-spacing:-0.3px;">
                    홈 화면에 추가하면 더 편해요!
                </div>
                <div id="installDesc" style="font-size:13px; color:#868e96; line-height:1.6; letter-spacing:-0.2px;"></div>
                <button id="installBtn" style="display:none; margin-top:10px; width:100%; padding:12px; background:linear-gradient(135deg,#6366f1,#8b5cf6); color:#fff; border:none; border-radius:10px; font-size:14px; font-weight:600; cursor:pointer; letter-spacing:-0.2px;">
                    앱 설치하기
                </button>
            </div>
        </div>
    </div>

    <script>
        const tokenInfo = {
            transaction_id: '{{ token_info.transaction_id }}',
            nonce: '{{ request.args.get("t").split(":")[1] }}'
        };

        const form = document.getElementById('formClaim');
        const btnSubmit = document.getElementById('btnSubmit');
        const alertMsg = document.getElementById('alertMsg');
        const claimFormDiv = document.getElementById('claimForm');
        const successScreen = document.getElementById('successScreen');

        // 품목 토글
        function toggleItems() {
            const btn = document.getElementById('itemsToggle');
            const list = document.getElementById('itemsList');
            if (btn && list) {
                btn.classList.toggle('open');
                list.classList.toggle('open');
            }
        }

        // 뒷번호 자동 하이픈 (010 고정)
        const phoneInput = document.getElementById('phone');
        phoneInput.addEventListener('input', function(e) {
            let value = e.target.value.replace(/[^0-9]/g, '');
            if (value.length <= 4) {
                e.target.value = value;
            } else {
                e.target.value = value.slice(0, 4) + '-' + value.slice(4, 8);
            }
        });

        // 포커스 시 자동으로 전화번호 필드로
        phoneInput.focus();

        // 폼 제출
        form.addEventListener('submit', async function(e) {
            e.preventDefault();

            const phoneRaw = document.getElementById('phone').value.trim().replace(/[^0-9]/g, '');
            const phone = '010-' + phoneRaw.slice(0, 4) + '-' + phoneRaw.slice(4, 8);
            const name = document.getElementById('name').value.trim();
            const privacyConsent = document.getElementById('privacyConsent').checked;

            if (!phone || !name) {
                showAlert('전화번호와 이름을 모두 입력해주세요.');
                return;
            }

            if (!privacyConsent) {
                showAlert('개인정보 수집·이용에 동의해주세요.');
                return;
            }

            btnSubmit.disabled = true;
            btnSubmit.textContent = '처리 중...';
            alertMsg.style.display = 'none';

            try {
                const response = await fetch('/api/claim', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        transaction_id: tokenInfo.transaction_id,
                        nonce: tokenInfo.nonce,
                        phone: phone,
                        name: name,
                        privacy_consent: true
                    })
                });

                const data = await response.json();

                if (data.success) {
                    showSuccess(data.points, data.balance, phone);
                } else {
                    showAlert(data.message);
                    btnSubmit.disabled = false;
                    btnSubmit.textContent = '포인트 적립하기';
                }

            } catch (error) {
                showAlert('네트워크 오류가 발생했습니다.');
                btnSubmit.disabled = false;
                btnSubmit.textContent = '포인트 적립하기';
            }
        });

        function showAlert(msg) {
            alertMsg.textContent = msg;
            alertMsg.style.display = 'block';

            setTimeout(() => {
                alertMsg.style.display = 'none';
            }, 5000);
        }

        function showSuccess(points, balance, phone) {
            claimFormDiv.style.display = 'none';

            document.getElementById('successPoints').textContent = points.toLocaleString() + 'P';
            document.getElementById('successBalance').textContent = balance.toLocaleString() + 'P';
            document.getElementById('btnMyPage').href = '/my-page?phone=' + encodeURIComponent(phone);

            successScreen.style.display = 'block';
        }
    </script>
    <script src="https://t1.kakaocdn.net/kakao_js_sdk/2.7.4/kakao.min.js"
      integrity="sha384-DKYJZ8NLiK8MN4/C5P2dtSmLQ4KwPaoqAfyA/DfmOGfnSNqoARCbb2xl4Kh1v6Q"
      crossorigin="anonymous"></script>
    <script>
    // 카카오 JS SDK 초기화
    if (typeof Kakao !== 'undefined') {
        Kakao.init('3d1e098107157c5021b73bd5ab48600f');
    }

    function kakaoLogin() {
        if (typeof Kakao !== 'undefined' && Kakao.isInitialized()) {
            Kakao.Auth.authorize({
                redirectUri: 'https://mile.0bin.in/claim/kakao/callback',
                state: '{{ kakao_state }}'
            });
        } else {
            // JS SDK 로드 실패 시 서버 리다이렉트 폴백
            window.location.href = '/claim/kakao/start?t={{ request.args.get("t") }}';
        }
    }
    </script>
    <script>
    if('serviceWorker' in navigator){navigator.serviceWorker.register('/sw.js').catch(()=>{});}

    // PWA 설치 유도
    (function() {
        const banner = document.getElementById('installBanner');
        const desc = document.getElementById('installDesc');
        const btn = document.getElementById('installBtn');
        if (!banner) return;

        if (window.matchMedia('(display-mode: standalone)').matches || navigator.standalone) return;

        let deferredPrompt = null;
        window.addEventListener('beforeinstallprompt', function(e) {
            e.preventDefault();
            deferredPrompt = e;
            desc.textContent = '다음부터 QR 스캔하면 입력 없이 바로 적립됩니다.';
            btn.style.display = 'block';
            banner.style.display = 'block';
        });
        btn.addEventListener('click', function() {
            if (deferredPrompt) {
                deferredPrompt.prompt();
                deferredPrompt.userChoice.then(function() { banner.style.display = 'none'; });
            }
        });

        const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
        const isSafari = /Safari/.test(navigator.userAgent) && !/CriOS|FxiOS/.test(navigator.userAgent);
        if (isIOS && isSafari && !deferredPrompt) {
            desc.innerHTML = '하단 <strong style="color:#495057;">공유 버튼</strong> ➜ <strong style="color:#495057;">홈 화면에 추가</strong>를 누르면<br>다음부터 QR만 찍으면 바로 적립!';
            banner.style.display = 'block';
        }
    })();
    </script>
</body>
</html>
