<div class="toss-nav-wrapper">
    <div class="nav-container">
        <a href="/" class="brand-logo">
            <img src="https://snseyessell.com/img/logo.png" alt="SNS아이즈" onerror="this.src='https://via.placeholder.com/120x30?text=SNS-EYES';">
        </a>
        <div class="toss-header">
            <div class="toss-balance-card" id="toss-card-trigger" onclick="toggleTossMenu(event)">
                <div class="balance-info">
                    <div class="balance-label">{{ user['username'] }}님 잔액</div>
                    <div class="toss-balance-val">{{ user['balance_formatted'] }}원</div>
                </div>
                <div class="toss-charge-tag">내정보</div>
            </div>
            
            <div class="toss-dropdown" id="toss-dropdown">
                <a href="{{ page_url('addfunds') }}" class="toss-menu-item"><i class="fa-solid fa-wallet"></i>충전하기</a>
                <a href="{{ page_url('tickets') }}" class="toss-menu-item"><i class="fa-solid fa-comment-dots"></i>문의하기</a>
                <a href="{{ page_url('account') }}" class="toss-menu-item"><i class="fa-solid fa-user-gear"></i>설정</a>
                <div class="menu-divider"></div>
                <a href="{{ page_url('logout') }}" class="toss-menu-item logout"><i class="fa-solid fa-arrow-right-from-bracket"></i>로그아웃</a>
            </div>
            
            <button type="button" class="navbar-toggle collapsed toss-navbar-toggle hidden-lg hidden-md" data-toggle="collapse" data-target="#navbar" style="display: block;">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
    </div>
</div>

<div class="container main-content-wrapper">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">

            {% if user['username'] != 'tester' %}
            <style>
                /* 토스 스타일 UI */
                .toss-notice-wrapper { margin: 0 0 15px 0 !important; background: #fff; border-radius: 16px; padding: 10px 16px; box-shadow: 0 4px 16px rgba(0,0,0,0.04); border: 1px solid #f2f4f6; display: flex; align-items: center; position: relative; z-index: 10; }
                .toss-notice-badge { background: #eef2ff; color: #3182f6; padding: 2px 7px; border-radius: 6px; font-size: 11px; font-weight: 800; white-space: nowrap; margin-right: 10px; }
                .toss-notice-slider { height: 32px; overflow: hidden; flex: 1; position: relative; }
                .toss-notice-list { margin: 0; padding: 0; list-style: none; transition: transform 0.4s ease-in-out; }
                .toss-notice-list li { height: 32px; line-height: 32px; display: flex; justify-content: space-between; align-items: center; }
                .notice-content-area { display: flex; align-items: center; flex: 1; overflow: hidden; }
                .auto-icon-box { width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; margin-right: 2px; }
                .auto-icon-box img { width: 24px !important; height: 24px !important; object-fit: contain !important; display: block; margin-left: -2px; }
                .notice-text { font-size: 12.5px; color: #191f28; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1; }
                .notice-date { background: #f7f8fa; color: #8b95a1; font-size: 10px; padding: 3px 10px; border-radius: 50px; font-weight: 600; white-space: nowrap; margin-left: 10px; }
                .toss-charge-tag { background: #f2f4f6 !important; color: #4e5968 !important; padding: 4px 9px; border-radius: 8px; font-weight: 700; font-size: 11px; white-space: nowrap; }
                
                #order-form { padding-bottom: 80px; }

                /* 햄버거 메뉴 해결 */
                .toss-navbar-toggle { border: 1px solid #e5e8eb !important; border-radius: 8px !important; background: #fff !important; padding: 10px 12px !important; margin: 0 !important; cursor: pointer; float: right; margin-left: 15px !important;}
                .toss-navbar-toggle .icon-bar { background-color: #4e5968 !important; height: 2px !important; border-radius: 2px !important; margin-bottom: 4px !important; width: 18px !important; display: block; transition: 0.2s; }
                @media (min-width: 768px) {
                    .toss-navbar-toggle { border-color: #3182f6 !important; }
                    .toss-navbar-toggle .icon-bar { background-color: #3182f6 !important; }
                }

                .quick-chips-wrapper { display: flex; gap: 8px; margin-bottom: 25px; overflow-x: auto; padding-bottom: 8px; white-space: nowrap; }
                .quick-chip { background: #f2f7ff; color: #3182f6; border: 1px solid #d1dffd; padding: 8px 16px; border-radius: 20px; font-size: 13px; font-weight: 700; cursor: pointer; transition: 0.2s; flex-shrink: 0; }
                .recent-chip { background: #fff8e5; color: #f59a23; border: 1px solid #ffe8b5; }

                .submit-btn-fixed-wrapper { position: fixed; bottom: 0; left: 0; width: 100%; background: #fff; padding: 12px 20px 20px 20px; box-shadow: 0 -4px 20px rgba(0,0,0,0.06); z-index: 9999; border-top-left-radius: 24px; border-top-right-radius: 24px; display: flex; justify-content: center; }
                .submit-btn-fixed { width: 100%; max-width: 800px; height: 56px; background: #3182f6; color: #fff; border: none; border-radius: 16px; font-size: 18px; font-weight: 700; cursor: pointer; transition: transform 0.2s; }

                /* 실시간 서버 상태 박스 */
                .server-status-box { background: #f9fafb !important; border-radius: 20px !important; padding: 20px 24px !important; margin-bottom: 35px !important; display: flex; flex-direction: column; gap: 16px; border: 1px solid #f2f4f6 !important; }
                .server-title { font-size: 16px !important; font-weight: 700 !important; color: #333d4b !important; margin-bottom: 0 !important; }
                .server-bottom-row { display: flex !important; align-items: center !important; justify-content: space-between !important; border-top: 1px solid #eee; padding-top: 15px; margin-top: 4px; }
                .server-time { font-size: 13.5px !important; color: #8b95a1 !important; font-weight: 500 !important; }
                .status-pill { font-size: 12.5px !important; font-weight: 700 !important; color: #00a260 !important; background: #e2f7ec !important; padding: 6px 14px !important; border-radius: 10px !important; display: flex !important; align-items: center !important; gap: 4px !important; cursor: pointer; position: relative; }
                
                /* 예약작업 디자인 */
                #dripfeed .drip_arco { display: none !important; }
                #dripfeed .form-group__checkbox { display: flex !important; align-items: center !important; justify-content: space-between; background: #fff; padding: 18px 20px; border-radius: 16px; box-shadow: 0 2px 10px rgba(0,0,0,0.03); border: 1px solid #e5e8eb; margin-top: 15px; margin-bottom: 15px; width: 100%; }
                #dripfeed .form-group__label-title { order: 1; font-size: 0 !important; margin: 0 !important; flex: 1; cursor: pointer; }
                #dripfeed .form-group__label-title::before { content: '👋 자연스럽게 나누어 받기 (예약작업)'; font-size: 15px; font-weight: 800; color: #191f28; letter-spacing: -0.5px; display: block; }
                #dripfeed .form-group__checkbox-label { order: 2; margin: 0 !important; padding: 0 !important; display: flex !important; }
                #dripfeed input[type="checkbox"] { appearance: none; -webkit-appearance: none; width: 52px; height: 30px; background: #e5e8eb; border-radius: 30px; position: relative; cursor: pointer; outline: none; transition: 0.3s ease; margin: 0 !important; flex-shrink: 0; }
                #dripfeed input[type="checkbox"]::after { content: ''; position: absolute; top: 2px; left: 2px; width: 26px; height: 26px; background: #fff; border-radius: 50%; box-shadow: 0 2px 6px rgba(0,0,0,0.15); transition: 0.3s ease; }
                #dripfeed input[type="checkbox"]:checked { background: #3182f6; }
                #dripfeed input[type="checkbox"]:checked::after { transform: translateX(22px); }
                
                #dripfeed-options { background: #f9fafb; border-radius: 16px; padding: 20px; border: 1px solid #f2f4f6; margin-top: 5px; margin-bottom: 20px; }
                #dripfeed-options .form-control { height: 48px; border-radius: 12px; border: 1px solid #d1d6db; box-shadow: none; font-size: 15px; font-weight: 600; }
                #dripfeed-options .form-control:focus { border-color: #3182f6; background: #fff; }
                #dripfeed-options .form-group label { font-size: 0 !important; display: block; margin-bottom: 8px; }
                #dripfeed-options .form-group:nth-child(1) label::before { content: '몇 번 나누어서 주문할까요? (예: 5)'; font-size: 14px; color: #4e5968; font-weight: 700; }
                #dripfeed-options .form-group:nth-child(2) label::before { content: '몇 분마다 유입시킬까요? (예: 60 = 1시간)'; font-size: 14px; color: #4e5968; font-weight: 700; }
                #dripfeed-options .form-group:nth-child(3) label::before { content: '총 유입될 수량'; font-size: 14px; color: #4e5968; font-weight: 700; }

                .toss-dripfeed-guide { display: none; background: #f9fafb; border-radius: 16px; padding: 20px; margin-top: 15px; margin-bottom: 15px; border: 1px solid #f2f4f6; }
                #dripfeed.is-active .toss-dripfeed-guide { display: block; }
                
                #footer_kakao { display: none !important; }
            </style>

            <div class="toss-notice-wrapper">
                <div class="toss-notice-badge">공지</div>
                <div class="toss-notice-slider">
                    <ul class="toss-notice-list" id="toss-notice-list">
                        <li><div class="notice-content-area"><div class="auto-icon-box" data-text="인스타"></div><span class="notice-text">인스타 팔로워 단가 대폭 인하! 최저가 도전</span></div><div class="notice-date-area"><span class="notice-date">03.26</span></div></li>
                        <li><div class="notice-content-area"><div class="auto-icon-box" data-text="유튜브"></div><span class="notice-text">유튜브 조회수 로직 업데이트 완료 (속도 UP)</span></div><div class="notice-date-area"><span class="notice-date">03.25</span></div></li>
                        <li><div class="notice-content-area"><div class="auto-icon-box" data-text="좋아요"></div><span class="notice-text">전 서비스 좋아요 작업 속도 향상 중</span></div><div class="notice-date-area"><span class="notice-date">03.24</span></div></li>
                        <li><div class="notice-content-area"><div class="auto-icon-box" data-text="네이버"></div><span class="notice-text">네이버 플레이스 저장하기 최적화 업데이트 완료</span></div><div class="notice-date-area"><span class="notice-date">03.23</span></div></li>
                        <li><div class="notice-content-area"><div class="auto-icon-box" data-text="인스타"></div><span class="notice-text">인스타 한국인 서버 속도개선</span></div><div class="notice-date-area"><span class="notice-date">03.22</span></div></li>
                        <li><div class="notice-content-area"><div class="auto-icon-box" data-text="인스타"></div><span class="notice-text">인스타 팔로워 단가 대폭 인하! 최저가 도전</span></div><div class="notice-date-area"><span class="notice-date">03.26</span></div></li>
                    </ul>
                </div>
            </div>
            {% endif %}

            {% if error %}
            <div style="background: #fff0f0; border-radius: 20px; padding: 20px; margin-bottom: 25px; display: flex; align-items: flex-start; gap: 12px; box-shadow: 0 4px 16px rgba(229, 57, 53, 0.08);">
                <div style="font-size: 26px; line-height: 1;">🚨</div>
                <div>
                    <div style="font-size: 16px; font-weight: 800; color: #e53935; margin-bottom: 6px; letter-spacing: -0.5px;">앗, 주문에 실패했어요</div>
                    <div style="font-size: 14px; color: #c62828; font-weight: 500; word-break: keep-all; line-height: 1.4;">{{ errorText }}</div>
                </div>
            </div>
            {% endif %}

            {% if data and (data['id'] or data['order_id'] or data['service']) %}
            <div style="background: #e2f7ec; border-radius: 20px; padding: 24px; margin-bottom: 25px; box-shadow: 0 4px 20px rgba(0, 162, 96, 0.1);">
                <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 20px;">
                    <div style="font-size: 32px; line-height: 1;">✅</div>
                    <div>
                        <div style="font-size: 20px; font-weight: 800; color: #00a260; letter-spacing: -0.5px; margin-bottom: 2px;">주문이 완료되었어요!</div>
                        <div style="font-size: 13px; color: #008751; font-weight: 600;">주문번호: {{ data['id'] }}{{ data['order_id'] }}</div>
                    </div>
                </div>
                <div style="background: #ffffff; border-radius: 14px; padding: 18px; font-size: 14px; color: #333d4b; line-height: 1.8; box-shadow: 0 2px 10px rgba(0,0,0,0.02);">
                    <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                        <span style="color: #8b95a1; flex-shrink: 0;">서비스</span> 
                        <span style="font-weight: 700; text-align: right; max-width: 70%; word-break: keep-all;">{{ data['service'] }}{{ data['service_name'] }}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                        <span style="color: #8b95a1; flex-shrink: 0;">수량</span> 
                        <span style="font-weight: 700;">{{ data['quantity'] }}{{ data['amount'] }}{{ data['quantity_formatted'] }}개</span>
                    </div>
                    <div style="height: 1px; background: #f2f4f6; margin: 14px 0;"></div>
                    <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                        <span style="color: #8b95a1; flex-shrink: 0;">결제 금액</span> 
                        <span style="font-weight: 800; color: #3182f6; font-size: 15px;">{{ data['charge'] }}{{ data['price'] }}{{ data['charge_formatted'] }}원</span>
                    </div>
                    <div style="display: flex; justify-content: space-between;">
                        <span style="color: #8b95a1; flex-shrink: 0;">남은 잔액</span> 
                        <span style="font-weight: 700;">{{ data['balance'] }}{{ data['user_balance'] }}{{ data['balance_formatted'] }}원</span>
                    </div>
                </div>
            </div>
            {% endif %}
            
            <div class="well" style="background: #fff; border-radius: 24px; padding: 30px 20px; border:none; box-shadow: 0 4px 20px rgba(0,0,0,0.03);">
                <div style="margin-bottom: 30px; text-align: left; padding: 0 5px;">
                    <div class="welcome-msg" style="text-align: left; word-break: keep-all;">
                        <div style="font-size: 16px; font-weight: 700; color: #4e5968; letter-spacing: -0.5px; margin-bottom: 8px; display: flex; align-items: center; gap: 4px;">
                            <div><span style="color: #3182f6;">{{ user['username'] }}</span>님, 늘 행복하세요</div>
                            <div style="font-size: 16px; line-height: 1;">❤️</div>
                        </div>
                        <div style="font-size: 20px; font-weight: 800; color: #191f28; letter-spacing: -0.6px; line-height: 1.4; margin-bottom: 45px;">
                            편하게 서비스를 이용해보세요 😊
                        </div>
                    </div>

                    <div style="text-align: center; margin-bottom: 25px;">
                        <div style="font-size: 14px; color: #8b95a1; font-weight: 600; margin-bottom: 6px;">실시간 누적 주문량</div>
                        <div style="font-size: 38px; font-weight: 800; color: #191f28; letter-spacing: -1px; line-height: 1.2;"><span id='count_all_orders'>0</span>건</div>
                    </div>

                    <div class="server-status-box">
                        <div class="server-title">실시간 서버는 <span style="color: #00a260;">정상 운영 중이에요 🟢</span></div>
                        <div class="server-bottom-row">
                            <div class="server-time">현재 시간 <span id="span_now" style="font-weight: 700; color: #4e5968; margin-left: 4px;">00:00:00</span></div>
                            <div class="status-pill" onclick="toggleTooltip(event)">
                                서버상태 <span id="random-status" style="margin-left:2px;">98</span>%
                                <i class="fa-regular fa-circle-question" style="font-size: 13px; color: #4bce96;"></i>
                                <div class="mini-tooltip" id="status-tooltip" style="display:none; position: absolute; bottom: calc(100% + 12px); right: 0; background: #333d4b; color: #fff; font-size: 12px; padding: 12px 16px; border-radius: 12px; z-index: 1000; white-space: nowrap; width: max-content; box-shadow: 0 8px 20px rgba(0,0,0,0.15); font-weight: 500; border: none;">서버 상태가 80% 이상일 경우 안정적입니다.</div>
                            </div>
                        </div>
                    </div>

                    <div class="quick-chips-wrapper" id="chips-wrapper">
                        <button type="button" class="quick-chip" onclick="quickSelect('1', '8')">🇰🇷 인스타 한국인 팔로워</button>
                        <button type="button" class="quick-chip" onclick="quickSelect('1', '5')">❤ 인스타 한국인 좋아요</button>
                        <button type="button" class="quick-chip" onclick="quickSelect('3', '13')">🚀 유튜브 조회수</button>
                    </div>

                    <div class="instabox" style="margin-bottom: 30px;">
                        <div class="fust_box" style="display:flex; gap:10px; margin-bottom: 10px;">
                            <button type="button" class="btn-sns" id="sbtn1" onclick="go_box('1')" style="flex:1; border: 1px solid #f2f4f6; background: #fff; padding: 12px; border-radius: 16px; font-size: 13px;"><img src="https://i.ibb.co/Nd7LqTyK/image.png" style="width:18px; margin-right:5px;">인스타</button>
                            <button type="button" class="btn-sns" id="sbtn2" onclick="go_box('2')" style="flex:1; border: 1px solid #f2f4f6; background: #fff; padding: 12px; border-radius: 16px; font-size: 13px;"><img src="https://i.ibb.co/yFdNhQZp/image.png" style="width:18px; margin-right:5px;">페북</button>
                            <button type="button" class="btn-sns" id="sbtn3" onclick="go_box('3')" style="flex:1; border: 1px solid #f2f4f6; background: #fff; padding: 12px; border-radius: 16px; font-size: 13px;"><img src="https://i.ibb.co/HfdcvT8f/image.png" style="width:18px; margin-right:5px;">유튜브</button>
                        </div>
                        <div class="fust_box" style="display:flex; gap:10px;">
                            <button type="button" class="btn-sns" id="sbtn4" onclick="go_box('4')" style="flex:1; border: 1px solid #f2f4f6; background: #fff; padding: 12px; border-radius: 16px; font-size: 13px;"><img src="https://i.ibb.co/XQWxV9V/image.png" style="width:18px; margin-right:5px;">월관리📆</button>
                            <button type="button" class="btn-sns" id="sbtn5" onclick="go_box('5')" style="flex:1; border: 1px solid #f2f4f6; background: #fff; padding: 12px; border-radius: 16px; font-size: 13px;"><img src="https://i.ibb.co/fzKNTJZM/image.png" style="width:18px; margin-right:5px;">기기타</button>
                            <button type="button" class="btn-sns" id="sbtn6" onclick="go_box('6')" style="flex:1; border: 1px solid #f2f4f6; background: #fff; padding: 12px; border-radius: 16px; font-size: 13px;"><img src="https://i.ibb.co/Kz3yXW5c/image.png" style="width:18px; margin-right:5px;">네이버</button>
                        </div>
                    </div>

                    <form action="{{ page['url'] }}" method="post" id="order-form">
                        <div class="form-group">
                            <label style="font-size:15px; color:#4e5968; font-weight:600; margin-bottom:8px; display:block;">어떤 작업이 필요하신가요?</label>
                            <select class="form-control" id="orderform-category" name="OrderForm[category]" style="height: 50px; border-radius: 12px; border: 1px solid #e5e8eb;">
                                {% for categoryId,categoryName in categories %}
                                <option value="{{ categoryId }}">{{ categoryName }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="form-group" style="margin-top:20px;">
                            <label style="font-size:15px; color:#4e5968; font-weight:600; margin-bottom:8px; display:block;">원하시는 상세 서비스를 선택해주세요</label>
                            <select id="orderform-service" class="form-control" name="OrderForm[service]" style="height: 50px; border-radius: 12px; border: 1px solid #e5e8eb;"></select>
                        </div>
                        
                        <div class="form-group" style="margin-top: 25px;">
                            <label style="font-size:15px; color:#4e5968; font-weight:600; margin-bottom:8px; display:block;">서비스 설명 📝</label>
                            <div style="background: #f9fafb; border: 1px solid #e5e8eb; border-radius: 12px; padding: 18px; font-size: 13.5px; color: #4e5968; line-height: 1.6; word-break: keep-all;">
                                <div id="service_description">
                                    <div id="orderform-description">서비스를 선택하시면 상세 설명이 이곳에 표시됩니다.</div>
                                </div>
                            </div>
                        </div>

                        <div id="fields"></div>

                        <div id="safe-qty-container" style="display:none; gap: 6px; margin-top: 15px; margin-bottom: 15px; flex-wrap: wrap;">
                            <button type="button" onclick="addQty(50)" style="background: #f2f4f6; color: #4e5968; border: none; padding: 10px 14px; border-radius: 10px; font-size: 13px; font-weight: 700; cursor: pointer;">+50</button>
                            <button type="button" onclick="addQty(100)" style="background: #f2f4f6; color: #4e5968; border: none; padding: 10px 14px; border-radius: 10px; font-size: 13px; font-weight: 700; cursor: pointer;">+100</button>
                            <button type="button" onclick="addQty(500)" style="background: #f2f4f6; color: #4e5968; border: none; padding: 10px 14px; border-radius: 10px; font-size: 13px; font-weight: 700; cursor: pointer;">+500</button>
                            <button type="button" onclick="addQty(1000)" style="background: #f2f4f6; color: #4e5968; border: none; padding: 10px 14px; border-radius: 10px; font-size: 13px; font-weight: 700; cursor: pointer;">+1,000</button>
                            <button type="button" onclick="addQty(5000)" style="background: #f2f4f6; color: #4e5968; border: none; padding: 10px 14px; border-radius: 10px; font-size: 13px; font-weight: 700; cursor: pointer;">+5,000</button>
                            <button type="button" onclick="clearQty()" style="background:#fff; border:1px solid #e5e8eb; color: #4e5968; padding: 10px 14px; border-radius: 10px; font-size: 13px; font-weight: 700; cursor: pointer;">초기화</button>
                        </div>

                        <div id="custom-dripfeed-guide" class="toss-dripfeed-guide" style="display:none;">
                            <div style="font-size: 16px; font-weight: 800; color: #191f28; margin-bottom: 8px;">💡 예약작업은 이렇게 설정해요!</div>
                            <p style="font-size: 13.5px; color: #4e5968; line-height: 1.5; margin-bottom: 12px;">한 번에 모든 수량이 들어가지 않고, 일정한 시간 간격으로 나누어서 자연스럽게 주문이 들어가는 기능입니다.</p>
                            <div style="background: #ffffff; padding: 16px; border-radius: 12px; border: 1px solid #e5e8eb; font-size:13.5px;">
                                예) 1회 수량 10, 횟수 5회, 간격 60분 입력 시 <br>👉 <b>1시간마다 10개씩 총 5번 유입</b> (총 50개)
                            </div>
                        </div>

                        <div class="form-group" style="margin-top: 35px;">
                            <label style="font-size:15px; color:#4e5968; font-weight:600; margin-bottom:8px; display:block;">총 주문할 금액이에요</label>
                            <div style="position: relative;">
                                <input type="text" class="form-control" id="charge" name="OrderForm[charge]" readonly style="position: absolute; opacity: 0; z-index: -1; pointer-events: none;">
                                <input type="text" class="form-control" id="charge_dummy" readonly style="font-weight: 800; color: #3182f6; font-size: 24px; background: #f2f7ff !important; border: 1px solid #e1e9ff !important; height:60px !important; border-radius: 12px;">
                            </div>
                        </div>
                        <input type="hidden" name="_csrf" value="{{ csrftoken }}">
                        
                        <div class="submit-btn-fixed-wrapper">
                            <button type="submit" class="submit-btn-fixed">주문하기</button>
                        </div>

                    </form>
                </div>

            </div>
        </div>
    </div>
</div>

<script>
    const iconMap = {
        '인스타': 'https://i.ibb.co/Nd7LqTyK/image.png', '유튜브': 'https://i.ibb.co/HfdcvT8f/image.png',
        '페북': 'https://i.ibb.co/yFdNhQZp/image.png', '페이스북': 'https://i.ibb.co/yFdNhQZp/image.png',
        '네이버': 'https://i.ibb.co/Kz3yXW5c/image.png', '틱톡': 'https://i.ibb.co/JjWL6XVw/image.png',
        '카톡': 'https://i.ibb.co/m5py7FK9/image.png', '카카오': 'https://i.ibb.co/m5py7FK9/image.png',
        '엑스': 'https://i.ibb.co/gZ8CNTzT/image.png', '트위터': 'https://i.ibb.co/gZ8CNTzT/image.png',
        '텔레': 'https://i.ibb.co/W42wjvpt/image.png', '팔로워': 'https://i.ibb.co/XQWxV9V/image.png',
        '좋아요': 'https://i.ibb.co/fzKNTJZM/image.png'
    };

    function applyAutoIcons() {
        document.querySelectorAll('.auto-icon-box').forEach(box => {
            const text = box.getAttribute('data-text') || "";
            let imgSrc = iconMap['인스타']; 
            for (const key in iconMap) { if (text.includes(key)) { imgSrc = iconMap[key]; break; } }
            box.innerHTML = `<img src="${imgSrc}">`;
        });
    }
    applyAutoIcons(); 

    /* 공지사항 롤링 */
    (function() {
        var noticeList = document.getElementById('toss-notice-list');
        if (noticeList) {
            var noticeIdx = 0; var lineHeight = 32; 
            setInterval(function() {
                noticeIdx++; 
                noticeList.style.transition = 'transform 0.4s ease-in-out'; 
                noticeList.style.transform = 'translateY(-' + (noticeIdx * lineHeight) + 'px)'; 
                if (noticeIdx === 5) { 
                    setTimeout(function() { 
                        noticeList.style.transition = 'none'; 
                        noticeIdx = 0; 
                        noticeList.style.transform = 'translateY(0)'; 
                    }, 400); 
                }
            }, 3000);
        }
    })();

    function toggleTossMenu(e) { e.stopPropagation(); document.getElementById('toss-dropdown').style.display = (document.getElementById('toss-dropdown').style.display === 'block' ? 'none' : 'block'); }
    function toggleTooltip(e) { e.stopPropagation(); const t = document.getElementById('status-tooltip'); t.style.display = (t.style.display === 'block' ? 'none' : 'block'); }
    window.onclick = function(e) { if (!e.target.closest('#toss-card-trigger')) document.getElementById('toss-dropdown').style.display = 'none'; if (!e.target.closest('.status-pill')) document.getElementById('status-tooltip').style.display = 'none'; }
    
    function updateTime() { const n = new Date(); document.getElementById('span_now').innerText = n.toLocaleTimeString('ko-KR', {hour12: false}); }
    setInterval(updateTime, 1000); updateTime();
    
    function runPureCounter(elementId, startValue, endValue, durationMs) {
        var obj = document.getElementById(elementId); if (!obj) return;
        var startTime = null;
        function step(timestamp) {
            if (!startTime) startTime = timestamp;
            var progress = Math.min((timestamp - startTime) / durationMs, 1);
            var currentNum = Math.floor(progress * (endValue - startValue) + startValue);
            obj.innerHTML = currentNum.toLocaleString();
            if (progress < 1) { window.requestAnimationFrame(step); } else { obj.innerHTML = endValue.toLocaleString(); }
        }
        window.requestAnimationFrame(step);
    }
    var baseOrders = 13196947; var startDate = new Date("2024-01-01T00:00:00").getTime(); var now = new Date().getTime(); 
    var elapsed = (now - startDate) / (1000 * 60 * 60 * 24);
    runPureCounter('count_all_orders', 0, baseOrders + Math.floor(elapsed * 7662), 2500);

    var currentGlobalTabId = '1';

    function go_box(obj){
        currentGlobalTabId = obj; 
        var h = ""; $(".btn-sns").css("background","#ffffff"); $("#sbtn"+obj).css("background","#ffdc26");
        if(obj=="1"){ // 인스타
            h+= '<option value="911">📸릴스 알고리즘 노출</option>';
            h+= '<option value="647">✅셀프 추천탭 상위노출</option>';
            h+= '<option value="731">📌리그램 추천탭 노출(종합)</option>';
            h+= '<option value="816">📌추천탭 상위노출 30일(월관리)</option>';
            h+= '<option value="14">인스타그램 조회수🤳</option>';
            h+= '<option value="2">인스타그램 좋아요❤️</option>';
            h+= '<option value="1">인스타그램 팔로워🙋🏻</option>';
            h+= '<option value="10">인스타그램 댓글💬</option>';
            h+= '<option value="12">인스타그램 자동화♻</option>';
            h+= '<option value="5">인스타그램 인사이트📈</option>';
            h+= '<option value="32">인스타그램 계정관리📆</option>';
            h+= '<option value="54">인스타그램 DM📩</option>';
            h+= '<option value="51">✅추천탭 본인계정 월관리형(30일)</option>';
            h+= '<option value="29">📊 인스타 계정관리(최적화-30일)</option>';
            h+= '<option value="6">📌추천탭 리그램 월보장(30일)</option>';
            h+= '<option value="30">인스타그램 인기게시물(30일)</option>';    
        }
        else if(obj=="2"){ // 페북
            h+= '<option value="21">🟦페이스북 조회수🤳</option>';
            h+= '<option value="62">🟦 페이스북 좋아요❤️</option>';
            h+= '<option value="64">🟦 페이스북 팔로워👥</option>';
            h+= '<option value="8">🟦페이스북 (페이지)</option>';
            h+= '<option value="66">🟦 페이스북 그룹📁</option>';
            h+= '<option value="63">🟦 페이스북 댓글💬</option>';
            h+= '<option value="65">🟦 페이스북 공유♻</option>';
        }
        else if(obj=="3"){ // 유튜브
            h+= '<option value="7">🟥유튜브 동영상 조회수🤳</option>';
            h+= '<option value="17">🟥유튜브 동영상 좋아요❤️</option>';
            h+= '<option value="13">🟥유튜브 채널 구독자👥</option>';
            h+= '<option value="18">🟥유튜브 동영상 댓글💬</option>';
            h+= '<option value="55">🟥유튜브 동영상 시청시간🕣</option>';
            h+= '<option value="36">🟥유튜브 동영상 공유♻</option>';
            h+= '<option value="68">🟥유튜브 라이브 시청자👩🏻‍❤‍👨🏻</option>';
            h+= '<option value="69">🟥 유튜브 커뮤니티👨🏻</option>';    
            h+= '<option value="902">🆕 유튜브 추천</option>';   
        }
        else if(obj=="4"){ h+= '<option value="134">📊 인스타 계정관리(30일)</option>'; }
        else if(obj=="5"){ // 기타
            h+= '<option value="24">🎶 틱톡(종합)</option>';
            h+= '<option value="11">[✖︎]엑스(종합)</option>';    
            h+= '<option value="80">[@]스레드(종합)</option>';
            h+= '<option value="33">🟨카카오톡(종합)</option>';   
            h+= '<option value="238">아프리카TV(종합)</option>';   
            h+= '<option value="905">[™]텔레그램(종합)</option>'; 
        }
        else if(obj=="6"){ h+= '<option value="91">💚 네이버 플레이스 </option>'; }
        
        $("#orderform-category").html(h).trigger('change');
    }

    setInterval(function() {
        var rc = document.getElementById('charge');
        var dc = document.getElementById('charge_dummy');
        if(rc && dc && dc.dataset.last !== rc.value) {
            dc.dataset.last = rc.value;
            var clean = rc.value.replace(/[^0-9.,]/g, '').trim();
            dc.value = clean ? clean + ' 원' : '';
        }
    }, 50);

    document.addEventListener('change', function(e) {
        if(e.target && (e.target.id === 'orderform-category' || e.target.id === 'orderform-service')) {
            var state = { tab: currentGlobalTabId, cat: $("#orderform-category").val(), svc: $("#orderform-service").val() };
            localStorage.setItem('sns_final_state', JSON.stringify(state));
        }
    });

    $(document).ready(function() {
        var saved = localStorage.getItem('sns_final_state');
        if (saved) {
            try {
                var d = JSON.parse(saved);
                go_box(d.tab);
                setTimeout(function() {
                    $("#orderform-category").val(d.cat).trigger('change');
                    setTimeout(function() { $("#orderform-service").val(d.svc).trigger('change'); }, 400);
                }, 100);
            } catch(e) { go_box('1'); }
        } else { go_box('1'); }
    });

    /* 🔥 수동 계산용 자바스크립트 함수 */
    window.addQty = function(amount) {
        // 이름에 quantity가 포함된 인풋칸을 찾아서 값을 더해줍니다.
        var qtyInput = document.getElementById('orderform-quantity') || document.querySelector('input[name*="quantity" i]');
        if(qtyInput) {
            qtyInput.value = (parseInt(qtyInput.value) || 0) + amount;
            qtyInput.dispatchEvent(new Event('input', { bubbles: true }));
            qtyInput.dispatchEvent(new Event('change', { bubbles: true }));
        }
    };
    
    window.clearQty = function() {
        var qtyInput = document.getElementById('orderform-quantity') || document.querySelector('input[name*="quantity" i]');
        if(qtyInput) { 
            qtyInput.value = ''; 
            qtyInput.dispatchEvent(new Event('input', { bubbles: true }));
            qtyInput.dispatchEvent(new Event('change', { bubbles: true }));
        }
    };

    /* 🔥 버튼 표시 ON/OFF 스위치 (절대 삭제되지 않음) */
    setInterval(function() {
        // 화면에 quantity 입력칸이 있는지 검사
        var qtyInput = document.getElementById('orderform-quantity') || document.querySelector('input[name*="quantity" i]');
        var safeContainer = document.getElementById('safe-qty-container');
        
        if (qtyInput) {
            safeContainer.style.display = 'flex'; // 있으면 버튼을 보여줍니다.
        } else {
            safeContainer.style.display = 'none'; // 없으면 숨깁니다.
        }

        // 예약작업 디자인 감시
        if(document.getElementById('dripfeed')) {
             var checkbox = document.querySelector('#dripfeed input[type="checkbox"]');
             if(checkbox && checkbox.checked) { 
                 $("#dripfeed").addClass('is-active'); 
                 $("#custom-dripfeed-guide").show();
             } else {
                 $("#dripfeed").removeClass('is-active');
                 $("#custom-dripfeed-guide").hide();
             }
        }
    }, 200);

</script>