{{-- resources/views/library/book/read.blade.php
     全站共用阅读器。供 anthology/read 和 tipitaka/read 路由使用。
     重构：改为 @extends('layouts.reader')，移除 CDN 引入，JS 提取为模块。
--}}
@extends('layouts.reader')

@section('title', $book['title'])

@section('body-class', session('theme', 'light') . '-mode')

{{-- 术语抽屉（所有阅读页统一使用 wiki.term-drawer） --}}
@push('scripts')
@vite(['resources/js/modules/term-tooltip.js','resources/js/reader.js'])
@endpush

@section('reader-content')

{{-- 术语抽屉 --}}
<x-wiki.term-drawer />

{{-- Navbar --}}
<header class="navbar navbar-expand-md navbar-light d-print-none">
    <div class="container-xl">
        <button class="navbar-toggler"
            type="button"
            data-bs-toggle="offcanvas"
            data-bs-target="#tocDrawer"
            aria-controls="tocDrawer">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="navbar-brand d-flex flex-column lh-1">
            @if(!empty($book['anthology']))
            <small class="text-muted" style="font-size:.75rem;">
                <a href="{{ route('library.anthology.show', $book['anthology']['id']) }}"
                    class="text-muted text-decoration-none">
                    {{ $book['anthology']['title'] }}
                </a>
            </small>
            @endif
        </div>

        <div class="navbar-nav flex-row order-md-last align-items-center">

            {{-- 编辑器按钮 --}}
            @if(!empty($editor_link))
            <div class="nav-item me-2">
                <a href="{{ $editor_link }}" target="_blank" class="nav-link">
                    <i class="ti ti-pencil me-1 d-none d-md-inline"></i>
                    <span class="d-none d-md-inline">{{ __('library.editor') }}</span>
                    <i class="ti ti-pencil d-md-none"></i>
                </a>
            </div>
            @endif

            {{-- 设置 --}}
            <div class="nav-item me-2">
                <a href="#"
                    class="nav-link"
                    data-bs-toggle="modal"
                    data-bs-target="#settingsModal">
                    <i class="ti ti-settings me-1 d-none d-md-inline"></i>
                    <span class="d-none d-md-inline">{{ __('library.settings') }}</span>
                    <i class="ti ti-settings d-md-none"></i>
                </a>
            </div>

            {{-- 版本切换：所有设备统一触发 offcanvas，放在设置右边 --}}
            @if(!empty($channels))
            <div class="nav-item me-2">
                <a href="#" class="nav-link"
                    data-bs-toggle="offcanvas"
                    data-bs-target="#channelDrawer">
                    <i class="ti ti-stack-2 me-1 d-none d-md-inline"></i>
                    <span class="d-none d-md-inline">{{ __('library.versions') }}</span>
                    <i class="ti ti-stack-2 d-md-none"></i>
                </a>
            </div>
            @endif

            {{-- 夜间模式 --}}
            <div class="nav-item">
                <a href="#" class="nav-link" id="themeToggle">
                    <i class="ti ti-moon"></i>
                </a>
            </div>

            @auth
            <div class="nav-item dropdown">
                <a href="#" class="nav-link d-flex lh-1 text-reset p-0"
                    data-bs-toggle="dropdown">
                    <span class="avatar avatar-sm"
                        style="background-image: url({{ auth()->user()->avatar ?? '' }})">
                    </span>
                </a>
                <div class="dropdown-menu dropdown-menu-end">
                    <a class="dropdown-item" href="{{ route('logout') }}">{{ __('library.logout') }}</a>
                </div>
            </div>
            @endauth

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

{{-- 版本 Offcanvas（mobile） --}}
@if(!empty($channels))
<div class="offcanvas offcanvas-end" tabindex="-1" id="channelDrawer">
    <div class="offcanvas-header">
        <h5 class="offcanvas-title">{{ __('library.select_version') }}</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
    </div>
    <div class="offcanvas-body">
        <div class="list-group list-group-flush">
            @foreach($channels as $channel)
            @php $isActive = request('channel') == $channel['id']; @endphp
            @if($isActive)
            <div class="list-group-item active pe-none">
                <div class="fw-bold">{{ $channel['name'] }}</div>
                <small class="opacity-75">{{ __('language.' . $channel['lang']) }}</small>
            </div>
            @else
            <a href="{{ request()->fullUrlWithQuery(['channel' => $channel['id']]) }}"
                class="list-group-item list-group-item-action">
                <div class="fw-bold">{{ $channel['name'] }}</div>
                <small class="text-muted">{{ __('language.' . $channel['lang']) }}</small>
            </a>
            @endif
            @endforeach
        </div>
    </div>
</div>
@endif

{{-- TOC Offcanvas（mobile） --}}
<div class="offcanvas offcanvas-start" tabindex="-1" id="tocDrawer">
    <div class="offcanvas-header">
        <h5 class="offcanvas-title">{{ $book['book_title'] }}</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
    </div>
    <div class="offcanvas-body">
        @include('library.book.toc', ['toc' => $book['toc'] ?? []])
    </div>
</div>

{{-- 主内容区 --}}
<div class="container-fluid px-0">
    <div class="main-container">

        {{-- TOC 侧边栏（tablet+） --}}
        <div class="toc-sidebar card">
            <div class="card-body">
                <h5>{{ $book['book_title'] }}</h5>
                @include('library.book.toc', ['toc' => $book['toc'] ?? []])
            </div>
        </div>

        {{-- 正文 --}}
        <div class="content-area card">
            <div class="card-body">

                <h2>{{ $book['title'] }}</h2>
                <p>
                    <strong>{{ __('library.author') }}：</strong>
                    {{ $book['author'] }}
                    @if(isset($book['studio']))
                    @ <a href="{{ route('blog.index', ['user' => $book['studio']['studioName']]) }}">
                        {{ $book['studio']['nickName'] }}
                    </a>
                    @endif
                </p>

                {{-- ↓ 正文内容用 article 包裹，隔离排版作用域 ── --}}
                <article class="reader-body">
                    @if(isset($book['content']))
                    {!! $book['content'] !!}
                    @else
                    <div>{{ __('library.no_content') }}</div>
                    @endif
                </article>

                {{-- 上下翻页 --}}
                <div class="mt-6 pt-6">
                    <ul class="pagination">
                        @if(!empty($book['pagination']['prev']))
                        <li class="page-item page-prev">
                            <a class="page-link" href="{{ isset($anthologyId)
                            ? route('library.anthology.read', ['anthology' => $anthologyId, 'article' => $book['pagination']['prev']['id'], 'channel' => request('channel')])
                            : route('library.tipitaka.read', ['id' => $book['pagination']['prev']['id'], 'channel' => request('channel')]) }}">
                                <div class="row align-items-center">
                                    <div class="col-auto">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M15 6l-6 6l6 6"></path>
                                        </svg>
                                    </div>
                                    <div class="col">
                                        <div class="page-item-subtitle">{{ __('library.prev_article') }}</div>
                                        <div class="page-item-title">{{ $book['pagination']['prev']['title'] }}</div>
                                    </div>
                                </div>
                            </a>
                        </li>
                        @endif
                        @if(!empty($book['pagination']['next']))
                        <li class="page-item page-next">
                            <a class="page-link" href="{{ isset($anthologyId)
                            ? route('library.anthology.read', ['anthology' => $anthologyId, 'article' => $book['pagination']['next']['id'], 'channel' => request('channel')])
                            : route('library.tipitaka.read', ['id' => $book['pagination']['next']['id'], 'channel' => request('channel')]) }}">
                                <div class="row align-items-center">
                                    <div class="col">
                                        <div class="page-item-subtitle">{{ __('library.next_article') }}</div>
                                        <div class="page-item-title">{{ $book['pagination']['next']['title'] }}</div>
                                    </div>
                                    <div class="col-auto">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M9 6l6 6l-6 6"></path>
                                        </svg>
                                    </div>
                                </div>
                            </a>
                        </li>
                        @endif
                    </ul>
                </div>

            </div>
        </div>

        {{-- 右侧边栏 --}}
        <div class="right-sidebar">



            {{-- 下载 --}}
            @if(!empty($book['downloads']))
            <div class="reader-channel-card">
                <div class="reader-channel-title">{{ __('library.download') }}</div>
                <ul class="list-unstyled mb-0">
                    @foreach ($book['downloads'] as $download)
                    <li>
                        <a href="{{ $download['url'] }}" class="btn btn-outline-primary mb-2 w-100">
                            <i class="ti ti-download me-2"></i>{{ $download['format'] }}
                        </a>
                    </li>
                    @endforeach
                </ul>
            </div>
            @endif

            {{-- 标签 --}}
            @if(!empty($book['tags']))
            <div class="reader-channel-card">
                <div class="reader-channel-title">{{ __('library.tags') }}</div>
                @foreach ($book['tags'] as $tag)
                <span class="badge me-1">{{ $tag['name'] }}</span>
                @endforeach
            </div>
            @endif

        </div>

    </div>
</div>

{{-- 阅读设置 Modal --}}
<div class="modal modal-blur fade" id="settingsModal" tabindex="-1">
    <div class="modal-dialog">
        <form id="settingsForm" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">{{ __('library.reading_settings') }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-4">
                    <label class="form-label">{{ __('library.show_original') }}</label>
                    <label class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="showOrigin">
                        <span class="form-check-label">{{ __('library.toggle_original') }}</span>
                    </label>
                </div>
                <div class="mb-4">
                    <label class="form-label">{{ __('library.ui_language') }}</label>
                    <select class="form-select" id="uiLanguage">
                        <option value="auto">{{ __('library.auto') }}</option>
                        <option value="zh">{{ __('library.lang_zh_hans') }}</option>
                        <option value="en">{{ __('library.lang_en') }}</option>
                    </select>
                </div>
                <div class="mb-4">
                    <label class="form-label">{{ __('library.pali_script') }}</label>
                    <select class="form-select" id="paliScript">
                        <option value="auto">{{ __('library.auto') }}</option>
                        <option value="roman">{{ __('library.script_roman') }}</option>
                        <option value="myanmar">{{ __('library.script_myanmar') }}</option>
                        <option value="thai">{{ __('library.script_thai') }}</option>
                    </select>
                </div>
                @isset($commentaryChannels)
                <div class="mb-4">
                    <label class="form-label">{{ __('library.commentary_version') }}</label>
                    <select class="form-select" id="commentary">
                        <option value="none">{{ __('library.none') }}</option>
                        @foreach($commentaryChannels as $channel)
                        <option value="{{ $channel['id'] }}">{{ $channel['name'] }}</option>
                        @endforeach
                    </select>
                </div>
                @endisset
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link" data-bs-dismiss="modal">{{ __('library.cancel') }}</button>
                <button type="submit" class="btn btn-primary">{{ __('library.confirm') }}</button>
            </div>
        </form>
    </div>
</div>

@endsection

@push('scripts')
<script>
    // 夜间模式
    document.getElementById('themeToggle').addEventListener('click', function(e) {
        e.preventDefault();
        const isDark = document.body.classList.contains('dark-mode');
        document.body.classList.toggle('dark-mode', !isDark);
        document.body.classList.toggle('light-mode', isDark);
        this.innerHTML = isDark ?
            '<i class="ti ti-moon"></i>' :
            '<i class="ti ti-sun"></i>';
        fetch('{{ route("theme.toggle") }}', {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                theme: isDark ? 'light' : 'dark'
            })
        });
    });

    // 阅读设置
    function getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return decodeURIComponent(parts.pop().split(';').shift());
        return null;
    }

    function setCookie(name, value, days = 365) {
        const date = new Date();
        date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
        document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + date.toUTCString() + '; path=/';
    }

    function toggleOriginDisplay(show) {
        document.querySelectorAll('.origin').forEach(el => {
            el.style.display = show ? 'unset' : 'none';
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        const showOrigin = getCookie('show_origin') === 'true';
        document.getElementById('showOrigin').checked = showOrigin;
        document.getElementById('uiLanguage').value = getCookie('ui_language') || 'auto';
        document.getElementById('paliScript').value = getCookie('pali_script') || 'auto';
        document.getElementById('commentary').value = getCookie('commentary') || 'none';
        toggleOriginDisplay(showOrigin);
    });

    document.getElementById('settingsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        setCookie('show_origin', document.getElementById('showOrigin').checked);
        setCookie('ui_language', document.getElementById('uiLanguage').value);
        setCookie('pali_script', document.getElementById('paliScript').value);
        setCookie('commentary', document.getElementById('commentary').value);
        // 修改 URL 的 comm 参数
        const commValue = document.getElementById('commentary').value;
        const url = new URL(window.location.href);
        if (commValue === 'none') {
            url.searchParams.delete('comm');
        } else {
            url.searchParams.set('comm', commValue);
        }
        window.location.href = url.toString();
    });
</script>
@endpush
