"use client";

import type { ReactNode } from "react";
import { KIND_META, orderSections, templateFor, type ItemKind } from "@/lib/protocols/templates";

// ──────────────────────────────────────────────────────────────────────────
// Darstellung eines Eintrags als Versions-Block.
// Bewusst eine gemeinsame Komponente für Übersicht UND Editor-Vorschau —
// so kann die Vorschau nicht von der späteren Ansicht abweichen.
// ──────────────────────────────────────────────────────────────────────────

export type EntryView = {
  title: string;
  version: string | null;
  /** ISO-Datum. */
  date: string;
  template: string;
  summary: string | null;
  isDraft: boolean;
  authorName?: string | null;
  items: { id?: string; kind: ItemKind; text: string }[];
};

export function fmtDate(iso: string): string {
  const d = new Date(iso.length === 10 ? `${iso}T12:00:00` : iso);
  if (Number.isNaN(d.getTime())) return "—";
  return d.toLocaleDateString("de-DE", { day: "2-digit", month: "long", year: "numeric" });
}

export function EntryBlock({
  entry,
  actions,
}: {
  entry: EntryView;
  actions?: ReactNode;
}) {
  const tpl = templateFor(entry.template);
  const present = [...new Set(entry.items.map((i) => i.kind))];
  const sections = orderSections(entry.template, present);

  // Ohne Version trägt der Titel die Überschrift.
  const headline = entry.version?.trim() || entry.title.trim() || "Ohne Titel";
  const showTitle = Boolean(entry.version?.trim());

  return (
    <article className="rel" data-draft={entry.isDraft}>
      <div className="rel-head">
        <div className="flex min-w-0 flex-wrap items-baseline gap-3">
          <h3 className="rel-version">{headline}</h3>
          <span className="rel-tag" style={{ color: tpl.color }}>
            {tpl.name}
          </span>
          {entry.isDraft ? <span className="rel-draft">Entwurf</span> : null}
        </div>
        {/* Aktionen innen, Datum ganz außen am Rand. */}
        <div className="rel-head-right">
          {actions}
          <div className="rel-meta">
            <span className="rel-date">{fmtDate(entry.date)}</span>
            {entry.authorName ? (
              <span className="rel-author">von {entry.authorName}</span>
            ) : null}
          </div>
        </div>
      </div>

      {showTitle ? <p className="rel-title">{entry.title || "Ohne Titel"}</p> : null}
      {entry.summary?.trim() ? <p className="rel-summary">{entry.summary}</p> : null}

      {sections.map((kind) => {
        const meta = KIND_META[kind];
        const items = entry.items.filter((i) => i.kind === kind);
        return (
          <section key={kind} className="rel-section">
            <div className="rel-kind" style={{ color: meta.color }}>
              {meta.label}
            </div>
            <ul className="rel-items">
              {items.map((i, idx) => (
                <li key={i.id ?? `${kind}-${idx}`} className="rel-item" style={{ color: meta.color }}>
                  <span style={{ color: "var(--text)" }}>{i.text}</span>
                </li>
              ))}
            </ul>
          </section>
        );
      })}

      {sections.length === 0 && !entry.summary?.trim() ? (
        <p className="rel-summary" style={{ opacity: 0.6 }}>
          Noch keine Punkte erfasst.
        </p>
      ) : null}
    </article>
  );
}
