import type { ReactNode } from "react";
import { headingId } from "../../components/RichText";
import type { CompanySettings } from "../../lib/payload";
import type { TOCSection } from "../../components/SectionTOC";

// Renders "Angaben zum Anbieter"/"Umsatzsteuer"/(conditionally)
// "Handelsregister"/"Geschäftsführung"/"Verantwortlich für den Inhalt"
// straight from company-settings, matching RichText.tsx's own heading/
// paragraph classes so it reads as one continuous page with the CMS
// content below it, not a bolted-on block. This used to be hand-typed
// prose baked into the Impressum's richText (seed-legal-pages.ts on the
// Payload side) — duplicated, and silently out of date the moment an
// admin changed company-settings without also remembering to re-edit the
// Impressum text by hand. Single-sourced here instead, same "structural/
// brand elements in code, only pull the actual numbers/copy that need
// single-sourcing from data" pattern this page's own Nachhaltigkeit card
// already uses (see page.tsx's comment on that).
//
// Also closes a real compliance gap the old hand-typed text had: it never
// showed Handelsregister/Geschäftsführung at all, even though
// company-settings already models both (§37a HGB/§35a GmbHG) — those
// fields just weren't wired into the Impressum. A sole proprietorship
// (this shop's current legalForm) has neither, so neither section shows
// today, but the moment that changes in company-settings, the Impressum
// picks it up automatically instead of needing a second manual edit.
//
// A "Gesellschafter"/Komplementäre section for OHG/KG was attempted
// 2026-07-23 but reverted the same day — the legal basis turned out
// genuinely unclear on research (§125a HGB's Geschäftsbriefe-naming duty
// only applies to the narrow case where *no* partner is a natural person,
// not the general OHG/KG case; whether §5 DDG's Impressum-specific
// "vertretungsberechtigte Person" requirement independently mandates it
// wasn't resolved with confidence). Deliberately not modeled until that's
// actually clarified — don't rebuild this without re-verifying the legal
// basis first, and don't assume the old attempt's reasoning was correct.
export function anbieterAngabenHeadings(seller: CompanySettings | null): TOCSection[] {
  if (!seller) return [];
  const sections = ["Angaben zum Anbieter"];
  if (seller.vatId) sections.push("Umsatzsteuer");
  if (seller.registerCourt && seller.registerNumber) sections.push("Handelsregister");
  if (seller.managingDirector) sections.push("Geschäftsführung");
  sections.push("Verantwortlich für den Inhalt");
  return sections.map((title) => ({ id: headingId(title), title }));
}

function Heading({ children }: { children: string }) {
  return (
    <h2
      id={headingId(children)}
      className="font-semibold text-h-small text-text-primary mt-2 scroll-mt-32 first:mt-0"
      style={{ fontFamily: "var(--font-lora)" }}
    >
      {children}
      <span className="block h-[0.125rem] w-8 bg-brand mt-2" aria-hidden />
    </h2>
  );
}

function P({ children }: { children: ReactNode }) {
  return <p className="text-body text-text-body">{children}</p>;
}

export function AnbieterAngaben({ seller }: { seller: CompanySettings }) {
  return (
    <div className="flex flex-col gap-4 w-full">
      <Heading>Angaben zum Anbieter</Heading>
      {/* gap-1, not the outer container's own gap-4 — these 5 lines are one
          continuous address block, not 5 separate paragraphs; the large
          inter-section gap only belongs between a heading's own block and
          the next, not between lines that visually belong together
          (fixed 2026-07-24, same fix applied to every block below). */}
      <div className="flex flex-col gap-1">
        <P>{seller.sellerName}</P>
        <P>{seller.sellerStreet}</P>
        <P>
          {seller.sellerZip} {seller.sellerCity}
        </P>
        <P>{seller.sellerCountry}</P>
        <P>
          E-Mail: <a href={`mailto:${seller.sellerEmail}`} className="text-brand hover:underline">{seller.sellerEmail}</a>
        </P>
      </div>

      {seller.vatId && (
        <>
          <Heading>Umsatzsteuer</Heading>
          <div className="flex flex-col gap-1">
            <P>Umsatzsteuer-Identifikationsnummer gemäß § 27 a Umsatzsteuergesetz:</P>
            <P>{seller.vatId}</P>
          </div>
        </>
      )}

      {seller.registerCourt && seller.registerNumber && (
        <>
          <Heading>Handelsregister</Heading>
          <div className="flex flex-col gap-1">
            <P>{seller.registerCourt}</P>
            <P>{seller.registerNumber}</P>
            {/* Optional/voluntary, not a Pflichtangabe — see
                CompanySettings.ts's own comment on shareCapital. Only shows
                if an admin deliberately filled it in. */}
            {seller.shareCapital ? <P>Stammkapital: {seller.shareCapital.toLocaleString("de-DE")} €</P> : null}
          </div>
        </>
      )}

      {seller.managingDirector && (
        <>
          <Heading>Geschäftsführung</Heading>
          <P>{seller.managingDirector}</P>
        </>
      )}

      <Heading>Verantwortlich für den Inhalt</Heading>
      {/* §18 Abs. 2 MStV wants a natural person — managingDirector first
          (Kapitalgesellschaften), falling back to sellerName itself (sole
          proprietorship/e.K., already a natural person's own name). No
          OHG/KG general-partner fallback here — see this file's top
          comment on why that field doesn't exist yet. */}
      <div className="flex flex-col gap-1">
        <P>{seller.managingDirector || seller.sellerName}</P>
        <P>{seller.sellerStreet}</P>
        <P>
          {seller.sellerZip} {seller.sellerCity}
        </P>
        <P>{seller.sellerCountry}</P>
      </div>
    </div>
  );
}
