<?php
declare(strict_types=1);

$app = app();
$pdo = $app->pdo();
$userId = $_SESSION['user_id'] ?? null;
$error = '';
$info = '';
$search = trim((string)($_GET['q'] ?? ''));
$boardSlug = trim((string)($_GET['board'] ?? ''));

$communityCfg = require __DIR__ . '/../../../config/community.php';
$community = $pdo ? new \App\Community($pdo, $communityCfg) : null;
$access = $pdo ? new \App\CommunityAccess($pdo, $communityCfg) : null;

$forumCategories = $community ? $community->listForumCategories() : [];
$selectedBoard = ($community && $boardSlug !== '') ? $community->getBoardBySlug($boardSlug) : null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $community && $access) {
    $action = (string)($_POST['action'] ?? '');
    try {
        if ($action === 'thread_create') {
            if (!$userId) {
                throw new \RuntimeException('Bitte einloggen, um Themen zu erstellen.');
            }
            if (!$access->canCreateThread((int)$userId)) {
                $state = $access->getRestrictionState((int)$userId);
                throw new \RuntimeException($state['reason'] ?: 'Du darfst aktuell keine Themen erstellen.');
            }
            $community->createThreadInBoard((int)$userId, (string)($_POST['board_slug'] ?? ''), (string)($_POST['title'] ?? ''), (string)($_POST['body'] ?? ''));
            redirect('/community' . ($boardSlug !== '' ? '?board=' . rawurlencode($boardSlug) : ''));
        }
    } catch (\Throwable $e) {
        $error = $e->getMessage();
    }
}

$threads = $community
    ? ($search !== '' ? $community->searchThreads($search, 50, $boardSlug !== '' ? $boardSlug : null) : $community->listThreads(50, $boardSlug !== '' ? $boardSlug : null))
    : [];
?>
<main class="section">
  <div class="container">
    <div class="forum-hero">
      <div>
        <div class="forum-breadcrumbs">
          <a href="/">Home</a>
          <span>/</span>
          <span>Community</span>
          <?php if ($selectedBoard): ?>
            <span>/</span>
            <span><?= htmlspecialchars((string)$selectedBoard['title'], ENT_QUOTES) ?></span>
          <?php endif; ?>
        </div>
        <h1>Community</h1>
        <p class="forum-hero__copy">Fragen stellen, Erfahrungen teilen, Antworten finden und gemeinsam weiterdenken.</p>
      </div>
      <div class="forum-hero__actions forum-hero__actions--stack">
        <form method="get" class="forum-search forum-search--hero">
          <?php if ($boardSlug !== ''): ?>
            <input type="hidden" name="board" value="<?= htmlspecialchars($boardSlug, ENT_QUOTES) ?>">
          <?php endif; ?>
          <label class="label" for="searchQHero">Suche</label>
          <div class="forum-search__row">
            <input id="searchQHero" name="q" class="input" value="<?= htmlspecialchars($search, ENT_QUOTES) ?>" placeholder="Thema oder Stichwort suchen">
            <button class="btn" type="submit">Suchen</button>
          </div>
        </form>
        <div class="forum-hero__cta">
          <?php if ($userId): ?>
            <button class="btn" type="button" data-modal-open="modalThread">Neues Thema</button>
          <?php else: ?>
            <a class="btn" href="/login">Einloggen und schreiben</a>
          <?php endif; ?>
        </div>
      </div>
    </div>

    <?php if ($error): ?>
      <div class="toast-bar" style="margin-top:14px; border-color:#f87171; color:#991b1b;"><?= htmlspecialchars($error, ENT_QUOTES) ?></div>
    <?php endif; ?>
    <?php if ($info): ?>
      <div class="toast-bar" style="margin-top:14px;"><?= htmlspecialchars($info, ENT_QUOTES) ?></div>
    <?php endif; ?>

    <?php if ($selectedBoard): ?>
      <div class="forum-shell">
        <?php
          $sidebarCategories = $forumCategories;
          $sidebarCurrentBoardSlug = (string)$selectedBoard['slug'];
          require __DIR__ . '/sidebar.php';
        ?>
        <div class="forum-shell__main">
          <div class="forum-board">
            <div class="forum-board__head">
              <div>
                <h2><?= htmlspecialchars($selectedBoard['title'], ENT_QUOTES) ?></h2>
                <p class="muted"><?= htmlspecialchars((string)$selectedBoard['description'], ENT_QUOTES) ?></p>
              </div>
              <a class="btn ghost" href="/community">Alle Bereiche anzeigen</a>
            </div>

            <div class="forum-list">
              <div class="forum-list__header">
                <span>Thema</span>
                <span>Antworten</span>
                <span>Letzte Aktivität</span>
              </div>

              <?php foreach ($threads as $t): ?>
                <?php
                  $pts = ($community && $pdo) ? $community->computePoints((int)$t['uid']) : 0.0;
                  $lvl = $community ? $community->membershipLevel($pts) : ['label'=>'','icon'=>''];
                  $preview = mb_substr((string)$t['body'], 0, 220);
                ?>
                <article class="forum-row">
                  <div class="forum-row__topic">
                    <div class="forum-row__avatar"><?= \App\Avatar\Lorelei::render($t, (string)($t['display_name'] ?: 'Mitglied'), 'forum-list') ?></div>
                    <div>
                      <h3><a href="/community_thread?id=<?= (int)$t['id'] ?>"><?= htmlspecialchars((string)$t['title'], ENT_QUOTES) ?></a></h3>
                      <div class="forum-row__meta">
                        <span><?= htmlspecialchars((string)($t['display_name'] ?: 'Mitglied'), ENT_QUOTES) ?></span>
                        <span><?= htmlspecialchars(trim((string)($lvl['icon'] ?? '') . ' ' . (string)($lvl['label'] ?? '')), ENT_QUOTES) ?></span>
                      </div>
                      <p><?= nl2br(htmlspecialchars($preview, ENT_QUOTES)) ?><?= mb_strlen((string)$t['body']) > 220 ? '…' : '' ?></p>
                    </div>
                  </div>
                  <div class="forum-row__count">
                    <strong><?= (int)$t['answers'] ?></strong>
                    <span>Antworten</span>
                  </div>
                  <div class="forum-row__activity">
                    <strong><?= htmlspecialchars((string)($t['last_activity_by'] ?: 'Mitglied'), ENT_QUOTES) ?></strong>
                    <span><?= htmlspecialchars((string)$t['last_activity_at'], ENT_QUOTES) ?></span>
                  </div>
                </article>
              <?php endforeach; ?>

              <?php if (!$threads): ?>
                <div class="forum-empty">In diesem Bereich gibt es noch keine Themen.</div>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>
    <?php else: ?>
      <div class="forum-category-list">
        <?php foreach ($forumCategories as $category): ?>
          <section class="forum-category-card">
            <div class="forum-category-card__title"><?= htmlspecialchars((string)$category['title'], ENT_QUOTES) ?></div>
            <div class="forum-board-grid">
              <?php foreach ($category['boards'] as $board): ?>
                <?php $latest = $board['latest_thread'] ?? null; ?>
                <article class="forum-board-row">
                  <div class="forum-board-row__main">
                    <div class="forum-row__icon" aria-hidden="true"><?= htmlspecialchars((string)($board['icon'] ?? '💬'), ENT_QUOTES) ?></div>
                    <div>
                      <h3>
                        <a href="/community?board=<?= rawurlencode((string)$board['slug']) ?>">
                          <?= htmlspecialchars((string)$board['title'], ENT_QUOTES) ?>
                        </a>
                      </h3>
                      <p><?= htmlspecialchars((string)$board['description'], ENT_QUOTES) ?></p>
                      <div class="forum-row__meta">
                        <span>Themen: <?= (int)($board['thread_count'] ?? 0) ?></span>
                        <span>Beiträge: <?= (int)($board['post_count'] ?? 0) ?></span>
                      </div>
                    </div>
                  </div>
                  <div class="forum-board-row__latest">
                    <?php if ($latest): ?>
                      <strong><a href="/community_thread?id=<?= (int)$latest['id'] ?>"><?= htmlspecialchars((string)$latest['title'], ENT_QUOTES) ?></a></strong>
                      <span><?= htmlspecialchars((string)($latest['last_activity_by'] ?: 'Mitglied'), ENT_QUOTES) ?></span>
                      <span><?= htmlspecialchars((string)$latest['last_activity_at'], ENT_QUOTES) ?></span>
                    <?php else: ?>
                      <span class="muted">Noch keine Themen</span>
                    <?php endif; ?>
                  </div>
                </article>
              <?php endforeach; ?>
            </div>
          </section>
        <?php endforeach; ?>
      </div>

      <div class="forum-board" style="margin-top:24px;">
        <div class="forum-board__head">
          <div>
            <h2>Neueste Themen</h2>
            <p class="muted">Hier siehst du die zuletzt erstellten oder zuletzt aktiven Themen aus der Community.</p>
          </div>
        </div>

        <div class="forum-list">
          <div class="forum-list__header">
            <span>Thema</span>
            <span>Antworten</span>
            <span>Letzte Aktivität</span>
          </div>

          <?php foreach ($threads as $t): ?>
            <?php
              $pts = ($community && $pdo) ? $community->computePoints((int)$t['uid']) : 0.0;
              $lvl = $community ? $community->membershipLevel($pts) : ['label'=>'','icon'=>''];
              $preview = mb_substr((string)$t['body'], 0, 220);
            ?>
            <article class="forum-row">
              <div class="forum-row__topic">
                <div class="forum-row__avatar"><?= \App\Avatar\Lorelei::render($t, (string)($t['display_name'] ?: 'Mitglied'), 'forum-list') ?></div>
                <div>
                  <h3><a href="/community_thread?id=<?= (int)$t['id'] ?>"><?= htmlspecialchars((string)$t['title'], ENT_QUOTES) ?></a></h3>
                  <div class="forum-row__meta">
                    <span><?= htmlspecialchars((string)($t['display_name'] ?: 'Mitglied'), ENT_QUOTES) ?></span>
                    <span><?= htmlspecialchars(trim((string)($lvl['icon'] ?? '') . ' ' . (string)($lvl['label'] ?? '')), ENT_QUOTES) ?></span>
                    <?php if (!empty($t['board_title'])): ?>
                      <span><?= htmlspecialchars((string)$t['board_title'], ENT_QUOTES) ?></span>
                    <?php endif; ?>
                  </div>
                  <p><?= nl2br(htmlspecialchars($preview, ENT_QUOTES)) ?><?= mb_strlen((string)$t['body']) > 220 ? '…' : '' ?></p>
                </div>
              </div>
              <div class="forum-row__count">
                <strong><?= (int)$t['answers'] ?></strong>
                <span>Antworten</span>
              </div>
              <div class="forum-row__activity">
                <strong><?= htmlspecialchars((string)($t['last_activity_by'] ?: 'Mitglied'), ENT_QUOTES) ?></strong>
                <span><?= htmlspecialchars((string)$t['last_activity_at'], ENT_QUOTES) ?></span>
              </div>
            </article>
          <?php endforeach; ?>

          <?php if (!$threads): ?>
            <div class="forum-empty">Keine Themen gefunden.</div>
          <?php endif; ?>
        </div>
      </div>
    <?php endif; ?>
  </div>
</main>

<?php if ($userId): ?>
<div class="modal" id="modalThread">
  <div class="panel">
    <div class="head flex between center-y">
      <h3 style="margin:0;">Neues Thema</h3>
      <button class="btn ghost" type="button" data-modal-close>✕</button>
    </div>
    <form method="post" class="stack gap-10" style="margin-top:12px;">
      <input type="hidden" name="action" value="thread_create">
      <div class="stack gap-6">
        <label class="label" for="fBoardModal">Unterforum</label>
        <select id="fBoardModal" name="board_slug" class="select">
          <?php foreach ($forumCategories as $category): ?>
            <optgroup label="<?= htmlspecialchars((string)$category['title'], ENT_QUOTES) ?>">
              <?php foreach ($category['boards'] as $board): ?>
                <option value="<?= htmlspecialchars((string)$board['slug'], ENT_QUOTES) ?>" <?= $boardSlug === $board['slug'] ? 'selected' : '' ?>>
                  <?= htmlspecialchars((string)$board['title'], ENT_QUOTES) ?>
                </option>
              <?php endforeach; ?>
            </optgroup>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="stack gap-6">
        <label class="label" for="fTitleModal">Frage/Titel</label>
        <input id="fTitleModal" name="title" class="input" required>
      </div>
      <div class="stack gap-6">
        <label class="label" for="fBodyModal">Text</label>
        <textarea id="fBodyModal" name="body" class="textarea" rows="5" required></textarea>
      </div>
      <div class="flex gap-12" style="flex-wrap:wrap;">
        <button class="btn ghost" type="button" data-modal-close>Abbrechen</button>
        <button class="btn" type="submit">Thema erstellen</button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<script>
  document.querySelectorAll('[data-modal-open]').forEach(btn => {
    btn.addEventListener('click', () => {
      const id = btn.getAttribute('data-modal-open');
      const modal = document.getElementById(id);
      if (modal) modal.classList.add('open');
    });
  });
  document.querySelectorAll('[data-modal-close]').forEach(btn => {
    btn.addEventListener('click', () => {
      const modal = btn.closest('.modal');
      if (modal) modal.classList.remove('open');
    });
  });
  document.querySelectorAll('.modal').forEach(modal => {
    modal.addEventListener('click', (e) => {
      if (e.target === modal) modal.classList.remove('open');
    });
  });
</script>
