@page
@model Admin.Pages.Channel.List.WriteModel
@{
    ViewData["Title"] = "채널 등록";
}

<div class="container">
    <h3>@ViewData["Title"]</h3>
    <hr />

    <partial name="_StatusMessage" />

    <div class="alert alert-success" role="alert">
        채널 등록 시 YouTube API를 통해 자동 수집된 정보입니다.<br />
        관리자가 직접 등록 시 잘못된 결과가 발생할 수 있습니다.
    </div>

    <form id="fAdminWrite" method="post" accept-charset="utf-8" autocomplete="off">
        <div class="row mb-2">
            <label class="col-sm-2 col-form-label"><span class="text-danger">*</span> 회원(소유자)</label>
            <div class="col-sm-10">
                <input type="hidden" asp-for="Input.MemberID" id="memberIdHidden" />
                <div id="memberSelected" class="mb-1" style="display:none;">
                    <span class="badge bg-primary fs-6 fw-normal" id="memberBadge">
                        <span id="memberBadgeText"></span>
                        <button type="button" class="btn-close btn-close-white ms-2" aria-label="제거" id="memberRemoveBtn" style="font-size:0.6em;vertical-align:middle;"></button>
                    </span>
                </div>
                <div class="position-relative" id="memberSearchWrap">
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-search"></i></span>
                        <input type="text" class="form-control" id="memberSearchInput" placeholder="회원 ID, SID, 이메일로 검색" autocomplete="off" />
                    </div>
                    <div class="list-group position-absolute w-100 shadow" id="memberSearchResults" style="z-index:1050;display:none;max-height:300px;overflow-y:auto;"></div>
                </div>
            </div>
        </div>
        <div class="row mb-2">
            <label asp-for="Input.SID" class="col-sm-2 col-form-label"><span class="text-danger">*</span> SID</label>
            <div class="col-sm-10">
                <input type="text" asp-for="Input.SID" class="form-control" required minlength="24" maxlength="24" placeholder="중복 시 등록이 불가합니다. 24자" />
                <div class="text-muted form-text">
                    YouTube 채널 고유 ID (예: UCxxxxxxxxxxxxxxxxxxxxxx)
                </div>
            </div>
        </div>
        <div class="row mb-2">
            <label asp-for="Input.Name" class="col-sm-2 col-form-label"><span class="text-danger">*</span> 이름</label>
            <div class="col-sm-10">
                <input type="text" asp-for="Input.Name" class="form-control" required maxlength="200" />
            </div>
        </div>
        <div class="row mb-2">
            <label asp-for="Input.Handle" class="col-sm-2 col-form-label">핸들</label>
            <div class="col-sm-10">
                <div class="input-group">
                    <span class="input-group-text">@@</span>
                    <input type="text" asp-for="Input.Handle" class="form-control" maxlength="30" />
                </div>
            </div>
        </div>
        <div class="row mb-2">
            <label asp-for="Input.YouTubeUrl" class="col-sm-2 col-form-label"><span class="text-danger">*</span> YouTube 주소</label>
            <div class="col-sm-10">
                <input type="url" asp-for="Input.YouTubeUrl" class="form-control" required maxlength="255" />
                <div class="text-muted form-text">
                    YouTube 채널 주소 (예: https://www.youtube.com/channel/UCxxxxxxxxxxxxxxxxxxxxxx)
                </div>
            </div>
        </div>
        <div class="row mb-2">
            <label asp-for="Input.PlatformFeeRate" class="col-sm-2 col-form-label"><span class="text-danger">*</span> 수수료(%)</label>
            <div class="col-sm-10">
                <div class="row">
                    <div class="col col-md-auto">
                        <div class="input-group">
                            <input type="number" asp-for="Input.PlatformFeeRate" class="form-control" required min="0" max="100" step="0.1" />
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                </div>
                <span asp-validation-for="Input.PlatformFeeRate" class="text-danger"></span>
            </div>
        </div>
        <div class="row mb-2">
            <label asp-for="Input.IsVerified" class="col-sm-2 col-form-label">인증 여부</label>
            <div class="col-sm-10 align-content-center">
                <div class="form-check form-check-inline">
                    <input type="checkbox" asp-for="Input.IsVerified" class="form-check-input" />
                    <label class="form-check-label" asp-for="Input.IsVerified">인증합니다.</label>
                </div>
            </div>
        </div>
        <div class="row mb-2">
            <label asp-for="Input.IsActive" class="col-sm-2 col-form-label">사용 여부</label>
            <div class="col-sm-10 align-content-center">
                <div class="form-check form-check-inline">
                    <input type="checkbox" asp-for="Input.IsActive" class="form-check-input" />
                    <label class="form-check-label" asp-for="Input.IsActive">사용합니다.</label>
                </div>
            </div>
        </div>

        <hr />

        <div class="d-grid gap-2 text-center d-md-block">
            <button type="submit" class="btn btn-success">저장</button>
            <a href="/Channel/List" class="btn btn-secondary">취소</a>
        </div>

        <br />
    </form>
</div>

@section Scripts {
<script>
    $(function () {
        let timer = null;
        const $input = $('#memberSearchInput');
        const $results = $('#memberSearchResults');
        const $hidden = $('#memberIdHidden');
        const $selected = $('#memberSelected');
        const $badgeText = $('#memberBadgeText');
        const $searchWrap = $('#memberSearchWrap');

        function showSelected(id, email, name, sid) {
            const display = id + ' (' + email + ')' + (name ? ' ' + name : '') + (sid ? ' ' + sid : '');
            $badgeText.text(display);
            $hidden.val(id);
            $selected.show();
            $searchWrap.hide();
            $results.hide();
        }

        function clearSelected() {
            $hidden.val('');
            $selected.hide();
            $searchWrap.show();
            $input.val('').focus();
        }

        $('#memberRemoveBtn').on('click', function () {
            clearSelected();
        });

        $input.on('input', function () {
            clearTimeout(timer);
            const val = $(this).val().trim();
            if (val.length < 1) {
                $results.hide().empty();
                return;
            }
            timer = setTimeout(function () {
                $.getJSON('/Channel/List/Write?handler=SearchMember&keyword=' + encodeURIComponent(val), function (data) {
                    $results.empty();
                    if (data.length === 0) {
                        $results.append('<div class="list-group-item text-muted">검색 결과가 없습니다.</div>');
                    } else {
                        $.each(data, function (i, m) {
                            const text = m.id + ' (' + m.email + ')' + (m.name ? ' ' + m.name : '') + (m.sid ? ' ' + m.sid : '');
                            $results.append(
                                $('<a href="#" class="list-group-item list-group-item-action"></a>')
                                    .text(text)
                                    .on('click', function (e) {
                                        e.preventDefault();
                                        showSelected(m.id, m.email, m.name, m.sid);
                                    })
                            );
                        });
                    }
                    $results.show();
                });
            }, 300);
        });

        $(document).on('click', function (e) {
            if (!$(e.target).closest('#memberSearchWrap').length) {
                $results.hide();
            }
        });

        $input.on('focus', function () {
            if ($results.children().length > 0) {
                $results.show();
            }
        });

        // 폼 제출 시 회원 선택 여부 확인
        $('#fAdminWrite').on('submit', function (e) {
            if (!$hidden.val() || $hidden.val() === '0') {
                e.preventDefault();
                alert('회원(소유자)을 선택해주세요.');
                $input.focus();
            }
        });
    });
</script>
}