import Link from "next/link";
import type { CSSProperties } from "react";

import { BlueprintSheet } from "@/components/BlueprintSheet";
import { DemoBlock } from "@/components/DemoBlock";
import { DocumentRegister } from "@/components/DocumentRegister";
import { Evidence } from "@/components/Evidence";
import { Section } from "@/components/Section";
import { StructuredData } from "@/components/StructuredData";
import { ForwardLink, TextLink } from "@/components/TextLink";
import { VideoMedia } from "@/components/VideoMedia";
import { getModule, getModules, getProduct, getSectors, getT } from "@/lib/content";
import type { Locale } from "@/lib/locales";
import { href, MODULES, moduleById, type ModuleId } from "@/lib/routes";

import styles from "./Page.module.css";
import { PageTitle } from "./PageTitle";
import { EVIDENCE_STRINGS, evidenceRecords, VIDEO_STRINGS, videoRecords } from "./evidence";

/**
 * /nexys/[module] — a product world.
 *
 * One skeleton, four tempos. Every product page opens on its own document at
 * full width — the ledger, the delivery note, the payslip, the table map —
 * then the register of what it produces, then the program at work in Sulsys's
 * own recording, then the day's six steps with what the module connects to,
 * then the ask. The order is also the surface rhythm: paper, paper, navy,
 * paper, paper.
 *
 * Caffe is the exception, and it is one that can be said aloud: it is the one
 * product that runs at night, on a touch screen, in a room, so its world is
 * on the system's surface. Its recording then follows the register rather
 * than the world, so two navy chapters never meet.
 *
 * Budget has no cleared recording — both payroll walkthroughs are held back
 * pending a personal-data check — so it has no media chapter, and no
 * placeholder pretending to be one.
 */
export function ModuleView({ locale, moduleId }: { locale: Locale; moduleId: ModuleId }) {
  const t = getT(locale);
  const meta = moduleById(moduleId);
  const content = getModule(locale, moduleId);
  const allModules = getModules(locale);
  const sectors = getSectors(locale);
  const product = getProduct(locale);

  if (!meta) return null;

  const videos = videoRecords(locale, moduleId);
  const evidence = evidenceRecords(locale, moduleId);
  const night = moduleId === "bar-restorant";

  const connected = content.connects
    .map((id) => ({
      meta: MODULES.find((m) => m.id === id),
      content: allModules.find((m) => m.id === id),
    }))
    .filter((row) => row.meta && row.content);

  const moduleSectors = sectors.filter((sector) => content.sectors.includes(sector.id));

  return (
    <div className={styles.module} data-module={moduleId}>
      <StructuredData
        locale={locale}
        crumbs={[
          { name: t("nav.home"), target: { key: "home" } },
          { name: product.name, target: { key: "nexys" } },
          { name: content.brandName, target: { key: "module", module: moduleId } },
        ]}
      />

      {/* The title, with the module's own spec beside it */}
      <PageTitle
        tone={night ? "navy" : "paper"}
        eyebrow={[`${t("label.module")} ${meta.code}`, product.name]}
        title={content.brandName}
        subtitle={content.name}
        oneLiner={content.records}
        aside={
          <dl className={styles.spec}>
            {/* The signature: what this module counts. No two are alike. */}
            <div className={styles.specRow}>
              <dt className={styles.specLabel}>{t("label.unit")}</dt>
              <dd className={styles.specUnit}>
                {content.unit.map((noun, index) => (
                  <span key={noun}>
                    {index > 0 ? (
                      <span className={styles.specUnitSep} aria-hidden="true">
                        ·
                      </span>
                    ) : null}
                    {noun}
                  </span>
                ))}
              </dd>
            </div>

            {moduleSectors.length > 0 ? (
              <div className={styles.specRow}>
                <dt className={styles.specLabel}>{t("sectors.forWhom")}</dt>
                <dd className={styles.specValue}>
                  {moduleSectors.map((sector, index) => (
                    <span key={sector.id}>
                      {index > 0 ? " · " : null}
                      <Link
                        href={href({ key: "sector", sector: sector.id }, locale)}
                        className={styles.specLink}
                      >
                        {sector.name}
                      </Link>
                    </span>
                  ))}
                </dd>
              </div>
            ) : null}

            {connected.length > 0 ? (
              <div className={styles.specRow}>
                <dt className={styles.specLabel}>{t("label.connects")}</dt>
                <dd className={styles.specValue}>
                  {connected.map((row, index) => (
                    <span key={row.meta!.id}>
                      {index > 0 ? " · " : null}
                      <Link
                        href={href({ key: "module", module: row.meta!.id }, locale)}
                        className={styles.specLink}
                      >
                        {row.meta!.brandName}
                      </Link>
                    </span>
                  ))}
                </dd>
              </div>
            ) : null}
          </dl>
        }
      >
        <p className={styles.partOf}>
          <TextLink href={href({ key: "nexys" }, locale)}>{t("module.partOf")}</TextLink>
        </p>
        {content.legacyNames.length > 0 ? (
          <p className={styles.legacy}>
            {t("module.legacyName")}: {content.legacyNames.join(" · ")}
          </p>
        ) : null}
      </PageTitle>

      {/* 1 — the world: the module's own document, first and at full width */}
      <Section first tight surface={night ? "navy" : "paper"}>
        <BlueprintSheet
          sheet={content.sheet}
          locale={locale}
          variant="world"
          tone={night ? "navy" : "paper"}
        />
      </Section>

      {/* 2 — what it produces */}
      <Section surface="alt" heading={t("heading.documents")}>
        <DocumentRegister
          documents={content.documents}
          connectsLabel={t("table.connects")}
          features={content.features}
          featuresLabel={t("heading.features")}
        />
      </Section>

      {/* 3 — at work: this module, in Sulsys's own recording */}
      {videos.length > 0 || evidence.length > 0 ? (
        <Section
          surface="navy"
          heading={videos.length > 0 ? t("media.heading") : t("evidence.heading")}
          action={
            <ForwardLink href={href({ key: "support" }, locale)}>
              {t("cta.allTutorials")}
            </ForwardLink>
          }
        >
          {videos.length > 0 ? <VideoMedia items={videos} strings={VIDEO_STRINGS(locale)} /> : null}
          {evidence.length > 0 ? (
            <div className={videos.length > 0 ? styles.stacked : undefined}>
              <Evidence
                items={evidence}
                strings={EVIDENCE_STRINGS(locale)}
                showNote={videos.length === 0}
              />
            </div>
          ) : null}
        </Section>
      ) : null}

      {/* 4 — a day, and what it connects to */}
      <Section heading={t("heading.workflow")}>
        <ol className={styles.strip}>
          {content.workflow.map((step, index) => (
            <li key={step} className={styles.stripStep} style={{ "--i": index } as CSSProperties}>
              <span className={styles.stripNr}>{String(index + 1).padStart(2, "0")}</span>
              <span>{step}</span>
            </li>
          ))}
        </ol>

        {connected.length > 0 ? (
          <div className={styles.connects}>
            <p className={styles.connectsLabel}>{t("heading.connects")}</p>
            <div className={styles.connectsGrid}>
              <ul className={styles.connectLanes}>
                {connected.map((row, index) => (
                  <li
                    key={row.meta!.id}
                    className={styles.connectLane}
                    style={{ "--i": index } as CSSProperties}
                  >
                    <Link
                      href={href({ key: "module", module: row.meta!.id }, locale)}
                      className={styles.connectLink}
                    >
                      <span className={styles.connectCode}>{row.meta!.code}</span>
                      <span className={styles.connectName}>
                        {row.meta!.brandName}
                        <span className={styles.connectSub}>{row.content!.name}</span>
                      </span>
                    </Link>
                    <span className={styles.connectBar} aria-hidden="true" />
                  </li>
                ))}
              </ul>
              <p className={styles.connectApex}>
                <span className={styles.connectCode}>{meta.code}</span>
                {content.brandName}
              </p>
            </div>
          </div>
        ) : null}
      </Section>

      {/* 5 — the ask */}
      <DemoBlock locale={locale} />
    </div>
  );
}
