---
export const prerender = false;

import AdminLayout from '../../layouts/AdminLayout.astro';
import { getSession, SESSION_COOKIE, cleanExpiredSessions } from '../../lib/auth';
import { getPendingEntries, getRecentModerated } from '../../lib/guestbook';

const sessionId = Astro.cookies.get(SESSION_COOKIE)?.value;
const session = sessionId ? getSession(sessionId) : undefined;

if (!session) {
  return Astro.redirect('/admin/login');
}

// Periodic cleanup
cleanExpiredSessions();

const pending = getPendingEntries();
const recent = getRecentModerated(20);

const errorParam = Astro.url.searchParams.get('error');
---

<AdminLayout title="Moderation">
  <h1>guestbook moderation</h1>

  {errorParam && (
    <div class="alert alert-error" role="alert">
      {errorParam === 'invalid' ? 'Invalid action.' : errorParam}
    </div>
  )}

  <!-- Pending entries -->
  <section aria-labelledby="pending-heading">
    <h2 id="pending-heading">
      Pending
      {pending.length > 0 && <span class="count-badge">{pending.length}</span>}
    </h2>

    {pending.length === 0 ? (
      <div class="card empty">
        <p>No pending messages. All clear.</p>
      </div>
    ) : (
      <div class="entry-list">
        {pending.map((entry) => (
          <article class="card entry-card">
            <div class="entry-meta meta">
              <span class="badge badge-pending">pending</span>
              <span>id #{entry.id}</span>
              <time datetime={entry.created_at}>{entry.created_at.replace('T', ' ').replace('Z', ' UTC')}</time>
              {entry.ip_hash && <span title="Truncated IP hash (privacy-safe)">ip: {entry.ip_hash}</span>}
            </div>

            <div class="entry-fields">
              <div class="entry-field">
                <span class="field-label">name:</span>
                <span class="field-value">{entry.display_name}</span>
              </div>
              {entry.website && (
                <div class="entry-field">
                  <span class="field-label">website:</span>
                  <a
                    href={entry.website}
                    class="field-value"
                    rel="noopener noreferrer nofollow"
                    target="_blank"
                  >
                    {entry.website}
                  </a>
                </div>
              )}
              <div class="entry-field">
                <span class="field-label">message:</span>
              </div>
              <blockquote class="message-text">{entry.message}</blockquote>
            </div>

            <form method="post" action="/api/admin/moderate" class="action-form">
              <input type="hidden" name="id" value={entry.id} />

              <div class="note-field">
                <label for={`note-${entry.id}`} class="meta">
                  Note (optional):
                </label>
                <input
                  type="text"
                  id={`note-${entry.id}`}
                  name="note"
                  maxlength="200"
                  placeholder="internal note..."
                />
              </div>

              <div class="action-btns">
                <button type="submit" name="action" value="approve" class="btn btn-approve">
                  approve
                </button>
                <button type="submit" name="action" value="reject" class="btn btn-reject">
                  reject
                </button>
                <button type="submit" name="action" value="spam" class="btn btn-spam">
                  spam
                </button>
              </div>
            </form>
          </article>
        ))}
      </div>
    )}
  </section>

  <!-- Recently moderated -->
  {recent.length > 0 && (
    <section class="section-gap" aria-labelledby="recent-heading">
      <h2 id="recent-heading">Recently moderated</h2>
      <div class="entry-list">
        {recent.map((entry) => (
          <article class="card entry-card entry-card--compact">
            <div class="entry-meta meta">
              <span class:list={['badge', `badge-${entry.status}`]}>{entry.status}</span>
              <span>id #{entry.id}</span>
              <time datetime={entry.created_at}>{entry.created_at.slice(0, 10)}</time>
              <span class="entry-name">{entry.display_name}</span>
            </div>
            <p class="message-text compact-msg">{entry.message}</p>
            {entry.moderation_note && (
              <p class="meta mod-note">note: {entry.moderation_note}</p>
            )}
          </article>
        ))}
      </div>
    </section>
  )}
</AdminLayout>

<style>
  h1 {
    margin-bottom: var(--space-md);
  }

  h2 {
    display: flex;
    align-items: center;
    gap: var(--space-xs);
    margin-bottom: var(--space-sm);
  }

  .count-badge {
    background: var(--color-peach);
    color: #1e1e2e;
    font-size: 0.75rem;
    font-weight: bold;
    padding: 1px 7px;
    border-radius: 10px;
  }

  .entry-list {
    display: flex;
    flex-direction: column;
    gap: var(--space-sm);
  }

  .entry-card {
    border-left: 3px solid var(--color-surface);
  }

  .entry-meta {
    display: flex;
    align-items: center;
    gap: var(--space-sm);
    flex-wrap: wrap;
    margin-bottom: var(--space-xs);
    font-size: 0.8rem;
  }

  .entry-fields {
    margin-bottom: var(--space-sm);
  }

  .entry-field {
    display: flex;
    gap: 6px;
    font-size: 0.88rem;
    margin-bottom: 4px;
  }

  .field-label {
    color: var(--color-text-dim);
    flex-shrink: 0;
    min-width: 5em;
  }

  .field-value {
    word-break: break-all;
  }

  .message-text {
    white-space: pre-wrap;
    word-break: break-word;
    font-size: 0.88rem;
    padding: var(--space-xs) var(--space-sm);
    border-left: 2px solid var(--color-surface);
    margin: var(--space-xs) 0;
    font-style: normal;
  }

  .action-form {
    display: flex;
    flex-direction: column;
    gap: var(--space-xs);
    border-top: 1px solid var(--color-surface);
    padding-top: var(--space-sm);
    margin-top: var(--space-xs);
  }

  .note-field {
    display: flex;
    flex-direction: column;
    gap: 2px;
  }

  .note-field input {
    max-width: 400px;
    font-size: 0.82rem;
  }

  .action-btns {
    display: flex;
    gap: var(--space-xs);
    flex-wrap: wrap;
  }

  .btn {
    padding: 4px 14px;
    border-radius: 4px;
    border: 1px solid currentColor;
    background: none;
    font-family: inherit;
    font-size: 0.85rem;
    cursor: pointer;
    transition: opacity 0.15s;
  }
  .btn:hover { opacity: 0.75; }
  .btn-approve { color: var(--color-green); }
  .btn-reject  { color: var(--color-text-dim); }
  .btn-spam    { color: var(--color-warm); }

  .entry-card--compact {
    padding: var(--space-xs) var(--space-sm);
  }

  .compact-msg {
    font-size: 0.85rem;
    color: var(--color-text-dim);
    white-space: pre-wrap;
    word-break: break-word;
    max-height: 3em;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .mod-note {
    font-size: 0.78rem;
    color: var(--color-text-dim);
    font-style: italic;
  }

  .entry-name {
    color: var(--color-text);
  }

  .empty {
    color: var(--color-text-dim);
    font-size: 0.88rem;
    padding: var(--space-md);
  }

  .section-gap {
    margin-top: var(--space-xl);
  }
</style>
