import Link from "next/link";
import { notFound } from "next/navigation";
import SiteChrome from "@/components/layout/SiteChrome";
import AffidavitButton from "@/components/widgets/AffidavitButton";
import { getEntry, getSiteSettings } from "@/lib/api";
import { formatDate, obj, str, toNotice } from "@/lib/content";
import { paperDay, stampOf } from "@/lib/editions";
import TypewriterSheet from "@/components/notices/TypewriterSheet";

/** The published notice text with its line breaks, without markup (display only). */
const plainNotice = (html: string) =>
  html
    .replace(/<br\s*\/?>/gi, "\n")
    .replace(/<\/(p|div|h\d|li)>/gi, "\n")
    .replace(/<[^>]+>/g, "")
    .replace(/&nbsp;/g, " ")
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/\n{3,}/g, "\n\n")
    .trim();

const paperDayOf = (iso: string) => {
  const d = new Date(iso);
  return Number.isNaN(d.getTime()) ? iso : paperDay(d);
};
import { DEFAULT_NOTICE_LABELS, noticeVolume } from "@/components/notices/NoticeCard";

export const revalidate = 300;

const NOTICES = "notices";

export async function generateMetadata({ params }: { params: { slug: string } }) {
  const e = await getEntry(NOTICES, params.slug);
  if (!e) return {};
  const n = toNotice(e);
  return { title: n.noticeNumber ? `Notice No. ${n.noticeNumber}: ${n.title}` : n.title, description: n.summary || undefined };
}

/** One published notice (an entry of the CMS "notices" collection). Labels
 *  and the sample/affidavit wording come from theme_json.noticeDetail. */
export default async function NoticePage({ params }: { params: { slug: string } }) {
  const [entry, site] = await Promise.all([getEntry(NOTICES, params.slug), getSiteSettings()]);
  if (!entry) notFound();
  const n = toNotice(entry);
  const f = entry.fields;
  const t = obj(site.theme, "noticeDetail");
  const L = (k: string, d: string) => str(t, k, d);
  const published = n.status !== "scheduled";
  const statusText = published ? L("publishedLabel", "Published") : L("scheduledLabel", "Scheduled");
  const statusColor = published ? "#065f46" : "var(--navy)";
  const affidavit = str(f, "affidavitStatus", n.isSample ? L("affidavitStatusDefault", "Sample Only") : L("affidavitStatusReal", "After final run"));

  const meta: [string, string, React.CSSProperties?][] = [
    [L("noticeNumberLabel", "Notice No."), n.noticeNumber, { fontWeight: 700 }],
    [L("organizationLabel", "Organization"), n.organization],
    [L("stateLabel", "State"), `${n.stateCode.toUpperCase()} ${n.stateName}`],
    [L("countyLabel", "County"), n.county],
    [L("zipLabel", "ZIP Code"), str(f, "zip")],
    [L("facilityLabel", "Facility Type"), n.facilityType],
    [L("projectTypeLabel", "Project Type"), str(f, "projectType")],
    [published ? L("publicationDateLabel", "Publication Date") : L("scheduledDateLabel", "Scheduled Date"), formatDate(n.date, true)],
    [L("timestampLabel", "Published (timestamp)"), published && n.publishedAt ? stampOf(n.publishedAt) : ""],
    [
      L("editionLabel", "Edition"),
      published
        ? noticeVolume(n, {
            ...DEFAULT_NOTICE_LABELS,
            volumeTemplate: str(site.theme, "volumeLabel", DEFAULT_NOTICE_LABELS.volumeTemplate),
            editionEpoch: str(site.theme, "editionEpoch", DEFAULT_NOTICE_LABELS.editionEpoch)
          })
        : ""
    ],
    [L("runDatesLabel", "Publication Runs"), str(f, "runDates")],
    [L("statusLabel", "Status"), statusText, { color: statusColor, fontWeight: 700 }]
  ];

  return (
    <SiteChrome slug="notice-detail" cssScope="notice-detail">
      <div className="main-content">
        <div className="breadcrumb">
          <Link href="/">{L("breadcrumbHome", "Home")}</Link>
          <span>/</span>
          <Link href="/directory">{L("breadcrumbDirectory", "Search for CONs")}</Link>
          <span>/</span>
          <span>
            {n.organization}, {n.county}, {n.stateCode.toUpperCase()}
          </span>
        </div>
        <div>
          <div className="notice-card">
            {n.isSample && <div className="sample-banner">{L("sampleBanner", "SAMPLE NOTICE: This is not a real published CON notice")}</div>}
            {/* The whole notice, typed on vintage paper coming out of a typewriter, then stamped. */}
            <TypewriterSheet
              stampLabel={statusText}
              stampDate={published && n.publishedAt ? formatDate(paperDayOf(n.publishedAt), true) : formatDate(n.date, true)}
              stampNumber={n.noticeNumber ? `${L("noticeNumberLabel", "Notice No.")} ${n.noticeNumber}` : ""}
              scheduled={!published}
            >
              <span className={`notice-status ${published ? "published" : "pending"}`}>
                <span className="nl-dot" aria-hidden="true" /> {statusText}
              </span>
              <h1 className="notice-title">{n.title}</h1>
              <div className="notice-meta-grid">
                {meta
                  .filter(([, v]) => v && v.trim())
                  .map(([k, v, style]) => (
                    <div className="meta-item" key={k}>
                      <div className="meta-key">{k}</div>
                      <div className="meta-val" style={style}>
                        {v}
                      </div>
                    </div>
                  ))}
              </div>
              {str(f, "noticeText") && (
                <>
                  <h3 className="tws-heading">{L("noticeTextHeading", "Notice Text")}</h3>
                  <div className="tws-notice-text">{plainNotice(str(f, "noticeText"))}</div>
                </>
              )}
            </TypewriterSheet>
            {n.isSample ? (
              <div className="affidavit-box">
                <span className="sample-label">{L("affidavitBadge", "SAMPLE: NOT LEGALLY VALID")}</span>
                <h4 style={{ fontWeight: 700, color: "var(--navy)", marginBottom: 6, fontSize: ".875rem" }}>{L("affidavitHeading", "Affidavit of Publication")}</h4>
                <p style={{ fontSize: ".82rem", color: "var(--gray-600)", marginBottom: 14 }} dangerouslySetInnerHTML={{ __html: L("affidavitHtml", "") }} />
                <AffidavitButton label={L("affidavitButton", "Download Sample Affidavit")} message={L("affidavitAlert", "Sample affidavit download — Prototype only.")} />
              </div>
            ) : (
              <div className="affidavit-box">
                <h4 style={{ fontWeight: 700, color: "var(--navy)", marginBottom: 6, fontSize: ".875rem" }}>{L("affidavitHeading", "Affidavit of Publication")}</h4>
                <p
                  style={{ fontSize: ".82rem", color: "var(--gray-600)", marginBottom: 14 }}
                  dangerouslySetInnerHTML={{ __html: L("affidavitRealHtml", "An affidavit of publication is issued after the notice's final publication run.") }}
                />
                <Link
                  href={`${L("affidavitRequestHref", "/affidavit-request")}${n.noticeNumber ? `?noticeNumber=${encodeURIComponent(n.noticeNumber)}` : ""}`}
                  className="download-btn"
                  style={{ textDecoration: "none" }}
                >
                  {L("affidavitRequestLabel", "Request the Affidavit")}
                </Link>
              </div>
            )}
          </div>
        </div>
        <div>
          <div className="sidebar-card" style={{ borderTop: `4px solid ${published ? "#22c55e" : "var(--gold)"}` }}>
            <h4>{L("statusCardHeading", "Notice Status")}</h4>
            <div style={{ fontSize: ".82rem" }}>
              {[
                [L("statusLabel", "Status"), statusText, { color: statusColor, fontWeight: 700 }],
                [published ? L("publishedLabel", "Published") : L("scheduledLabel", "Scheduled"), formatDate(n.date), {}],
                [L("stateLabel", "State"), n.stateName, {}],
                [L("affidavitLabel", "Affidavit"), affidavit, { color: "#856404", fontWeight: 600 }]
              ].map(([k, v, style], i, arr) => (
                <div
                  key={String(k)}
                  style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderBottom: i < arr.length - 1 ? "1px solid var(--gray-100)" : undefined }}
                >
                  <span style={{ color: "var(--gray-600)" }}>{k as string}</span>
                  <span style={style as React.CSSProperties}>{v as string}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="sidebar-card">
            <h4>{L("submitCardHeading", "Submit Your Own Notice")}</h4>
            <p style={{ fontSize: ".82rem", color: "var(--gray-600)", marginBottom: 12 }}>{L("submitCardText", "")}</p>
            <Link href={L("submitCardHref", "/submit")} className="cta-btn">
              {L("submitCardLabel", "Start Your Notice")}
            </Link>
          </div>
          <div className="sidebar-card">
            <h4>{L("disclaimerHeading", "Legal Disclaimer")}</h4>
            <p style={{ fontSize: ".78rem", color: "var(--gray-600)", lineHeight: 1.6 }}>
              {n.isSample ? L("disclaimerText", "") : L("disclaimerTextReal", L("disclaimerText", ""))}
            </p>
          </div>
          <div className="sidebar-card">
            <h4>{L("moreHeading", "More Notices")}</h4>
            <Link href="/directory" style={{ fontSize: ".875rem", color: "var(--navy)", fontWeight: 600, textDecoration: "none" }}>
              {L("moreLabel", "Back to Search for CONs")}
            </Link>
          </div>
        </div>
      </div>
    </SiteChrome>
  );
}
