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

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

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

        .header-profile {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            padding: 28px 24px 32px 24px;
            color: #ffffff;
        }

        .user-info {
            text-align: center;
            padding: 20px 0;
        }

        .user-name {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 8px;
            letter-spacing: -0.5px;
        }

        .user-phone {
            font-size: 15px;
            opacity: 0.9;
            font-weight: 500;
            letter-spacing: -0.2px;
        }

        .balance-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 32px 24px;
            margin: -40px 24px 24px 24px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
            text-align: center;
        }

        .balance-label {
            color: #868e96;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 12px;
            letter-spacing: -0.2px;
        }

        .balance-amount {
            color: #6366f1;
            font-size: 48px;
            font-weight: 700;
            letter-spacing: -1.5px;
            margin-bottom: 8px;
        }

        .balance-desc {
            color: #868e96;
            font-size: 13px;
            font-weight: 500;
            letter-spacing: -0.2px;
        }

        /* 퀵 메뉴 */
        .quick-menu {
            display: flex;
            justify-content: space-around;
            padding: 20px 16px;
            background: #fff;
            margin: 0 16px 16px;
            border-radius: 16px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
        }

        .quick-menu-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
            text-decoration: none;
            padding: 8px 12px;
            border-radius: 12px;
            transition: background 0.2s;
        }

        .quick-menu-item:active {
            background: #f5f5f5;
        }

        .quick-menu-icon {
            width: 48px;
            height: 48px;
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 22px;
        }

        .quick-menu-item span {
            font-size: 12px;
            font-weight: 600;
            color: #495057;
            letter-spacing: -0.3px;
        }

        .section {
            padding: 24px;
        }

        .section-title {
            color: #212529;
            font-size: 18px;
            font-weight: 700;
            margin-bottom: 16px;
            letter-spacing: -0.3px;
        }

        .transaction-list {
            list-style: none;
        }

        .transaction-item {
            background: #ffffff;
            border: 1px solid #e9ecef;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 12px;
            transition: all 0.2s ease;
        }

        .transaction-item:active {
            transform: scale(0.98);
            background: #f8f9fa;
        }

        .transaction-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }

        .transaction-reason {
            color: #495057;
            font-size: 15px;
            font-weight: 600;
            letter-spacing: -0.2px;
        }

        .transaction-points {
            color: #6366f1;
            font-size: 18px;
            font-weight: 700;
            letter-spacing: -0.3px;
        }

        .transaction-points.positive::before {
            content: '+';
        }

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

        .transaction-date {
            color: #adb5bd;
            font-size: 12px;
            font-weight: 500;
            letter-spacing: -0.2px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #868e96;
        }

        .empty-icon {
            font-size: 64px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        .empty-text {
            font-size: 15px;
            font-weight: 500;
            letter-spacing: -0.2px;
        }

        /* 품목 상세 */
        .transaction-item.clickable {
            cursor: pointer;
        }

        .item-detail {
            display: none;
            margin-top: 12px;
            padding-top: 12px;
            border-top: 1px solid #f1f3f5;
        }

        .item-detail.open {
            display: block;
        }

        .item-detail-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 6px 0;
            font-size: 13px;
        }

        .item-detail-name {
            color: #495057;
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-right: 8px;
        }

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

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

        .item-detail-loading {
            text-align: center;
            color: #adb5bd;
            font-size: 13px;
            padding: 8px 0;
        }

        .item-detail-hint {
            color: #adb5bd;
            font-size: 11px;
            margin-top: 4px;
        }

        /* 모바일 최적화 */
        @media (max-width: 480px) {
            .header-top {
                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-top">
            <div class="header-title">마이페이지</div>
            <div style="display: flex; align-items: center; gap: 8px;">
                <a href="/my-page" class="btn-logout">다른 번호</a>
                <a href="/my-page/kakao/start" class="btn-logout" style="display: flex; align-items: center; gap: 4px; background: #FEE500; color: #191919; padding: 6px 12px; border-radius: 8px; font-size: 12px; font-weight: 600;">
                    <svg width="12" height="12" 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>
                <a href="/logout" class="btn-logout" style="font-size: 12px; opacity: 0.7;">로그아웃</a>
            </div>
        </div>

        <div class="header-profile">
            <div class="user-info">
                <div class="user-name">{{ user.nickname }}님</div>
                <div class="user-phone">{{ user.phone[:3] }}-{{ user.phone[3:7] }}-{{ user.phone[7:] if user.phone|length > 7 else '' }}</div>
            </div>
        </div>

        <div class="balance-card">
            <div class="balance-label">보유 포인트</div>
            <div class="balance-amount">{{ "{:,}".format(user.mileage_balance) }}P</div>
            <div class="balance-desc">약국에서 1P = 1원으로 사용 가능</div>
        </div>

        <!-- 퀵 메뉴 -->
        <div class="quick-menu">
            <a href="/mypage" class="quick-menu-item">
                <div class="quick-menu-icon" style="background: #fef3c7;">🐾</div>
                <span>반려동물</span>
            </a>
            <a href="#" class="quick-menu-item" onclick="alert('준비중입니다'); return false;">
                <div class="quick-menu-icon" style="background: #dbeafe;">🎟️</div>
                <span>쿠폰함</span>
            </a>
            <a href="#" class="quick-menu-item" onclick="alert('준비중입니다'); return false;">
                <div class="quick-menu-icon" style="background: #fce7f3;">📦</div>
                <span>구매내역</span>
            </a>
            <a href="/mypage" class="quick-menu-item">
                <div class="quick-menu-icon" style="background: #ede9fe;">⚙️</div>
                <span>내정보</span>
            </a>
        </div>

        <div class="section">
            <div class="section-title">적립 내역</div>

            {% if transactions %}
            <ul class="transaction-list">
                {% for tx in transactions %}
                <li class="transaction-item {% if tx.transaction_id %}clickable{% endif %}"
                    {% if tx.transaction_id %}onclick="toggleDetail(this, '{{ tx.transaction_id }}')"{% endif %}>
                    <div class="transaction-header">
                        <div class="transaction-reason">
                            {% if tx.reason == 'CLAIM' %}
                            영수증 적립
                            {% elif tx.reason == 'USE' %}
                            포인트 사용
                            {% else %}
                            {{ tx.reason }}
                            {% endif %}
                        </div>
                        <div class="transaction-points {% if tx.points > 0 %}positive{% endif %}">
                            {{ "{:,}".format(tx.points) }}P
                        </div>
                    </div>
                    {% if tx.description %}
                    <div class="transaction-desc">{{ tx.description }}</div>
                    {% endif %}
                    <div class="transaction-date">
                        {{ tx.created_at }}
                        {% if tx.transaction_id %}
                        <span class="item-detail-hint">탭하여 품목 보기</span>
                        {% endif %}
                    </div>
                    <div class="item-detail" id="detail-{{ tx.transaction_id }}"></div>
                </li>
                {% endfor %}
            </ul>
            {% else %}
            <div class="empty-state">
                <div class="empty-icon">📭</div>
                <div class="empty-text">아직 적립 내역이 없습니다</div>
            </div>
            {% endif %}
        </div>
    </div>

    <script>
    const detailCache = {};

    async function toggleDetail(el, txId) {
        const detail = document.getElementById('detail-' + txId);
        if (!detail) return;

        // 이미 열려있으면 닫기
        if (detail.classList.contains('open')) {
            detail.classList.remove('open');
            return;
        }

        // 캐시에 있으면 바로 표시
        if (detailCache[txId]) {
            detail.innerHTML = detailCache[txId];
            detail.classList.add('open');
            return;
        }

        // 로딩 표시
        detail.innerHTML = '<div class="item-detail-loading">품목 조회 중...</div>';
        detail.classList.add('open');

        try {
            const res = await fetch('/admin/transaction/' + txId);
            const data = await res.json();

            if (data.success && data.items && data.items.length > 0) {
                let html = '';
                data.items.forEach(item => {
                    html += `<div class="item-detail-row">
                        <span class="item-detail-name">${item.name}</span>
                        <span class="item-detail-qty">${item.qty}개</span>
                        <span class="item-detail-price">${item.total.toLocaleString()}원</span>
                    </div>`;
                });
                detailCache[txId] = html;
                detail.innerHTML = html;
            } else {
                detail.innerHTML = '<div class="item-detail-loading">품목 정보를 불러올 수 없습니다</div>';
            }
        } catch (e) {
            detail.innerHTML = '<div class="item-detail-loading">조회 실패</div>';
        }
    }
    </script>

    <!-- AI 추천 바텀시트 -->
    <div id="rec-sheet" style="display:none;">
        <div id="rec-backdrop" style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.3);z-index:999;animation:recFadeIn .3s ease;"></div>
        <div id="rec-content" style="position:fixed;bottom:0;left:50%;transform:translateX(-50%);width:100%;max-width:420px;background:#fff;border-radius:24px 24px 0 0;padding:0 0 0;box-shadow:0 -8px 32px rgba(0,0,0,0.12);z-index:1000;animation:recSlideUp .4s cubic-bezier(.16,1,.3,1);touch-action:none;">
            <!-- 드래그 핸들 영역 -->
            <div id="rec-drag-handle" style="padding:12px 24px 0;cursor:grab;">
                <div style="width:40px;height:4px;background:#dee2e6;border-radius:2px;margin:0 auto 20px;"></div>
            </div>
            <div style="padding:0 24px 32px;">
                <div style="text-align:center;padding:8px 0 20px;">
                    <div id="rec-image-container" style="margin-bottom:20px;width:100%;display:flex;justify-content:center;">
                        <img id="rec-image" style="width:160px;height:auto;border:none;outline:none;display:none;" alt="추천 제품">
                        <div id="rec-emoji" style="font-size:56px;">💊</div>
                    </div>
                    <div id="rec-message" style="color:#343a40;font-size:16px;font-weight:500;line-height:1.6;letter-spacing:-0.3px;margin-bottom:16px;"></div>
                    <div id="rec-product" style="display:inline-block;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;font-size:14px;font-weight:600;padding:8px 20px;border-radius:20px;letter-spacing:-0.2px;"></div>
                </div>
                <div style="display:flex;gap:12px;padding-bottom:env(safe-area-inset-bottom,0);">
                    <button onclick="dismissRec('dismissed')" style="flex:1;padding:14px;border:1px solid #dee2e6;border-radius:14px;background:#fff;color:#868e96;font-size:15px;font-weight:600;cursor:pointer;font-family:inherit;">다음에요</button>
                    <button onclick="dismissRec('interested')" style="flex:2;padding:14px;border:none;border-radius:14px;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;font-size:15px;font-weight:600;cursor:pointer;font-family:inherit;">관심있어요!</button>
                </div>
            </div>
        </div>
    </div>
    <style>
        @keyframes recFadeIn { from{opacity:0} to{opacity:1} }
        @keyframes recSlideUp { from{transform:translate(-50%,100%)} to{transform:translate(-50%,0)} }
        @keyframes recSlideDown { from{transform:translate(-50%,0)} to{transform:translate(-50%,100%)} }
    </style>
    <script>
    let _recId = null;

    // ── 드래그 닫기 ──
    (function() {
        let startY = 0, currentY = 0, isDragging = false;
        const DISMISS_THRESHOLD = 80;

        function getContent() { return document.getElementById('rec-content'); }
        function getBackdrop() { return document.getElementById('rec-backdrop'); }

        function onStart(y) {
            const c = getContent();
            if (!c) return;
            isDragging = true;
            startY = y;
            currentY = 0;
            c.style.animation = 'none';
            c.style.transition = 'none';
        }
        function onMove(y) {
            if (!isDragging) return;
            const c = getContent();
            const b = getBackdrop();
            currentY = Math.max(0, y - startY); // 아래로만
            c.style.transform = 'translate(-50%, ' + currentY + 'px)';
            // 배경 투명도도 같이
            const opacity = Math.max(0, 0.3 * (1 - currentY / 300));
            b.style.background = 'rgba(0,0,0,' + opacity + ')';
        }
        function onEnd() {
            if (!isDragging) return;
            isDragging = false;
            const c = getContent();
            if (currentY > DISMISS_THRESHOLD) {
                // 충분히 내렸으면 닫기
                c.style.transition = 'transform .25s ease';
                c.style.transform = 'translate(-50%, 100%)';
                getBackdrop().style.transition = 'opacity .25s';
                getBackdrop().style.opacity = '0';
                setTimeout(function() {
                    document.getElementById('rec-sheet').style.display = 'none';
                    c.style.transition = '';
                    c.style.transform = '';
                }, 250);
                if (_recId) fetch('/api/recommendation/' + _recId + '/dismiss', {method:'POST'}).catch(function(){});
            } else {
                // 복귀
                c.style.transition = 'transform .25s cubic-bezier(.16,1,.3,1)';
                c.style.transform = 'translate(-50%, 0)';
                getBackdrop().style.transition = 'background .25s';
                getBackdrop().style.background = 'rgba(0,0,0,0.3)';
                setTimeout(function() { c.style.transition = ''; }, 250);
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            var el = document.getElementById('rec-content');
            if (!el) return;

            // 터치 (모바일)
            el.addEventListener('touchstart', function(e) {
                onStart(e.touches[0].clientY);
            }, {passive: true});
            el.addEventListener('touchmove', function(e) {
                if (isDragging && currentY > 0) e.preventDefault();
                onMove(e.touches[0].clientY);
            }, {passive: false});
            el.addEventListener('touchend', onEnd);

            // 마우스 (데스크톱 테스트용)
            el.addEventListener('mousedown', function(e) {
                if (e.target.tagName === 'BUTTON') return;
                onStart(e.clientY);
            });
            document.addEventListener('mousemove', function(e) {
                if (isDragging) onMove(e.clientY);
            });
            document.addEventListener('mouseup', onEnd);
        });
    })();

    // ── 추천 로드 ──
    window.addEventListener('load', function() {
        {% if user_id %}
        setTimeout(async function() {
            try {
                const res = await fetch('/api/recommendation/{{ user_id }}');
                const data = await res.json();
                if (data.success && data.has_recommendation) {
                    _recId = data.recommendation.id;
                    document.getElementById('rec-message').textContent = data.recommendation.message;
                    document.getElementById('rec-product').textContent = data.recommendation.product;
                    
                    // 제품 이미지 표시
                    if (data.recommendation.image) {
                        document.getElementById('rec-image').src = 'data:image/jpeg;base64,' + data.recommendation.image;
                        document.getElementById('rec-image').style.display = 'block';
                        document.getElementById('rec-emoji').style.display = 'none';
                    } else {
                        document.getElementById('rec-image').style.display = 'none';
                        document.getElementById('rec-emoji').style.display = 'block';
                    }
                    
                    document.getElementById('rec-sheet').style.display = 'block';
                    document.getElementById('rec-backdrop').onclick = dismissRec;
                }
            } catch(e) {
                console.error('[AI추천] 에러:', e);
            }
        }, 1500);
        {% endif %}
    });

    function dismissRec(action) {
        action = action || 'dismissed';
        const c = document.getElementById('rec-content');
        const b = document.getElementById('rec-backdrop');
        c.style.transition = 'transform .3s ease';
        c.style.transform = 'translate(-50%, 100%)';
        b.style.opacity = '0';
        b.style.transition = 'opacity .3s';
        setTimeout(function(){
            document.getElementById('rec-sheet').style.display='none';
            c.style.transition = '';
            c.style.transform = '';
        }, 300);
        if (_recId) fetch('/api/recommendation/' + _recId + '/dismiss', {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body: JSON.stringify({action: action})
        }).catch(function(){});
    }
    </script>
    <script>if('serviceWorker' in navigator){navigator.serviceWorker.register('/sw.js').catch(()=>{});}</script>
</body>
</html>
