<?php

declare(strict_types=1);

require_once __DIR__ . '/includes/layout.php';

library_bootstrap();

$query = trim((string) ($_GET['q'] ?? ''));
$language = trim((string) ($_GET['language'] ?? ''));

// Pagination Logic
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 12; // Grid layout 3x4
$offset = ($page - 1) * $limit;

$result = library_fetch_documents_paginated(true, ['q' => $query, 'language' => $language], $limit, $offset);
$documents = $result['data'];
$totalDocuments = $result['total'];
$totalPages = (int)ceil($totalDocuments / $limit);

$metrics = library_catalog_metrics();
$recentDocuments = library_recent_documents(3, true);

library_render_header(
    'Digital Catalog',
    'Browse a polished Arabic and English e-library with online reading, public/private publishing controls, and AI-ready summaries.',
    'catalog'
);
?>
<section class="hero-surface mb-4 mb-lg-5">
    <div class="row g-4 align-items-center">
        <div class="col-lg-7">
            <span class="eyebrow">Electronic library · Arabic + English</span>
            <h1 class="display-6 mb-3">A focused e-library for bilingual reading, controlled publishing, and AI-ready summaries.</h1>
            <p class="lead text-secondary mb-4">Readers can search the public shelf, open PDFs in-browser, and review concise AI summaries. Your content team can publish titles as public or private from one admin studio.</p>
            <div class="d-flex flex-wrap gap-2">
                <a class="btn btn-dark" href="#catalog-grid">Browse catalog</a>
                <a class="btn btn-outline-secondary" href="/admin.php">Add documents</a>
            </div>
        </div>
        <div class="col-lg-5">
            <div class="panel h-100">
                <div class="d-flex justify-content-between align-items-start gap-3 mb-4">
                    <div>
                        <div class="section-kicker">Live shelf snapshot</div>
                        <h2 class="h5 mb-1">What this first delivery includes</h2>
                    </div>
                    <span class="badge text-bg-light">MVP slice</span>
                </div>
                <div class="metric-grid">
                    <article class="metric-card">
                        <span class="metric-value"><?= h((string) $metrics['public_count']) ?></span>
                        <span class="metric-label">Public titles</span>
                    </article>
                    <article class="metric-card">
                        <span class="metric-value"><?= h((string) $metrics['private_count']) ?></span>
                        <span class="metric-label">Private titles</span>
                    </article>
                    <article class="metric-card">
                        <span class="metric-value"><?= h((string) $metrics['summarized_count']) ?></span>
                        <span class="metric-label">AI summaries</span>
                    </article>
                </div>
                <ul class="list-unstyled mb-0 mt-4 compact-list">
                    <li>Public catalog with search and language filters</li>
                    <li>Admin upload workflow with visibility control</li>
                    <li>Document detail view with embedded PDF reader</li>
                </ul>
            </div>
        </div>
    </div>
</section>

<section class="row g-4 mb-4 mb-lg-5">
    <div class="col-lg-8">
        <div class="panel h-100">
            <div class="section-kicker">Public discovery</div>
            <h2 class="h4 mb-3">Search the live collection</h2>
            <form class="row g-3 align-items-end" method="get" action="/index.php">
                <div class="col-md-7">
                    <label class="form-label" for="q">Keyword</label>
                    <input class="form-control" id="q" name="q" type="search" value="<?= h($query) ?>" placeholder="Title, author, tag, or excerpt">
                </div>
                <div class="col-md-3">
                    <label class="form-label" for="language">Language</label>
                    <select class="form-select" id="language" name="language">
                        <option value="">All shelves</option>
                        <option value="en" <?= $language === 'en' ? 'selected' : '' ?>>English</option>
                        <option value="ar" <?= $language === 'ar' ? 'selected' : '' ?>>Arabic</option>
                        <option value="bilingual" <?= $language === 'bilingual' ? 'selected' : '' ?>>Bilingual</option>
                    </select>
                </div>
                <div class="col-md-2 d-grid">
                    <button class="btn btn-dark" type="submit">Filter</button>
                </div>
            </form>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="panel h-100">
            <div class="section-kicker">Visibility rules</div>
            <h2 class="h5 mb-3">Admin-controlled access</h2>
            <p class="text-secondary mb-3">Public items appear in this catalog immediately. Private items stay out of the public shelf and are marked for member login in the admin workspace.</p>
            <a class="link-arrow" href="/admin.php">Review publishing controls</a>
        </div>
    </div>
</section>

<section class="mb-5" id="catalog-grid">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <div class="section-kicker">Catalog</div>
            <h2 class="h3 mb-0">Available public titles</h2>
        </div>
        <span class="text-secondary small"><?= h((string) $totalDocuments) ?> result<?= $totalDocuments === 1 ? '' : 's' ?></span>
    </div>

<?php if (!$documents): ?>
    <div class="panel empty-panel text-center py-5">
        <div class="empty-icon mb-3">⌘</div>
        <h3 class="h5">No public documents yet</h3>
        <p class="text-secondary mb-4">Upload your first Arabic or English PDF from the Admin Studio to turn this into a browsable library.</p>
        <a class="btn btn-dark" href="/admin.php">Open Admin Studio</a>
    </div>
<?php else: ?>
    <div class="row g-4">
<?php foreach ($documents as $document): ?>
<?php
    $cardSummary = (string) ($document['summary_text'] ?: ($document['description_en'] ?: $document['description_ar'] ?: 'No summary yet.'));
    $cardSummaryLang = library_text_lang(
        $cardSummary,
        !empty($document['description_ar']) && empty($document['summary_text']) && empty($document['description_en']) ? 'ar' : 'en'
    );
    $cardSummaryDir = library_text_dir($cardSummary, $cardSummaryLang);
?>
        <div class="col-md-6 col-xl-4">
            <article class="panel h-100 d-flex flex-column">
                <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
                    <div class="d-flex flex-wrap gap-2">
                        <span class="badge text-bg-light"><?= h(library_language_label((string) $document['document_language'])) ?></span>
                        <span class="badge text-bg-light"><?= h(library_document_type_label((string) $document['document_type'])) ?></span>
                    </div>
                    <?php if (!empty($document['is_featured'])): ?>
                        <span class="badge text-bg-dark">Featured</span>
                    <?php endif; ?>
                </div>
                <div class="mb-3">
                    <?php if (!empty($document['title_en'])): ?>
                        <h3 class="h5 mb-1"><?= h((string) $document['title_en']) ?></h3>
                    <?php endif; ?>
                    <?php if (!empty($document['title_ar'])): ?>
                        <div class="text-secondary" dir="rtl" lang="ar"><?= h((string) $document['title_ar']) ?></div>
                    <?php endif; ?>
                </div>
                <dl class="row small text-secondary mb-3 gx-2 gy-1">
                    <dt class="col-4">Author</dt>
                    <dd class="col-8 mb-0"><?= h((string) ($document['author'] ?: 'Not set')) ?></dd>
                    <dt class="col-4">Views</dt>
                    <dd class="col-8 mb-0"><?= h((string) $document['view_count']) ?></dd>
                    <dt class="col-4">Tags</dt>
                    <dd class="col-8 mb-0"><?= h((string) ($document['tags'] ?: '—')) ?></dd>
                </dl>
                <p class="text-secondary flex-grow-1" lang="<?= h($cardSummaryLang) ?>" dir="<?= h($cardSummaryDir) ?>"><?= h($cardSummary) ?></p>
                <div class="d-flex gap-2 mt-3">
                    <a class="btn btn-dark btn-sm" href="/document.php?id=<?= h((string) $document['id']) ?>">Open reader</a>
                    <a class="btn btn-outline-secondary btn-sm" href="/document.php?id=<?= h((string) $document['id']) ?>#summary-card">View summary</a>
                </div>
            </article>
        </div>
<?php endforeach; ?>
    </div>
    
    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
        <div class="mt-5">
            <?php library_render_pagination($page, $totalPages, '/index.php'); ?>
        </div>
    <?php endif; ?>
    
<?php endif; ?>
</section>

<section class="row g-4">
    <div class="col-lg-4">
        <div class="panel h-100">
            <div class="section-kicker">Workflow</div>
            <h2 class="h5 mb-3">Thin slice, end to end</h2>
            <ol class="compact-list-numbered mb-0 text-secondary">
                <li>Admin uploads a document and chooses public or private visibility.</li>
                <li>Readers discover public titles from the catalog and open the detail page.</li>
                <li>AI summaries can be generated from the saved excerpt for faster review.</li>
            </ol>
        </div>
    </div>
    <div class="col-lg-8">
        <div class="panel h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <div class="section-kicker">Recently added</div>
                    <h2 class="h5 mb-0">Latest public titles</h2>
                </div>
                <a class="link-arrow" href="/admin.php">Manage shelf</a>
            </div>
            <div class="row g-3">
<?php foreach ($recentDocuments as $document): ?>
<?php
    $recentTitle = (string) ($document['title_en'] ?: $document['title_ar'] ?: 'Untitled');
    $recentTitleLang = library_text_lang($recentTitle, !empty($document['title_ar']) && empty($document['title_en']) ? 'ar' : 'en');
    $recentTitleDir = library_text_dir($recentTitle, $recentTitleLang);
?>
                <div class="col-md-4">
                    <a class="recent-card text-decoration-none" href="/document.php?id=<?= h((string) $document['id']) ?>">
                        <span class="small text-secondary d-block mb-2"><?= h(library_language_label((string) $document['document_language'])) ?></span>
                        <strong class="d-block text-dark mb-1" lang="<?= h($recentTitleLang) ?>" dir="<?= h($recentTitleDir) ?>"><?= h($recentTitle) ?></strong>
                        <span class="small text-secondary"><?= h((string) ($document['author'] ?: 'Unknown author')) ?></span>
                    </a>
                </div>
<?php endforeach; ?>
            </div>
        </div>
    </div>
</section>
<?php
library_render_footer();