<!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;
            -webkit-font-smoothing: antialiased;
        }

        .app-container {
            background: #ffffff;
            min-height: 100vh;
            max-width: 420px;
            margin: 0 auto;
        }

        .header {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            padding: 0 24px;
            height: 56px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0;
            z-index: 100;
        }

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

        .btn-back {
            color: rgba(255,255,255,0.9);
            font-size: 14px;
            font-weight: 500;
            text-decoration: none;
        }

        .form-section {
            padding: 32px 24px;
        }

        .form-title {
            font-size: 22px;
            font-weight: 700;
            color: #212529;
            letter-spacing: -0.5px;
            margin-bottom: 8px;
        }

        .form-desc {
            font-size: 14px;
            color: #868e96;
            line-height: 1.6;
            letter-spacing: -0.2px;
            margin-bottom: 32px;
        }

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

        .input-group label {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 14px;
            font-weight: 600;
            color: #495057;
            margin-bottom: 6px;
            letter-spacing: -0.2px;
        }

        .label-badge {
            font-size: 11px;
            font-weight: 600;
            padding: 2px 6px;
            border-radius: 4px;
            letter-spacing: -0.2px;
        }

        .badge-required {
            background: #fff0f0;
            color: #e03131;
        }

        .badge-optional {
            background: #f0f4ff;
            color: #6366f1;
        }

        .input-purpose {
            font-size: 12px;
            color: #868e96;
            margin-bottom: 8px;
            line-height: 1.5;
            letter-spacing: -0.2px;
            padding-left: 2px;
        }

        .input-group input {
            width: 100%;
            padding: 16px;
            border: 1.5px solid #e9ecef;
            border-radius: 12px;
            font-size: 16px;
            font-family: inherit;
            color: #212529;
            transition: border-color 0.2s;
            -webkit-appearance: none;
        }

        .input-group input:focus {
            outline: none;
            border-color: #6366f1;
        }

        .input-group input::placeholder {
            color: #adb5bd;
        }

        .phone-wrapper {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .phone-prefix {
            font-size: 16px;
            font-weight: 600;
            color: #495057;
            white-space: nowrap;
            padding: 16px 0 16px 4px;
        }

        .phone-wrapper input {
            flex: 1;
        }

        .birthday-wrapper {
            display: flex;
            gap: 8px;
        }

        .birthday-wrapper select {
            flex: 1;
            padding: 16px 12px;
            border: 1.5px solid #e9ecef;
            border-radius: 12px;
            font-size: 15px;
            font-family: inherit;
            color: #212529;
            background: #fff;
            -webkit-appearance: none;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23868e96' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 12px center;
        }

        .birthday-wrapper select:focus {
            outline: none;
            border-color: #6366f1;
        }

        .birthday-wrapper select.placeholder {
            color: #adb5bd;
        }

        /* 수집 항목 안내 카드 */
        .info-card {
            background: #f8f9fa;
            border-radius: 14px;
            padding: 20px;
            margin-bottom: 24px;
        }

        .info-card-title {
            font-size: 13px;
            font-weight: 700;
            color: #495057;
            margin-bottom: 12px;
            letter-spacing: -0.2px;
        }

        .info-item {
            display: flex;
            align-items: flex-start;
            gap: 10px;
            margin-bottom: 10px;
        }

        .info-item:last-child { margin-bottom: 0; }

        .info-item-icon {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 15px;
            flex-shrink: 0;
        }

        .info-item-icon.blue { background: rgba(99, 102, 241, 0.1); }
        .info-item-icon.green { background: rgba(16, 185, 129, 0.1); }
        .info-item-icon.pink { background: rgba(244, 63, 94, 0.1); }

        .info-item-text {
            flex: 1;
        }

        .info-item-label {
            font-size: 13px;
            font-weight: 600;
            color: #495057;
            letter-spacing: -0.2px;
        }

        .info-item-desc {
            font-size: 12px;
            color: #868e96;
            line-height: 1.5;
            letter-spacing: -0.2px;
        }

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

        .checkbox-container {
            display: flex;
            align-items: flex-start;
            gap: 10px;
            cursor: pointer;
        }

        .checkbox-container input[type="checkbox"] {
            width: 20px;
            height: 20px;
            margin-top: 2px;
            accent-color: #6366f1;
            flex-shrink: 0;
        }

        .consent-text {
            font-size: 14px;
            color: #495057;
            line-height: 1.5;
            letter-spacing: -0.2px;
        }

        .consent-text a {
            color: #6366f1;
            text-decoration: underline;
        }

        .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;
            font-family: inherit;
            cursor: pointer;
            letter-spacing: -0.3px;
            transition: all 0.2s ease;
            box-shadow: 0 4px 16px rgba(99, 102, 241, 0.3);
        }

        .btn-submit:active { transform: scale(0.98); }
        .btn-submit:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .divider {
            text-align: center;
            margin: 24px 0;
            position: relative;
        }

        .divider span {
            background: #fff;
            padding: 0 16px;
            color: #adb5bd;
            font-size: 13px;
            font-weight: 500;
            position: relative;
            z-index: 1;
        }

        .divider::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 1px;
            background: #e9ecef;
        }

        .btn-kakao {
            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;
            font-family: inherit;
            cursor: pointer;
            text-decoration: none;
            letter-spacing: -0.3px;
            transition: all 0.2s ease;
        }

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

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

        .alert.error { background: #fff5f5; color: #e03131; }
        .alert.success { background: #f0fdf4; color: #16a34a; }

        .footer {
            text-align: center;
            padding: 16px 24px 24px;
        }

        .footer a {
            color: #adb5bd;
            font-size: 12px;
            text-decoration: none;
        }

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

        .success-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            border-radius: 50%;
            margin: 0 auto 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            animation: scaleIn 0.4s ease;
        }

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

        @keyframes drawCheck {
            to { stroke-dashoffset: 0; }
        }

        .success-icon svg {
            width: 40px;
            height: 40px;
            fill: none;
            stroke: #ffffff;
            stroke-width: 3;
            stroke-linecap: round;
            stroke-linejoin: round;
        }

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

        .success-desc {
            font-size: 15px;
            color: #868e96;
            line-height: 1.6;
            margin-bottom: 32px;
        }

        .success-buttons {
            display: flex;
            gap: 12px;
        }

        .success-buttons a {
            flex: 1;
            padding: 16px;
            border-radius: 14px;
            font-size: 15px;
            font-weight: 600;
            text-decoration: none;
            text-align: center;
        }

        .btn-home-s { background: #f1f3f5; color: #495057; }
        .btn-mypage-s { background: linear-gradient(135deg, #6366f1, #8b5cf6); color: #fff; }

        @media (max-width: 480px) {
            .header {
                padding-top: env(safe-area-inset-top, 0px);
                height: calc(56px + env(safe-area-inset-top, 0px));
            }
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="header">
            <div class="header-title">회원가입</div>
            <a href="/" class="btn-back">홈으로</a>
        </div>

        <!-- 가입 폼 -->
        <div id="signupForm">
            <div class="form-section">
                <div class="form-title">회원가입</div>
                <div class="form-desc">
                    청춘약국 마일리지 서비스에 가입하세요.<br>
                    영수증 QR 스캔으로 구매금액의 3%를 적립할 수 있습니다.
                </div>

                <!-- 수집 항목 안내 카드 -->
                <div class="info-card">
                    <div class="info-card-title">수집 항목 및 이용 목적</div>
                    <div class="info-item">
                        <div class="info-item-icon blue">📱</div>
                        <div class="info-item-text">
                            <div class="info-item-label">전화번호 (필수)</div>
                            <div class="info-item-desc">마일리지 적립 계정의 고유 식별자로 사용됩니다. 포인트 조회 및 사용 시 본인 확인에 필요합니다.</div>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-icon green">👤</div>
                        <div class="info-item-text">
                            <div class="info-item-label">이름 (필수)</div>
                            <div class="info-item-desc">동명이인 구분 및 약국 방문 시 본인 확인에 사용됩니다.</div>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-icon pink">🎂</div>
                        <div class="info-item-text">
                            <div class="info-item-label">생년월일 (선택)</div>
                            <div class="info-item-desc">생일 기념 포인트 2배 적립 이벤트 및 연령대별 맞춤 건강 정보 제공에 활용됩니다.</div>
                        </div>
                    </div>
                </div>

                <form id="formSignup" onsubmit="return false;">
                    <div class="input-group">
                        <label for="name">
                            이름
                            <span class="label-badge badge-required">필수</span>
                        </label>
                        <div class="input-purpose">약국 방문 시 본인 확인 및 동명이인 구분에 사용됩니다.</div>
                        <input type="text" id="name" placeholder="이름을 입력하세요" autocomplete="name" required>
                    </div>

                    <div class="input-group">
                        <label for="phone">
                            전화번호
                            <span class="label-badge badge-required">필수</span>
                        </label>
                        <div class="input-purpose">마일리지 적립·조회의 고유 식별자로 사용됩니다.</div>
                        <div class="phone-wrapper">
                            <span class="phone-prefix">010 -</span>
                            <input type="tel" id="phone"
                                   placeholder="0000-0000"
                                   inputmode="numeric"
                                   maxlength="9"
                                   autocomplete="tel"
                                   required>
                        </div>
                    </div>

                    <div class="input-group">
                        <label>
                            생년월일
                            <span class="label-badge badge-optional">선택</span>
                        </label>
                        <div class="input-purpose">생일 기념 포인트 2배 적립 및 연령대별 맞춤 건강 정보 제공에 활용됩니다.</div>
                        <div class="birthday-wrapper">
                            <select id="birthYear" class="placeholder">
                                <option value="">년도</option>
                            </select>
                            <select id="birthMonth" class="placeholder">
                                <option value="">월</option>
                            </select>
                            <select id="birthDay" class="placeholder">
                                <option value="">일</option>
                            </select>
                        </div>
                    </div>

                    <div class="privacy-consent">
                        <label class="checkbox-container">
                            <input type="checkbox" id="privacyConsent" required>
                            <span class="consent-text">
                                <a href="/privacy" target="_blank">개인정보 수집·이용</a>에 동의합니다.
                                <br><span style="font-size:12px; color:#868e96;">전화번호, 이름(필수), 생년월일(선택)을 마일리지 적립·조회 및 맞춤 서비스 목적으로 수집합니다.</span>
                            </span>
                        </label>
                    </div>

                    <button type="submit" class="btn-submit" id="btnSubmit">가입하기</button>
                </form>

                <div class="divider"><span>또는</span></div>

                <a href="/my-page/kakao/start" class="btn-kakao">
                    <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>
                    카카오로 간편 가입
                </a>

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

                <div class="footer">
                    <a href="/privacy" target="_blank">개인정보 처리방침</a>
                </div>
            </div>
        </div>

        <!-- 성공 화면 -->
        <div id="successScreen" class="success-screen">
            <div class="success-icon">
                <svg viewBox="0 0 52 52">
                    <path d="M14.1 27.2l7.1 7.2 16.7-16.8"
                          style="stroke-dasharray:100; stroke-dashoffset:100; animation: drawCheck 0.6s 0.3s ease forwards;"/>
                </svg>
            </div>
            <div class="success-title">가입 완료!</div>
            <div class="success-desc" id="successDesc"></div>
            <div class="success-buttons">
                <a href="/" class="btn-home-s">홈으로</a>
                <a href="#" class="btn-mypage-s" id="btnMyPage">내 마일리지</a>
            </div>
        </div>
    </div>

    <script>
    if('serviceWorker' in navigator){navigator.serviceWorker.register('/sw.js').catch(()=>{});}

    // 생년월일 셀렉트 초기화
    (function() {
        var yearSel = document.getElementById('birthYear');
        var monthSel = document.getElementById('birthMonth');
        var daySel = document.getElementById('birthDay');
        var currentYear = new Date().getFullYear();

        for (var y = currentYear; y >= 1920; y--) {
            var opt = document.createElement('option');
            opt.value = y;
            opt.textContent = y + '년';
            yearSel.appendChild(opt);
        }
        for (var m = 1; m <= 12; m++) {
            var opt = document.createElement('option');
            opt.value = m < 10 ? '0' + m : '' + m;
            opt.textContent = m + '월';
            monthSel.appendChild(opt);
        }
        for (var d = 1; d <= 31; d++) {
            var opt = document.createElement('option');
            opt.value = d < 10 ? '0' + d : '' + d;
            opt.textContent = d + '일';
            daySel.appendChild(opt);
        }

        // 선택 시 placeholder 클래스 제거
        [yearSel, monthSel, daySel].forEach(function(sel) {
            sel.addEventListener('change', function() {
                if (this.value) this.classList.remove('placeholder');
                else this.classList.add('placeholder');
            });
        });
    })();

    const phoneInput = document.getElementById('phone');
    const form = document.getElementById('formSignup');
    const alertMsg = document.getElementById('alertMsg');

    // 자동 하이픈
    phoneInput.addEventListener('input', function(e) {
        let v = e.target.value.replace(/[^0-9]/g, '');
        if (v.length <= 4) e.target.value = v;
        else e.target.value = v.slice(0, 4) + '-' + v.slice(4, 8);
    });

    form.addEventListener('submit', async function(e) {
        e.preventDefault();

        const name = document.getElementById('name').value.trim();
        const raw = phoneInput.value.replace(/[^0-9]/g, '');
        const phone = '010' + raw;
        const consent = document.getElementById('privacyConsent').checked;

        // 생년월일 (선택)
        const birthYear = document.getElementById('birthYear').value;
        const birthMonth = document.getElementById('birthMonth').value;
        const birthDay = document.getElementById('birthDay').value;
        let birthday = null;
        if (birthYear && birthMonth && birthDay) {
            birthday = birthYear + '-' + birthMonth + '-' + birthDay;
        }

        if (!name) return showAlert('이름을 입력해주세요.');
        if (raw.length < 7) return showAlert('올바른 전화번호를 입력해주세요.');
        if (!consent) return showAlert('개인정보 수집·이용에 동의해주세요.');

        const btn = document.getElementById('btnSubmit');
        btn.disabled = true;
        btn.textContent = '가입 중...';

        try {
            const body = { name, phone };
            if (birthday) body.birthday = birthday;

            const res = await fetch('/api/signup', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(body)
            });
            const data = await res.json();

            if (data.success) {
                document.getElementById('signupForm').style.display = 'none';
                document.getElementById('successScreen').style.display = 'block';
                document.getElementById('successDesc').innerHTML =
                    '<strong>' + name + '</strong>님, 환영합니다!<br>이제 영수증 QR을 스캔하면 포인트가 적립됩니다.';
                document.getElementById('btnMyPage').href = '/my-page?phone=' + encodeURIComponent(phone);
            } else {
                showAlert(data.message || '가입 중 오류가 발생했습니다.');
                btn.disabled = false;
                btn.textContent = '가입하기';
            }
        } catch (err) {
            showAlert('서버 연결에 실패했습니다.');
            btn.disabled = false;
            btn.textContent = '가입하기';
        }
    });

    function showAlert(msg) {
        alertMsg.textContent = msg;
        alertMsg.style.display = 'block';
        setTimeout(() => { alertMsg.style.display = 'none'; }, 4000);
    }

    </script>
</body>
</html>
