<?php
// public/article.php — Single article
require_once __DIR__ . '/includes/api.php';

$id = (int)($_GET['id'] ?? 0);
if (!$id) { header('Location: /public/index.php'); exit; }

$art = api_article($id);
if (!$art) {
    http_response_code(404);
    $pageTitle  = 'Not Found — NewsForge';
    $activePage = 'article';
    require_once __DIR__ . '/includes/header.php';
    echo '<div class="container" style="padding:80px 20px;text-align:center">
            <h1>Article not found</h1>
            <a href="/public/index.php" style="color:var(--primary)">← Home</a>
          </div>';
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

// Related articles — same category, exclude current
$related = api_news(['category' => $art['category'], 'limit' => 4, 'exclude' => $id]);

// Build content HTML
$bodyHtml = (string)($art['content'] ?? '');
if (!$bodyHtml) $bodyHtml = (string)($art['description'] ?? '');
// If plain text (no HTML tags), wrap in paragraphs
if ($bodyHtml && strip_tags($bodyHtml) === $bodyHtml) {
    $paras = array_filter(array_map('trim', preg_split('/\n{2,}/', $bodyHtml)));
    $bodyHtml = '<p>' . implode('</p><p>', array_map('htmlspecialchars', $paras)) . '</p>';
}

// First image for hero
$heroImg = null;
foreach (($art['images'] ?? []) as $img) { $heroImg = $img; break; }

$pageTitle  = h($art['title']) . ' — NewsForge';
$activePage = 'article';
require_once __DIR__ . '/includes/header.php';
?>

<main>
<div class="container" style="padding-top:28px">
  <div class="content-with-sidebar">

    <article class="article-full">

      <!-- Breadcrumb -->
      <div class="breadcrumb">
        <a href="/public/index.php">Home</a>
        <span>›</span>
        <?php if ($art['category']): ?>
        <a href="/public/category.php?cat=<?= urlencode(strtolower($art['category'])) ?>">
          <?= h(ucfirst($art['category'])) ?>
        </a>
        <span>›</span>
        <?php endif; ?>
        <span><?= h(mb_substr($art['title'], 0, 55)) ?>…</span>
      </div>

      <!-- Category badge -->
      <span class="cat-badge <?= cat_color($art['category']) ?>" style="font-size:12px">
        <?= strtoupper(h($art['category'] ?? 'NEWS')) ?>
      </span>

      <!-- Title -->
      <h1 class="article-title" dir="auto"><?= h($art['title']) ?></h1>

      <!-- Meta -->
      <div class="article-meta">
        <div>
          <div class="author-name">
            <?= h($art['source_name'] ?? 'NewsForge') ?>
          </div>
          <div class="article-date">
            <?= date('F j, Y', strtotime($art['published_at'] ?? $art['created_at'] ?? 'now')) ?>
            — <?= read_time($art['content'] ?? $art['description'] ?? '') ?> min read
            <?php if (!empty($art['extraction_mode'])): ?>
            &nbsp;<span title="Extraction method" style="font-size:11px;opacity:.5">[<?= h($art['extraction_mode']) ?>]</span>
            <?php endif; ?>
          </div>
        </div>
        <div class="article-actions">
          <button class="action-btn" onclick="shareArticle()">📤 Share</button>
          <button class="action-btn" onclick="window.print()">🖨 Print</button>
          <?php if (!empty($art['url'])): ?>
          <a class="action-btn" href="<?= h($art['url']) ?>" target="_blank" rel="noopener"
             style="text-decoration:none">🔗 Source</a>
          <?php endif; ?>
        </div>
      </div>

      <!-- Share bar -->
      <div class="share-bar">
        <span>Share:</span>
        <button class="share-btn fb" onclick="shareOn('facebook')">Facebook</button>
        <button class="share-btn tw" onclick="shareOn('twitter')">𝕏 / Twitter</button>
        <button class="share-btn wa" onclick="shareOn('whatsapp')">WhatsApp</button>
        <button class="share-btn li" onclick="shareOn('linkedin')">LinkedIn</button>
      </div>

      <!-- Reading progress bar -->
      <div class="read-progress-bar">
        <div class="read-progress-fill" id="readProgress"></div>
      </div>

      <!-- Hero image -->
      <?php if ($heroImg): ?>
      <img src="<?= h($heroImg['file_url'] ?? $heroImg['original_url'] ?? '') ?>"
           alt="<?= h($art['title']) ?>"
           class="article-hero-img"
           onerror="this.style.display='none'">
      <?php elseif (!empty($art['id'])): ?>
      <img src="https://picsum.photos/seed/<?= $art['id'] ?>/900/480"
           alt="<?= h($art['title']) ?>"
           class="article-hero-img">
      <?php endif; ?>

      <!-- Body -->
      <div class="article-body" dir="auto">
        <?php if (!empty($art['description']) && !empty($art['content'])): ?>
        <p class="lead-para"><?= h($art['description']) ?></p>
        <?php endif; ?>
        <?= $bodyHtml ?>

        <!-- Extra images in article -->
        <?php $extraImgs = array_slice(array_values($art['images'] ?? []), 1, 4); ?>
        <?php foreach ($extraImgs as $img): ?>
        <figure style="margin:24px 0">
          <img src="<?= h($img['file_url'] ?? $img['original_url'] ?? '') ?>"
               style="width:100%;border-radius:var(--radius)"
               onerror="this.style.display='none'">
        </figure>
        <?php endforeach; ?>

        <!-- Videos -->
        <?php foreach (($art['videos'] ?? []) as $vid): ?>
        <div style="margin:24px 0">
          <?php if (!empty($vid['file_url']) && str_ends_with(strtolower($vid['file_url']), '.mp4')): ?>
          <video controls style="width:100%;border-radius:var(--radius)">
            <source src="<?= h($vid['file_url']) ?>" type="video/mp4">
          </video>
          <?php else: ?>
          <a href="<?= h($vid['original_url'] ?? $vid['file_url'] ?? '#') ?>"
             target="_blank" class="action-btn">▶ Watch Video</a>
          <?php endif; ?>
        </div>
        <?php endforeach; ?>

        <!-- Source link -->
        <?php if (!empty($art['url'])): ?>
        <p style="margin-top:28px;font-size:13px;color:var(--text-light);border-top:1px solid var(--border);padding-top:14px">
          Original source:
          <a href="<?= h($art['url']) ?>" target="_blank" rel="noopener"
             style="color:var(--primary)">
            <?= h(parse_url($art['url'], PHP_URL_HOST) ?: $art['url']) ?>
          </a>
        </p>
        <?php endif; ?>

        <!-- Category tag -->
        <?php if (!empty($art['category'])): ?>
        <div class="article-tags">
          <strong>Category:</strong>
          <a href="/public/category.php?cat=<?= urlencode(strtolower($art['category'])) ?>"
             class="tag"><?= h(ucfirst($art['category'])) ?></a>
        </div>
        <?php endif; ?>
      </div><!-- /.article-body -->

      <!-- Source box -->
      <?php if (!empty($art['source_name'])): ?>
      <div class="author-box">
        <div style="width:60px;height:60px;border-radius:50%;background:var(--primary);
                    display:flex;align-items:center;justify-content:center;
                    font-size:24px;color:#fff;flex-shrink:0">📰</div>
        <div>
          <div class="author-box-name"><?= h($art['source_name']) ?></div>
          <div class="author-box-role">News Source</div>
          <?php if (!empty($art['source_site'])): ?>
          <a href="<?= h($art['source_site']) ?>" target="_blank" rel="noopener"
             style="color:var(--primary);font-size:13px">
            Visit <?= h(parse_url($art['source_site'], PHP_URL_HOST) ?: $art['source_name']) ?> →
          </a>
          <?php endif; ?>
        </div>
      </div>
      <?php endif; ?>

    </article>

    <?php require_once __DIR__ . '/includes/sidebar.php'; ?>

  </div><!-- /.content-with-sidebar -->

  <!-- Related Articles -->
  <?php if (!empty($related)): ?>
  <div class="related-section">
    <div class="section-header">
      <h2 class="section-title"><span>Related Articles</span></h2>
      <a href="/public/category.php?cat=<?= urlencode(strtolower($art['category'] ?? '')) ?>"
         class="see-all">See All →</a>
    </div>
    <div class="sports-strip">
      <?php foreach ($related as $rel): ?>
      <article class="strip-card"
               onclick="location.href='/public/article.php?id=<?= $rel['id'] ?>'"
               style="cursor:pointer">
        <img src="<?= h(thumb($rel, 280, 180)) ?>"
             alt="<?= h($rel['title']) ?>"
             onerror="this.src='https://picsum.photos/seed/<?= $rel['id'] ?>/280/180'">
        <span class="cat-badge <?= cat_color($rel['category']) ?>">
          <?= strtoupper(h($rel['category'] ?? 'NEWS')) ?>
        </span>
        <h4><?= h($rel['title']) ?></h4>
        <span class="small-time"><?= rel_time($rel['published_at'] ?? $rel['created_at']) ?></span>
      </article>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

</div><!-- /.container -->
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
