import type { ReactNode } from 'react';
import { Link, useParams } from 'react-router-dom';
import { ArrowLeft, ArrowRight, Play } from 'lucide-react';

import { StatusPill } from '@/components/site/EnvironmentPicker';
import { Term } from '@/components/site/Term';
import { iconFor } from '@/content/icons';
import { demosForVertical, featuredDemo, lineup, pad2, routes } from '@/content/lineup';
import * as s from '@/content/styles';
import { PROPOSAL_NOTICE, verticalBySlug } from '@/content/verticals';
import { pageTitle, useSeo } from '@/lib/seo';

/**
 * One proposal, in full.
 *
 * The page is the same shape as a demo page's header — persona, the buyer's
 * question as a quiet quote, then the environment in its parts — so a visitor
 * who has seen the word game reads this as the same machine with the board
 * missing. Every count and every neighbour is derived from the lineup.
 */

function Part({
  label,
  tone = 'default',
  children,
}: {
  label: ReactNode;
  tone?: 'default' | 'warning';
  children: ReactNode;
}) {
  return (
    <article className={`card p-4 sm:p-5 ${tone === 'warning' ? 'bg-warning-subtle' : ''}`}>
      <h3 className={`${s.label} ${tone === 'warning' ? 'text-warning' : ''}`}>{label}</h3>
      <p className={`${s.prose} mt-2 text-fg`}>{children}</p>
    </article>
  );
}

export default function VerticalPage() {
  const { slug } = useParams<{ slug: string }>();
  const vertical = verticalBySlug(slug);

  // Before the early return, because a hook cannot be called conditionally —
  // and because the "no such vertical" branch needs a head of its own too, or
  // it inherits whichever page the visitor came from.
  useSeo({
    title: pageTitle(vertical?.title ?? 'No such vertical'),
    description: vertical
      ? `${vertical.task} ${vertical.reward}`
      : `There is no proposal at that address. The ${lineup.length} we have written are all on the home page.`,
    ...(slug ? { canonical: routes.vertical(slug) } : {}),
    ...(vertical ? { ogImage: `/og/vertical-${vertical.slug}.png` } : {}),
  });

  if (!vertical) {
    return (
      <main className={`${s.shell} py-16`}>
        <p className={s.label}>No such vertical</p>
        <h1 className={`${s.h1} mt-3`}>There is no proposal at that address.</h1>
        <p className={`${s.lede} mt-4`}>
          Nothing is written at{' '}
          <code className="break-all font-mono text-mono-data text-fg">/verticals/{slug}</code>. The{' '}
          {lineup.length} we have written are all on the home page.
        </p>
        <div className="mt-6 flex flex-col gap-3 sm:flex-row">
          <Link className={s.btnPrimary} to={routes.home}>
            See the lineup
          </Link>
          <Link className={s.btnSecondary} to={routes.gallery}>
            See what is built
          </Link>
        </div>
      </main>
    );
  }

  const Icon = iconFor(vertical.icon);
  const demos = demosForVertical(vertical.key);
  const live = demos.find((d) => d.status === 'live');
  const spec = demos.find((d) => d.status === 'spec');

  const index = lineup.findIndex((v) => v.slug === vertical.slug);
  const previous = index > 0 ? lineup[index - 1] : undefined;
  const next = index >= 0 ? lineup[index + 1] : undefined;

  return (
    <main className={`${s.shell} py-8 sm:py-12`}>
      <Link className={s.navLink} to={routes.home}>
        <ArrowLeft aria-hidden="true" className="size-4" />
        All {lineup.length}
      </Link>

      <header className="mt-4">
        <div className="flex flex-wrap items-center gap-2">
          <span className={s.chipOutline}>{PROPOSAL_NOTICE}</span>
          <span className={s.chipOutline}>
            Rank {pad2(vertical.rank)} / {pad2(lineup.length)}
          </span>
          <span className={s.chipMuted}>
            {vertical.plannedForV1 ? 'In the first set' : 'Not in the first set'}
          </span>
        </div>
        <div className="mt-5 flex items-start gap-4">
          <span className="grid size-11 shrink-0 place-items-center rounded-md bg-surface-3">
            <Icon aria-hidden="true" className="size-5 text-border-strong" />
          </span>
          <h1 className={`${s.h1} min-w-0`}>{vertical.title}</h1>
        </div>
        <p className={`${s.label} mt-5 text-accent-fg`}>For the {vertical.persona}</p>
        <p className={`${s.label} mt-4`}>The question you walked in with</p>
        <blockquote className={`${s.quote} mt-2`}>
          <p>{vertical.anxiety}</p>
        </blockquote>
      </header>

      {/* ── The environment, in the same parts every time ───────────────── */}
      <section aria-labelledby="parts" className="mt-10">
        <h2 className={s.h2} id="parts">
          The environment
        </h2>
        <p className={`${s.prose} mt-3`}>
          The same machine as the word game: a task, a score in the number this desk already
          reports, and the term that takes points away — the{' '}
          <Term term="counterweight">counterweight</Term>. A <Term term="reward">reward</Term> with
          nothing pulling against it is a target, and a target is what a model learns to hit
          instead of doing the job.
        </p>
        <div className="mt-5 grid gap-4 lg:grid-cols-3">
          <Part label={<>01 &nbsp;The task</>}>{vertical.task}</Part>
          <Part label={<>04 &nbsp;The score that moves</>}>{vertical.reward}</Part>
          <Part label="The counterweight" tone="warning">
            {vertical.counterweight}
          </Part>
        </div>
      </section>

      {vertical.caveat ? (
        <section aria-labelledby="stops" className="card mt-6 bg-warning-subtle p-4 sm:p-5">
          <h2 className={`${s.label} text-warning`} id="stops">
            Where this stops
          </h2>
          <p className={`${s.prose} mt-2 text-fg`}>{vertical.caveat}</p>
        </section>
      ) : null}

      {/* ── What actually exists for this vertical, stated plainly ─────── */}
      <section aria-labelledby="exists" className="mt-10">
        <h2 className={s.h2} id="exists">
          What exists today
        </h2>
        {live ? (
          <Link
            aria-label={`${live.title} — play it`}
            className={`${s.cardLink} mt-4`}
            to={`${routes.demo(live.slug)}?tab=play`}
          >
            <span className="flex flex-wrap items-center gap-2">
              <StatusPill status="live" />
            </span>
            <span className={`${s.h3} mt-3`}>{live.title}</span>
            <span className={`${s.prose} mt-1.5`}>{live.tagline}</span>
            <span className="mt-4 inline-flex items-center gap-1.5 text-ui font-medium text-accent-fg">
              <Play aria-hidden="true" className="size-4" />
              Play it
            </span>
          </Link>
        ) : spec ? (
          <Link
            aria-label={`${spec.title} — read the specification`}
            className={`${s.cardLink} mt-4`}
            to={routes.demo(spec.slug)}
          >
            <span className="flex flex-wrap items-center gap-2">
              <StatusPill status="spec" />
            </span>
            <span className={`${s.h3} mt-3`}>{spec.title}</span>
            <span className={`${s.prose} mt-1.5`}>{spec.tagline}</span>
            <span className="mt-4 inline-flex items-center gap-1.5 text-ui font-medium text-accent-fg">
              Read the specification
              <ArrowRight aria-hidden="true" className="size-4" />
            </span>
          </Link>
        ) : (
          <div className="card mt-4 p-4 sm:p-5">
            <p className={`${s.prose} text-fg`}>
              Nothing. There is no environment for this vertical, no recorded run, and no number. It
              is a proposal, written to the same shape as the ones that are built so you can judge
              it on the same terms.
            </p>
            <div className="mt-5 flex flex-col gap-3 sm:flex-row">
              <Link className={s.btnSecondary} to={routes.gallery}>
                See what is built
              </Link>
              <Link className={s.btnSecondary} to={routes.honesty}>
                What we have not measured
              </Link>
            </div>
          </div>
        )}
      </section>

      {/* ── First visit ─────────────────────────────────────────────────── */}
      {!live && featuredDemo ? (
        <section aria-labelledby="first" className="mt-8 border-t border-border pt-6">
          <h2 className={s.label} id="first">
            If this is your first visit
          </h2>
          <p className={`${s.prose} mt-2`}>
            Play {featuredDemo.title} first. It is the same four parts on a board you already know,
            and every word on this page — task, grader, counterweight, score — is met there before
            it is used here. It is deliberately not one of these {lineup.length}: it shows the
            machinery without implying we have built yours.
          </p>
          <Link className={`${s.btnPrimary} mt-4`} to={`${routes.demo(featuredDemo.slug)}?tab=play`}>
            Play {featuredDemo.title}
            <ArrowRight aria-hidden="true" className="size-4" />
          </Link>
        </section>
      ) : null}

      {/* ── Move along the ranking ─────────────────────────────────────── */}
      <nav aria-label="Other verticals" className="mt-12 grid gap-3 sm:grid-cols-2">
        {previous ? (
          <Link
            aria-label={`Previous: ${previous.title}`}
            className={`${s.cardLink} sm:items-start`}
            to={routes.vertical(previous.slug)}
          >
            <span className={`${s.label} inline-flex items-center gap-1.5`}>
              <ArrowLeft aria-hidden="true" className="size-3.5" />
              Rank {pad2(previous.rank)}
            </span>
            <span className={`${s.h3} mt-1.5`}>{previous.title}</span>
          </Link>
        ) : (
          <span />
        )}
        {next ? (
          <Link
            aria-label={`Next: ${next.title}`}
            className={`${s.cardLink} sm:col-start-2 sm:items-end sm:text-right`}
            to={routes.vertical(next.slug)}
          >
            <span className={`${s.label} inline-flex items-center gap-1.5`}>
              Rank {pad2(next.rank)}
              <ArrowRight aria-hidden="true" className="size-3.5" />
            </span>
            <span className={`${s.h3} mt-1.5`}>{next.title}</span>
          </Link>
        ) : null}
      </nav>
    </main>
  );
}
