<?php

declare(strict_types=1);

/**
 * 我的帳號主欄內容（兩欄式：layout-main + sidebar）。
 *
 * @var array{id:int,username:string,display_name:string,avatar_rel:string} $member
 * @var PDO|null $pdo
 * @var string $msgOk
 * @var string $msgBad
 * @var string $dbErr
 * @var string $csrf
 * @var array{enabled:bool,email:string,masked:string,verified:bool,verified_at:?string} $emailStatus
 * @var bool $showVerifiedBanner
 * @var bool $needsVerify
 * @var bool $verifyReverseOnly
 * @var bool $verifyTokenOnly
 * @var bool $verifyUsesToken
 * @var bool $verifyUsesReverse
 * @var bool $pendingApproval
 * @var string $joinedLabel
 * @var int|null $userNcoin
 * @var array{earned:int,reverted:int,net:int,count:int} $ncoinSummary
 * @var list<array<string,mixed>> $ncoinHistory
 * @var int $ncoinPage
 * @var int $ncoinPages
 * @var int $ncoinTotal
 * @var int $ncoinRangeFrom
 * @var int $ncoinRangeTo
 * @var Closure $buildNcoinPageUrl
 * @var list<int|null> $ncoinPagerItems
 * @var string|null $avatarUrl
 * @var string $disp
 * @var list<array{spa_store_id:int,store_name:string,display_address:string,is_approved:int,synced_at:string}> $memberStores
 * @var int $memberStoreCount
 * @var bool $hasNcoinTab
 * @var string $profileTab
 * @var list<string> $profileTabAllowed
 * @var Closure $buildProfileTabUrl
 * @var bool $ncoinTransferOpen 站方是否開放轉帳（後台設定）
 * @var bool $ncoinTransferEnabled 可執行轉帳（開放且有余額）
 * @var bool $ncoinTransferEligible
 * @var array{transfer_enabled?:bool,transfer_fee_pct?:int,transfer_reserve?:int} $ncoinTransferCfg
 * @var int $ncoinTransferMax
 * @var bool $fateAdminNavVisible
 */

$fateSkipLayoutTopbar = !empty($fateSkipLayoutTopbar);
if (!$fateSkipLayoutTopbar):
?>
<body>
    <header class="topbar">
        <div class="topbar-inner">
            <a class="brand" href="./"><?= htmlspecialchars($fateBrand['title_main'] ?? 'FATE', ENT_QUOTES, 'UTF-8') ?> <span><?= htmlspecialchars($fateBrand['title_sub'] ?? '店家探索', ENT_QUOTES, 'UTF-8') ?></span></a>
            <nav>
                <a href="./">探索列表</a>
                <a href="member_profile.php">我的帳號</a>
                <a href="logout.php">登出</a>
                <?php if (!empty($fateAdminNavVisible)): ?>
                    <a href="admin/">管理後台</a>
                <?php endif; ?>
            </nav>
        </div>
    </header>
<?php else: ?>
<div class="minimal-page">
<?php endif; ?>

    <div class="layout-shell layout-shell--detail">
        <div class="layout">
            <div class="layout-main">
                <nav class="store-bc" aria-label="麵包屑">
                    <a href="./">探索</a>
                    <span class="store-bc__sep" aria-hidden="true">/</span>
                    <span class="store-bc__cur">我的帳號</span>
                </nav>

                <header class="page-head page-head--compact member-profile-head">
                    <h1 class="page-title">我的帳號</h1>
                    <p class="sub">管理個人資料、<?= $ncoinNameEsc ?>歷程與轉帳<?php
                    if (!empty($verifyUsesToken) && !empty($verifyUsesReverse)): ?>；Email 驗證可收<strong>驗證信</strong>或<strong>回寄驗證</strong>（擇一）<?php
                    elseif (empty($verifyReverseOnly)): ?>；Email 驗證可用<strong>信內連結</strong>或<strong>6 位驗證碼</strong>（擇一）<?php
                    endif; ?>。</p>
                </header>

                <?php if ($showVerifiedBanner): ?>
                    <div class="member-profile-msg member-profile-msg--ok">Email 驗證成功！您已可正常使用本站功能。</div>
                <?php endif; ?>
                <?php if ($needsVerify && !empty($verifyUsesToken) && !empty($verifyUsesReverse)): ?>
                    <div class="member-profile-msg member-profile-msg--warn">您的 Email 尚未驗證：可收驗證信（連結或驗證碼），或依下方回寄驗證完成（擇一）。</div>
                <?php elseif ($needsVerify && empty($verifyReverseOnly)): ?>
                    <div class="member-profile-msg member-profile-msg--warn">您的 Email 尚未驗證：可點信內連結，或於下方輸入 6 位驗證碼；亦可重寄／更正信箱。</div>
                <?php elseif ($needsVerify && !empty($verifyReverseOnly)): ?>
                    <div class="member-profile-msg member-profile-msg--warn">您的 Email 尚未驗證：請依下方「回寄驗證」從註冊信箱寄出驗證信。</div>
                <?php endif; ?>
                <?php if ($pendingApproval): ?>
                    <div class="member-profile-msg member-profile-msg--warn">帳號尚待管理員審核，通過後即可登入。</div>
                <?php endif; ?>
                <?php if ($msgOk !== ''): ?>
                    <div class="member-profile-msg member-profile-msg--ok"><?= htmlspecialchars($msgOk, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endif; ?>
                <?php if ($msgBad !== ''): ?>
                    <div class="member-profile-msg member-profile-msg--bad"><?= htmlspecialchars($msgBad, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endif; ?>
                <?php if ($dbErr !== ''): ?>
                    <div class="member-profile-msg member-profile-msg--bad">資料庫：<?= htmlspecialchars($dbErr, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endif; ?>

                <section class="store-card-fate store-card-fate--block member-profile-card" aria-label="帳號摘要">
                    <div class="member-profile-summary">
                        <?php if ($avatarUrl !== null): ?>
                            <img class="member-profile-avatar" src="<?= htmlspecialchars($avatarUrl, ENT_QUOTES, 'UTF-8') ?>" alt="" width="96" height="96">
                        <?php else: ?>
                            <div class="member-profile-avatar member-profile-avatar--empty">尚無<br>頭像</div>
                        <?php endif; ?>
                        <div class="member-profile-summary__body">
                            <p class="member-profile-who">
                                <?= htmlspecialchars($disp, ENT_QUOTES, 'UTF-8') ?>
                                <?php if ($userNcoin !== null): ?>
                                    <span class="member-profile-ncoin">
                                        <span class="member-profile-ncoin__label"><?= $ncoinNameEsc ?></span>
                                        <span class="member-profile-ncoin__amount"><?= htmlspecialchars(number_format($userNcoin), ENT_QUOTES, 'UTF-8') ?></span>
                                    </span>
                                <?php endif; ?>
                            </p>
                            <p class="member-profile-meta">帳號 <code class="inline"><?= htmlspecialchars($member['username'], ENT_QUOTES, 'UTF-8') ?></code></p>
                            <p class="member-profile-meta">會員編號 <code class="inline">#<?= (int) $member['id'] ?></code>（轉帳時請提供此編號）</p>
                            <?php if ($joinedLabel !== ''): ?>
                                <p class="member-profile-meta">註冊 <?= htmlspecialchars($joinedLabel, ENT_QUOTES, 'UTF-8') ?></p>
                            <?php endif; ?>
                        </div>
                    </div>
                </section>

                <?php if ($pdo instanceof PDO): ?>
                    <section class="store-card-fate store-card-fate--block member-profile-card member-profile-tabs-wrap" aria-label="帳號管理">
                        <nav class="member-profile-tabs" role="tablist" aria-label="帳號分頁">
                            <a class="member-profile-tabs__btn<?= $profileTab === 'profile' ? ' is-active' : '' ?>"
                               role="tab"
                               id="member-tab-btn-profile"
                               href="<?= htmlspecialchars($buildProfileTabUrl('profile'), ENT_QUOTES, 'UTF-8') ?>"
                               aria-selected="<?= $profileTab === 'profile' ? 'true' : 'false' ?>"
                               aria-controls="member-tab-panel-profile"
                               tabindex="<?= $profileTab === 'profile' ? '0' : '-1' ?>">個人資料</a>
                            <a class="member-profile-tabs__btn<?= $profileTab === 'stores' ? ' is-active' : '' ?>"
                               role="tab"
                               id="member-tab-btn-stores"
                               href="<?= htmlspecialchars($buildProfileTabUrl('stores'), ENT_QUOTES, 'UTF-8') ?>"
                               aria-selected="<?= $profileTab === 'stores' ? 'true' : 'false' ?>"
                               aria-controls="member-tab-panel-stores"
                               tabindex="<?= $profileTab === 'stores' ? '0' : '-1' ?>">我推薦的店家<?php if (($memberStoreCount ?? 0) > 0): ?><span class="member-profile-tabs__badge"><?= (int) $memberStoreCount ?></span><?php endif; ?></a>
                            <?php if (!empty($hasFavoritesTab)): ?>
                                <a class="member-profile-tabs__btn<?= $profileTab === 'favorites' ? ' is-active' : '' ?>"
                                   role="tab"
                                   id="member-tab-btn-favorites"
                                   href="<?= htmlspecialchars($buildProfileTabUrl('favorites'), ENT_QUOTES, 'UTF-8') ?>"
                                   aria-selected="<?= $profileTab === 'favorites' ? 'true' : 'false' ?>"
                                   aria-controls="member-tab-panel-favorites"
                                   tabindex="<?= $profileTab === 'favorites' ? '0' : '-1' ?>">收藏技師<?php if (($memberFavoritesCount ?? 0) > 0): ?><span class="member-profile-tabs__badge"><?= (int) $memberFavoritesCount ?></span><?php endif; ?></a>
                            <?php endif; ?>
                            <?php if (!empty($hasSavedThreadsTab)): ?>
                                <a class="member-profile-tabs__btn<?= $profileTab === 'saved_threads' ? ' is-active' : '' ?>"
                                   role="tab"
                                   id="member-tab-btn-saved_threads"
                                   href="<?= htmlspecialchars($buildProfileTabUrl('saved_threads'), ENT_QUOTES, 'UTF-8') ?>"
                                   aria-selected="<?= $profileTab === 'saved_threads' ? 'true' : 'false' ?>"
                                   aria-controls="member-tab-panel-saved_threads"
                                   tabindex="<?= $profileTab === 'saved_threads' ? '0' : '-1' ?>">收藏文章<?php if (($memberSavedArticlesCount ?? 0) > 0): ?><span class="member-profile-tabs__badge"><?= (int) $memberSavedArticlesCount ?></span><?php endif; ?></a>
                            <?php endif; ?>
                            <?php if (!empty($hasNcoinTab)): ?>
                                <a class="member-profile-tabs__btn<?= $profileTab === 'ncoin' ? ' is-active' : '' ?>"
                                   role="tab"
                                   id="member-tab-btn-ncoin"
                                   href="<?= htmlspecialchars($buildProfileTabUrl('ncoin'), ENT_QUOTES, 'UTF-8') ?>"
                                   aria-selected="<?= $profileTab === 'ncoin' ? 'true' : 'false' ?>"
                                   aria-controls="member-tab-panel-ncoin"
                                   tabindex="<?= $profileTab === 'ncoin' ? '0' : '-1' ?>"><?= $ncoinNameEsc ?>歷程</a>
                                <a class="member-profile-tabs__btn<?= $profileTab === 'transfer' ? ' is-active' : '' ?>"
                                   role="tab"
                                   id="member-tab-btn-transfer"
                                   href="<?= htmlspecialchars($buildProfileTabUrl('transfer'), ENT_QUOTES, 'UTF-8') ?>"
                                   aria-selected="<?= $profileTab === 'transfer' ? 'true' : 'false' ?>"
                                   aria-controls="member-tab-panel-transfer"
                                   tabindex="<?= $profileTab === 'transfer' ? '0' : '-1' ?>"><?= $ncoinNameEsc ?>轉帳</a>
                            <?php endif; ?>
                        </nav>

                        <div class="member-profile-tab-panel<?= $profileTab === 'profile' ? ' is-active' : '' ?>"
                             role="tabpanel"
                             id="member-tab-panel-profile"
                             aria-labelledby="member-tab-btn-profile"
                             <?= $profileTab !== 'profile' ? 'hidden' : '' ?>>
                            <?php require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'member_profile_tab_profile.inc.php'; ?>
                        </div>

                        <div class="member-profile-tab-panel<?= $profileTab === 'stores' ? ' is-active' : '' ?>"
                             role="tabpanel"
                             id="member-tab-panel-stores"
                             aria-labelledby="member-tab-btn-stores"
                             <?= $profileTab !== 'stores' ? 'hidden' : '' ?>>
                            <?php require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'member_profile_tab_stores.inc.php'; ?>
                        </div>

                        <?php if (!empty($hasFavoritesTab)): ?>
                            <div class="member-profile-tab-panel<?= $profileTab === 'favorites' ? ' is-active' : '' ?>"
                                 role="tabpanel"
                                 id="member-tab-panel-favorites"
                                 aria-labelledby="member-tab-btn-favorites"
                                 <?= $profileTab !== 'favorites' ? 'hidden' : '' ?>>
                                <?php require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'member_profile_tab_favorites.inc.php'; ?>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($hasSavedThreadsTab)): ?>
                            <div class="member-profile-tab-panel<?= $profileTab === 'saved_threads' ? ' is-active' : '' ?>"
                                 role="tabpanel"
                                 id="member-tab-panel-saved_threads"
                                 aria-labelledby="member-tab-btn-saved_threads"
                                 <?= $profileTab !== 'saved_threads' ? 'hidden' : '' ?>>
                                <?php require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'member_profile_tab_saved_threads.inc.php'; ?>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($hasNcoinTab)): ?>
                            <div class="member-profile-tab-panel<?= $profileTab === 'ncoin' ? ' is-active' : '' ?>"
                                 role="tabpanel"
                                 id="member-tab-panel-ncoin"
                                 aria-labelledby="member-tab-btn-ncoin"
                                 <?= $profileTab !== 'ncoin' ? 'hidden' : '' ?>>
                                <?php require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'member_profile_tab_ncoin.inc.php'; ?>
                            </div>
                            <div class="member-profile-tab-panel<?= $profileTab === 'transfer' ? ' is-active' : '' ?>"
                                 role="tabpanel"
                                 id="member-tab-panel-transfer"
                                 aria-labelledby="member-tab-btn-transfer"
                                 <?= $profileTab !== 'transfer' ? 'hidden' : '' ?>>
                                <?php require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'member_profile_tab_transfer.inc.php'; ?>
                            </div>
                        <?php endif; ?>
                    </section>
                <?php endif; ?>
            </div>

            <?php require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'sidebar.php'; ?>
        </div>
    </div>
<?php if ($fateSkipLayoutTopbar): ?>
</div>
<?php endif; ?>
    <script src="./static/fate-avatar-crop.js?v=1"></script>
    <?php if (!empty($ncoinTransferOpen) && $profileTab === 'transfer' && !empty($ncoinTransferEligible)): ?>
    <script>
    (function () {
        var ncoinName = <?= json_encode($ncoinName, JSON_UNESCAPED_UNICODE) ?>;
        var feePct = <?= (int) ($ncoinTransferCfg['transfer_fee_pct'] ?? 0) ?>;
        var maxAmt = <?= (int) $ncoinTransferMax ?>;
        var amountEl = document.getElementById('transfer_amount');
        var previewEl = document.getElementById('transfer-fee-preview');
        var lookupBtn = document.getElementById('transfer-lookup-btn');
        var targetEl = document.getElementById('to_member_id');
        var resultEl = document.getElementById('transfer-lookup-result');

        function updatePreview() {
            if (!amountEl || !previewEl) return;
            var amt = parseInt(amountEl.value, 10) || 0;
            if (amt < 1) {
                previewEl.textContent = '';
                return;
            }
            var fee = feePct > 0 ? Math.floor(amt * feePct / 100) : 0;
            var net = amt - fee;
            if (amt > maxAmt) {
                previewEl.textContent = '超過可轉上限 ' + maxAmt.toLocaleString() + ' ' + ncoinName + '。';
                return;
            }
            if (net < 1) {
                previewEl.textContent = '扣除手續費後對方實收須至少 1 ' + ncoinName + '。';
                return;
            }
            previewEl.textContent = fee > 0
                ? '手續費 ' + fee.toLocaleString() + ' ' + ncoinName + '，對方實收 ' + net.toLocaleString() + ' ' + ncoinName + '。'
                : '對方實收 ' + net.toLocaleString() + ' ' + ncoinName + '（免手續費）。';
        }

        if (amountEl) {
            amountEl.addEventListener('input', updatePreview);
            updatePreview();
        }

        function runLookup() {
            if (!targetEl || !resultEl) return;
            var id = (targetEl.value || '').trim();
            resultEl.hidden = true;
            resultEl.className = 'member-profile-transfer-lookup-result';
            if (!id) return;
            resultEl.textContent = '查詢中…';
            resultEl.hidden = false;
            fetch('member_ncoin_transfer_lookup.php?member_id=' + encodeURIComponent(id), { credentials: 'same-origin' })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    resultEl.hidden = false;
                    if (data.ok && data.member) {
                        resultEl.className = 'member-profile-transfer-lookup-result member-profile-transfer-lookup-result--ok';
                        resultEl.textContent = '收款人：' + data.member.display_name + '（#' + data.member.id + '）';
                    } else {
                        resultEl.className = 'member-profile-transfer-lookup-result member-profile-transfer-lookup-result--bad';
                        resultEl.textContent = data.message || '查詢失敗。';
                    }
                })
                .catch(function () {
                    resultEl.hidden = false;
                    resultEl.className = 'member-profile-transfer-lookup-result member-profile-transfer-lookup-result--bad';
                    resultEl.textContent = '無法連線，請稍後再試。';
                });
        }

        if (lookupBtn) lookupBtn.addEventListener('click', runLookup);
        if (targetEl) targetEl.addEventListener('change', runLookup);
    })();
    </script>
    <?php endif; ?>
