// Shared section frame + pill for the QAF comparison detail views (summary +
// G60). tdd-guard:skip — presentational primitives, no logic.

import { SectionPngButton } from "@/components/qaf-differences/qaf-export-controls"
import type { VariantDefinition } from "@/lib/qaf-differences"
import { actionTitle } from "@/lib/qaf-differences/internal/section-titles"

/** Compact placeholder for a section the current QAF type cannot fill (KAR-844). */
export function PlaceholderSection({
  title,
  reason,
  hidden,
}: {
  title: string
  reason: string
  hidden?: boolean
}) {
  return (
    <section
      className={`rounded border border-dashed border-border/60 bg-muted/10 px-4 py-2.5 ${hidden ? "hidden print:block" : ""}`}
    >
      <p className="text-sm">
        <span className="font-display font-bold tracking-tight text-muted-foreground uppercase">
          {title}
        </span>
        <span className="ml-2 text-xs text-muted-foreground">— {reason}</span>
      </p>
    </section>
  )
}

// adversarial-review-of-#318 findings 3+4: was byte-identical local
// UnavailableNotice/variantLabel in both qaf-multi-qaf-detail.tsx (KAR-947)
// and qaf-variant-vs-standard-detail.tsx (KAR-948) — one shared copy here,
// next to PlaceholderSection/Pill/Section which every Multi-QAF detail view
// already imports from this module.

/** Defensive per-section fallback (task requirement: "Result-Versionen sind
 * tolerant — defensiv rendern, nie crashen, nie leere Sektion die wie
 * 0-Diffs aussieht"). Deliberately NOT `PlaceholderSection` (that component
 * REPLACES a whole numbered section header for a QAF TYPE that structurally
 * cannot have this section at all, e.g. G60's missing form-view) — here the
 * `Section` wrapper (with its own numbered title + ⓘ info) already rendered;
 * this is only the BODY substitute for one comparison instance missing the
 * underlying data. */
export function UnavailableNotice({ reason }: { reason: string }) {
  return (
    <p className="rounded border border-dashed border-border/60 bg-muted/10 px-3 py-2 text-sm text-muted-foreground">
      {reason}
    </p>
  )
}

/** A variant's display label — its non-empty original column labels
 * (joined), falling back to the raw column letter, then the workbook's own
 * printed slot/variant number ("Slot 7"), and only as a last resort the
 * internal stable id (KAR-950 item 3: a raw `stableInternalId`/composite
 * canonical key — e.g. a `slot-N` positional id or a `fallback=…` identity
 * key, identity.ts's own `buildCompositeCanonicalKey` — must never be the
 * FIRST readable fallback when a more human label exists). `undefined`/
 * `null` (variant not resolvable in the persisted container) renders "—",
 * never crashes. */
export function variantLabel(v: VariantDefinition | undefined | null): string {
  if (!v) return "—"
  const labels = v.originalLabels.filter((l) => l.trim() !== "")
  if (labels.length > 0) return labels.join(" / ")
  if (v.originalColumn.trim() !== "") return v.originalColumn
  if (v.originalVariantNumber && v.originalVariantNumber.trim() !== "")
    return `Slot ${v.originalVariantNumber}`
  return v.stableInternalId
}

// `label` accepts a plain string OR a small ReactNode (KAR-950 item 6:
// several Pill callers now need a `<BilingualText>` label instead of a bare
// string) — a bare string still works unchanged everywhere else.
export function Pill({
  label,
  className,
}: {
  label: React.ReactNode
  className: string
}) {
  return (
    <span
      className={`inline-block rounded px-2 py-0.5 text-xs font-medium ${className}`}
    >
      {label}
    </span>
  )
}

export interface SectionInfo {
  /** What this section shows and why it matters (plain language). */
  text: string
  /** The formula(s) behind the numbers, in readable notation. */
  formula?: string
  /** A worked example with concrete numbers. */
  example?: string
}

export function Section({
  id,
  title,
  facts,
  count,
  exportId,
  exportPart,
  info,
  hidden,
  children,
}: {
  /** Anchor id for in-page jump navigation (KAR-952 §D3 — `QafMultiQafNav`'s
   * `href="#…"` targets). Optional/additive: every existing caller (Standard-
   * QAF/G60) that omits it renders exactly as before — no `id` attribute at
   * all, not even an empty string. */
  id?: string
  title: string
  /**
   * Fakten, die der Titel mitträgt — „25 → 31 Stationen · Δ +2,4727 EUR/Stück".
   *
   * Ohne sie nennt eine Überschrift nur die Kategorie, und der Leser muss
   * hineinschauen, um zu erfahren, ob überhaupt etwas passiert ist. Gebaut
   * werden die Satzteile in `section-titles.ts` — zentral, damit alle
   * Abschnitte dieselbe Sprache sprechen und nicht jeder seine eigene.
   *
   * Leere Einträge fallen weg; ist nichts übrig, steht der Titel allein da.
   */
  facts?: ReadonlyArray<string | null | undefined>
  count?: number
  /** Enables the per-section PNG download (KAR-840 export layer). */
  exportId?: string
  exportPart?: string | null
  /** Expandable ⓘ explanation (V11 SEC_INFO pattern, KAR-842 C). */
  info?: SectionInfo
  /** Loop 8: außerhalb des aktiven Hauptreiters. Die Sektion bleibt im DOM und
   *  im Ausdruck (`print:block`) — ein Reiter blendet am Bildschirm aus, er
   *  entfernt nichts. Ohne Angabe verhält sich `Section` wie bisher, alle
   *  Bestandsaufrufe (G60, Multi-QAF, Variant-vs-Standard) bleiben unberührt. */
  hidden?: boolean
  children: React.ReactNode
}) {
  return (
    <section
      id={id}
      data-export-id={exportId}
      className={`space-y-3 rounded border border-border bg-card p-4 print:break-inside-avoid scroll-mt-14 ${hidden ? "hidden print:block" : ""}`}
    >
      <h2 className="font-display text-sm font-bold tracking-tight text-foreground uppercase">
        {exportId && (
          <SectionPngButton
            exportId={exportId}
            partNumber={exportPart ?? null}
          />
        )}
        {actionTitle(title, facts ?? [])}
        {typeof count === "number" && (
          <span className="ml-2 text-muted-foreground">({count})</span>
        )}
      </h2>
      {info && (
        <details
          className="rounded border border-border/50 bg-muted/20 px-3 py-1.5 text-xs text-muted-foreground print:hidden"
          data-export-exclude
        >
          <summary className="cursor-pointer font-medium select-none">
            ⓘ Was zeigt diese Sektion?
          </summary>
          <div className="space-y-1 pt-1.5">
            <p>{info.text}</p>
            {info.formula && (
              <p>
                <span className="font-medium text-foreground">Formel:</span>{" "}
                <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">
                  {info.formula}
                </code>
              </p>
            )}
            {info.example && (
              <p>
                <span className="font-medium text-foreground">Beispiel:</span>{" "}
                {info.example}
              </p>
            )}
          </div>
        </details>
      )}
      {children}
    </section>
  )
}
