import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { lazy, Suspense, useEffect, useState, type ReactNode } from "react";
import { Wordmark } from "@/components/pbps/brand";
import { DeveloperFooter } from "@/components/pbps/developer-footer";
import { Button } from "@/components/ui/button";
import { getPublicStats, type PublicStats } from "@/api/public";
import { fmtInt, fmtPct } from "@/lib/format";

/** The charts are loaded after the text, so the page opens fast on a slow connection. */
const Evidence = lazy(() => import("@/components/public/evidence"));

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "PBPS | Skills for Jobs, monitored and independently verified" },
      {
        name: "description",
        content:
          "Public results of the Performance Based Payment Scheme of the Skills for Jobs component of the EASE Project in Ethiopia: enrolment, attendance, completion and certification, and how they are verified.",
      },
      {
        property: "og:title",
        content: "PBPS: Skills for Jobs, monitored and independently verified",
      },
      {
        property: "og:description",
        content:
          "Programme results, indicators, verification method and governance, published openly.",
      },
      { property: "og:type", content: "website" },
    ],
  }),
  component: Index,
});

const NAV = [
  ["about", "Programme"],
  ["results", "Results"],
  ["people", "Participants"],
  ["indicators", "Indicators"],
  ["verification", "Verification"],
  ["system", "System"],
  ["feedback", "Feedback"],
] as const;

function Index() {
  const q = useQuery({
    queryKey: ["public", "stats"],
    queryFn: getPublicStats,
    staleTime: 600_000,
  });
  const d = q.data;
  return (
    <div className="min-h-screen scroll-smooth text-[16px] leading-[26px]">
      <a
        href="#main"
        className="sr-only focus:not-sr-only focus:absolute focus:left-4 focus:top-3 focus:z-50 focus:rounded focus:bg-card focus:px-3 focus:py-2"
      >
        Skip to content
      </a>
      <Header />
      <main id="main">
        <Hero d={d} failed={q.isError} />
        <About />
        {q.isError ? (
          <Section id="results" title="Results to date">
            <p className="rounded-xl border bg-card p-5">
              The public figures cannot be loaded at the moment.{" "}
              <button
                type="button"
                className="text-primary underline"
                onClick={() => void q.refetch()}
              >
                Try again
              </button>
            </p>
          </Section>
        ) : d ? (
          <Suspense fallback={<Waiting />}>
            <Evidence d={d} />
          </Suspense>
        ) : (
          <Waiting />
        )}
        <Indicators d={d} />
        <Verification />
        <Governance />
        <System />
        <Feedback d={d} />
        <Faq />
      </main>
      <Footer />
    </div>
  );
}
function Waiting() {
  return (
    <div className="mx-auto grid max-w-6xl gap-5 px-6 py-16 md:grid-cols-2" aria-busy="true">
      {[0, 1, 2, 3].map((i) => (
        <div key={i} className="shimmer h-64 rounded-xl" />
      ))}
    </div>
  );
}
function Header() {
  const [open, setOpen] = useState(false);
  return (
    <header className="sticky top-0 z-30 border-b bg-background">
      <div className="mx-auto flex h-16 max-w-6xl items-center justify-between gap-6 px-6">
        <a href="#main" aria-label="PBPS MIS, top of page">
          <Wordmark />
        </a>
        <nav aria-label="Sections" className="hidden gap-5 text-[14px] lg:flex">
          {NAV.map(([id, l]) => (
            <a key={id} href={`#${id}`} className="py-2 hover:text-primary">
              {l}
            </a>
          ))}
        </nav>
        <div className="flex items-center gap-2">
          <Button
            variant="ghost"
            className="lg:hidden"
            aria-expanded={open}
            aria-controls="menu"
            onClick={() => setOpen(!open)}
          >
            Menu
          </Button>
          <Button asChild>
            <Link to="/login">Sign in</Link>
          </Button>
        </div>
      </div>
      {open && (
        <nav id="menu" aria-label="Sections" className="grid border-t px-6 py-2 lg:hidden">
          {NAV.map(([id, l]) => (
            <a key={id} href={`#${id}`} className="py-2" onClick={() => setOpen(false)}>
              {l}
            </a>
          ))}
        </nav>
      )}
    </header>
  );
}
/** Terraced hillsides of the Ethiopian highlands, the programme's mark, drawn wide. */
function Terraces() {
  return (
    <svg
      viewBox="0 0 1200 320"
      preserveAspectRatio="none"
      className="pointer-events-none absolute inset-x-0 bottom-0 h-64 w-full"
      aria-hidden="true"
    >
      {[0, 1, 2, 3, 4, 5, 6].map((i) => (
        <path
          key={i}
          d={`M0 ${150 + i * 28} C 200 ${40 + i * 34}, 380 ${250 + i * 12}, 620 ${150 + i * 27} S 1000 ${30 + i * 40}, 1200 ${130 + i * 30} V320 H0 Z`}
          fill="white"
          fillOpacity={0.035}
          stroke="white"
          strokeOpacity={0.12}
          vectorEffect="non-scaling-stroke"
        />
      ))}
    </svg>
  );
}
const month = (d?: string | null) =>
  d
    ? new Date(`${d.slice(0, 10)}T00:00:00Z`).toLocaleDateString("en-GB", {
        month: "long",
        year: "numeric",
        timeZone: "UTC",
      })
    : "";

function Hero({ d, failed }: { d: PublicStats | undefined; failed: boolean }) {
  const facts: [string, string | undefined][] = [
    ["young people enrolled", d && fmtInt(d.trainees)],
    ["of them women", d && fmtPct((d.female / d.trainees) * 100)],
    ["completed training", d && fmtInt(d.journey[2]?.value)],
    ["certified", d && fmtInt(d.journey[3]?.value)],
  ];
  return (
    <section
      className="relative overflow-hidden text-white"
      style={{ background: "var(--gradient-hero)" }}
    >
      <Terraces />
      <div className="relative mx-auto max-w-6xl px-6 pb-20 pt-16 sm:pt-24">
        <p className="max-w-2xl text-[15px] text-white/85">
          Performance Based Payment Scheme, Skills for Jobs component of the EASE Project, Ethiopia.
          Financed by the World Bank.
        </p>
        <h1 className="mt-5 max-w-3xl text-balance font-display text-4xl font-bold leading-[1.08] tracking-tight sm:text-6xl">
          Skills that lead to jobs, paid for by results that are verified
        </h1>
        <p className="mt-6 max-w-2xl text-lg leading-8 text-white/90">
          Young Ethiopians are trained in digital skills. Training providers are measured on what
          their trainees achieve, and reported results are checked by an independent verification
          team.
        </p>
        <div className="mt-8 flex flex-wrap gap-3">
          <Button asChild size="lg" className="bg-white text-primary hover:bg-white/90">
            <a href="#results">See the results</a>
          </Button>
          <Button
            asChild
            size="lg"
            variant="outline"
            className="border-white/60 bg-transparent text-white hover:bg-white/10 hover:text-white"
          >
            <a href="#verification">How results are verified</a>
          </Button>
        </div>
        {!failed && (
          <dl className="mt-14 grid grid-cols-2 gap-x-8 gap-y-6 border-t border-white/25 pt-6 md:grid-cols-4">
            {facts.map(([l, v]) => (
              <div key={l} className="flex flex-col-reverse justify-end">
                <dt className="text-[15px] text-white/85">{l}</dt>
                <dd className="font-display text-4xl font-bold tabular">
                  {v ?? <span className="inline-block h-9 w-24 rounded bg-white/15" />}
                </dd>
              </div>
            ))}
          </dl>
        )}
        {d && (
          <p className="mt-6 text-[13px] text-white/75">
            Live from the system,{" "}
            {new Date(d.asOf).toLocaleString("en-GB", { dateStyle: "long", timeStyle: "short" })}.
            Training runs from {month(d.classes.from)} to {month(d.classes.to)}.
          </p>
        )}
      </div>
    </section>
  );
}
function Section({
  id,
  title,
  intro,
  tone,
  children,
}: {
  id: string;
  title: string;
  intro?: ReactNode;
  tone?: boolean;
  children: ReactNode;
}) {
  return (
    <section id={id} className={`scroll-mt-16 ${tone ? "border-y bg-surface-2/60" : ""}`}>
      <div className="mx-auto max-w-6xl px-6 py-16 sm:py-20">
        <h2 className="max-w-3xl text-balance font-display text-3xl font-bold leading-tight tracking-tight sm:text-4xl">
          {title}
        </h2>
        {intro && <p className="mt-4 max-w-[68ch] text-muted-foreground">{intro}</p>}
        <div className="mt-10">{children}</div>
      </div>
    </section>
  );
}
function About() {
  const steps: [string, string][] = [
    [
      "Contract",
      "A training provider signs a contract with a target number of trainees and agreed results.",
    ],
    [
      "Enrol",
      "Young people aged 18 to 29 register with their consent. Eligibility is checked by rule.",
    ],
    [
      "Train",
      "Classes follow a published calendar and attendance is recorded for each session day.",
    ],
    [
      "Report",
      "Dropout, completion, certification, employment and retention are reported for the whole class.",
    ],
    ["Verify", "A statistical sample of trainees is contacted by an independent team."],
    [
      "Decide",
      "Reported and verified results are compared with the targets. They inform performance-based payment.",
    ],
  ];
  return (
    <Section
      id="about"
      title="Financing that follows results"
      intro="Under a performance-based payment scheme, funding is linked to outcomes rather than to activities alone. This makes three things necessary: indicators that everyone understands in the same way, data recorded at the source, and verification by a party that did not deliver the training."
    >
      <ol className="grid gap-x-10 gap-y-8 sm:grid-cols-2 lg:grid-cols-3">
        {steps.map(([t, x], i) => (
          <li key={t} className="border-t-2 border-primary pt-4">
            <h3 className="font-display text-lg font-semibold">
              {i + 1}. {t}
            </h3>
            <p className="mt-1 text-muted-foreground">{x}</p>
          </li>
        ))}
      </ol>
    </Section>
  );
}
function Indicators({ d }: { d: PublicStats | undefined }) {
  const groups: [string, (no: number) => boolean][] = [
    ["Readiness and enrolment", (n) => n <= 7],
    ["Delivery and learning", (n) => n >= 8 && n <= 13],
    ["Employment and accountability", (n) => n >= 14],
  ];
  return (
    <Section
      id="indicators"
      title="Eighteen indicators, from contract to lasting employment"
      intro="Each indicator has a written protocol: an operational definition, data sources, frequency, method of computation and disaggregation. A definition can only change through an approved new version, and every earlier version is kept."
    >
      <div className="grid gap-10 lg:grid-cols-3">
        {groups.map(([t, has]) => (
          <div key={t}>
            <h3 className="font-display text-lg font-semibold">{t}</h3>
            <ol className="mt-3 divide-y border-y text-[15px] leading-6">
              {d
                ? d.indicators
                    .filter((i) => has(i.no))
                    .map((i) => (
                      <li key={i.no} className="grid grid-cols-[2rem_1fr] py-2.5">
                        <span className="tabular text-muted-foreground">{i.no}</span>
                        <span>{i.name}</span>
                      </li>
                    ))
                : [1, 2, 3, 4].map((i) => <li key={i} className="shimmer my-2 h-6 rounded" />)}
            </ol>
          </div>
        ))}
      </div>
    </Section>
  );
}
function Verification() {
  const points: [string, string][] = [
    [
      "Drawn by statistics",
      "The sample size follows Cochran’s formula at 95 % confidence and a 5 % margin of error, corrected for the size of the population and for expected non-response.",
    ],
    [
      "Balanced by design",
      "Samples are stratified by training location and sex, with reserves in each stratum. The random seed is stored, so any draw can be repeated exactly.",
    ],
    [
      "Kept apart from delivery",
      "Training providers cannot see who is sampled, which calls are open or what a trainee answered.",
    ],
    [
      "Reviewed by a second person",
      "A result recorded by one person is approved by another before it counts.",
    ],
    [
      "Decided against the target",
      "The verified rate is read with its confidence interval. Where the first sample is inconclusive, a second one can be drawn.",
    ],
    [
      "Never rewritten",
      "A finished verification is closed. The target, the method and the answers used are kept with it.",
    ],
  ];
  return (
    <Section
      id="verification"
      tone
      title="A reported result is a claim until it has been verified"
      intro="Claimed and verified results are stored and shown separately. The verification method is the same for every provider and is fixed before the data are collected."
    >
      <dl className="grid gap-x-12 gap-y-8 md:grid-cols-2">
        {points.map(([t, x]) => (
          <div key={t}>
            <dt className="font-display text-lg font-semibold">{t}</dt>
            <dd className="mt-1 text-muted-foreground">{x}</dd>
          </div>
        ))}
      </dl>
    </Section>
  );
}
function Governance() {
  const rows: [string, string, string][] = [
    [
      "World Bank",
      "Financing partner",
      "Views programme results, indicators and reports. Cannot change any record.",
    ],
    [
      "Entrepreneurship Development Institute and Ministry of Labor and Skills",
      "Programme owner and implementing institution",
      "Contracts providers, oversees delivery and reviews performance.",
    ],
    [
      "Monitoring and evaluation team",
      "Data quality and reporting",
      "Reviews evidence, approves corrections, manages indicators and targets.",
    ],
    [
      "Independent verification team",
      "Verification",
      "Draws samples, contacts trainees and determines verified results.",
    ],
    [
      "Training providers",
      "Delivery",
      "Register trainees, record attendance and report outcomes for their own trainees only.",
    ],
    [
      "Trainees and the public",
      "Feedback",
      "Send feedback or a complaint without an account and follow the answer.",
    ],
  ];
  return (
    <Section
      id="governance"
      title="Clear roles, separated duties"
      intro="No institution both reports a result and verifies it. Access is given by role and limited to what that role needs."
    >
      <div className="overflow-x-auto rounded-xl border bg-card">
        <table className="w-full min-w-[640px] text-left text-[15px]">
          <thead className="bg-surface-2 text-[14px] text-muted-foreground">
            <tr>
              {["Party", "Role", "What it does in the system"].map((h) => (
                <th key={h} scope="col" className="px-5 py-3 font-medium">
                  {h}
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y">
            {rows.map(([a, b, c]) => (
              <tr key={a} className="align-top">
                <th scope="row" className="px-5 py-3.5 font-semibold">
                  {a}
                </th>
                <td className="px-5 py-3.5">{b}</td>
                <td className="px-5 py-3.5 text-muted-foreground">{c}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Section>
  );
}
function System() {
  const does = [
    [
      "Registration",
      "Single entry or file import, with checks on identity, age, education, consent and possible duplicates.",
    ],
    [
      "Attendance",
      "Daily marks per class, aware of holidays and approved breakdowns. A missing day stops later reports.",
    ],
    [
      "Outcome reporting",
      "Six reports in a fixed order. Anyone below 80 % attendance must be reported as a dropout.",
    ],
    [
      "Activities and evidence",
      "Inception reports, assessments and other deliverables with their documents and reviews.",
    ],
    [
      "Indicators and targets",
      "Calculated by the system from the source records, for the programme and each contract.",
    ],
    [
      "Grievance redress",
      "Public intake, response deadlines, escalation and a record of every answer.",
    ],
  ];
  const safe = [
    [
      "Tamper-evident audit trail",
      "Every change is chained to the one before it, so an alteration of history can be detected.",
    ],
    [
      "Corrections stay visible",
      "A corrected report becomes a new version. The earlier one is kept.",
    ],
    [
      "Role-based access",
      "Provider accounts see only their own provider, site or class. Two-step verification can be required.",
    ],
    [
      "Protected personal data",
      "Names and phone numbers are shown only to those who need them. None are published here.",
    ],
    [
      "Tested backups",
      "Automatic backups are restored into a test database and compared before they count as good.",
    ],
    [
      "Automatic data checks",
      "The system looks for missing, contradictory and duplicate data and lists what to correct.",
    ],
  ];
  return (
    <Section
      id="system"
      tone
      title="One system of record, from registration to verified result"
      intro="The Management Information System follows each trainee from registration to the last result. Each figure on this page is calculated from individual records in the system."
    >
      <div className="grid gap-12 lg:grid-cols-2">
        {(
          [
            ["What it covers", does],
            ["How the data are protected", safe],
          ] as const
        ).map(([t, list]) => (
          <div key={t}>
            <h3 className="font-display text-xl font-semibold">{t}</h3>
            <dl className="mt-4 divide-y border-y">
              {list.map(([a, b]) => (
                <div key={a} className="grid gap-x-6 py-3.5 sm:grid-cols-[11rem_1fr]">
                  <dt className="font-semibold">{a}</dt>
                  <dd className="text-muted-foreground">{b}</dd>
                </div>
              ))}
            </dl>
          </div>
        ))}
      </div>
    </Section>
  );
}
function Feedback({ d }: { d: PublicStats | undefined }) {
  return (
    <section
      id="feedback"
      className="scroll-mt-16 text-white"
      style={{ background: "var(--gradient-hero)" }}
    >
      <div className="mx-auto grid max-w-6xl gap-10 px-6 py-16 sm:py-20 lg:grid-cols-[1.4fr_1fr]">
        <div>
          <h2 className="text-balance font-display text-3xl font-bold leading-tight tracking-tight sm:text-4xl">
            Anyone can raise a concern
          </h2>
          <p className="mt-4 max-w-[60ch] text-white/90">
            Trainees, families and the public can send a complaint, a question, a suggestion or
            appreciation. Training providers do not see who sent it. You receive a reference number
            to follow the answer.
          </p>
          <div className="mt-7 flex flex-wrap gap-3">
            <Button asChild size="lg" className="bg-white text-primary hover:bg-white/90">
              <Link to="/feedback/new">Send feedback or a complaint</Link>
            </Button>
            <Button
              asChild
              size="lg"
              variant="outline"
              className="border-white/60 bg-transparent text-white hover:bg-white/10 hover:text-white"
            >
              <Link to="/feedback/status" search={{ ref: "" }}>
                Follow a case
              </Link>
            </Button>
          </div>
        </div>
        {d && d.feedback.total > 0 && (
          <dl className="grid content-center gap-6 border-white/25 lg:border-l lg:pl-10">
            {[
              [fmtInt(d.feedback.total), "cases received"],
              [fmtInt(d.feedback.resolved), "answered and resolved"],
            ].map(([v, l]) => (
              <div key={l} className="flex flex-col-reverse justify-end">
                <dt className="text-white/85">{l}</dt>
                <dd className="font-display text-4xl font-bold tabular">{v}</dd>
              </div>
            ))}
          </dl>
        )}
      </div>
    </section>
  );
}
function Faq() {
  const items: [string, string][] = [
    [
      "Who can join the training?",
      "People aged 18 to 29 with at least secondary-level education, including those who left high school, who are not working, work occasionally or are underemployed. Consent to data use and to being contacted for verification is required.",
    ],
    [
      "Are the published results verified?",
      "Figures are published as reported by the providers and calculated by the system. A verified value is shown next to the reported one once verification of that indicator is finished.",
    ],
    [
      "Why is the completion rate not the share of all enrolled trainees?",
      "Rates follow the indicator protocol. Completion, for example, compares completers with the contracted number of trainees of the providers that have reported, and a provider counts at most up to its contracted number.",
    ],
    [
      "Why are there no results per training provider?",
      "Provider results are part of a contractual relationship and are not published. Only programme totals are shown.",
    ],
    [
      "How is the privacy of trainees protected?",
      "This page shows totals only. A group of fewer than 10 people is combined with another one, so nobody can be identified.",
    ],
    [
      "How often are the figures updated?",
      "They are read from the live system and refreshed at least every ten minutes.",
    ],
  ];
  return (
    <Section id="faq" title="Questions and answers">
      <div className="max-w-3xl divide-y border-y">
        {items.map(([q, a]) => (
          <details key={q} className="group py-4">
            <summary className="flex cursor-pointer list-none items-center justify-between gap-4 font-semibold [&::-webkit-details-marker]:hidden">
              {q}
              <span aria-hidden="true" className="text-xl text-primary group-open:rotate-45">
                +
              </span>
            </summary>
            <p className="mt-2 max-w-[65ch] text-muted-foreground">{a}</p>
          </details>
        ))}
      </div>
    </Section>
  );
}
function Footer() {
  // The year is set in the browser, so the server's page and the visitor's page never differ.
  const [year, setYear] = useState("");
  useEffect(() => setYear(String(new Date().getFullYear())), []);
  return (
    <footer className="border-t">
      <div className="mx-auto grid max-w-6xl gap-8 px-6 py-12 text-[14px] text-muted-foreground md:grid-cols-[1.6fr_1fr_1fr]">
        <div>
          <Wordmark />
          <p className="mt-4 max-w-[52ch]">
            Performance Based Payment Scheme, Skills for Jobs component of the EASE Project.
            Personal data are processed only for programme monitoring and verification.
          </p>
        </div>
        <nav aria-label="On this page" className="grid content-start gap-1.5">
          {NAV.slice(0, 5).map(([id, l]) => (
            <a key={id} href={`#${id}`} className="hover:text-primary">
              {l}
            </a>
          ))}
        </nav>
        <nav aria-label="Services" className="grid content-start gap-1.5">
          <Link to="/feedback/new" className="hover:text-primary">
            Send feedback or a complaint
          </Link>
          <Link to="/feedback/status" search={{ ref: "" }} className="hover:text-primary">
            Follow a case
          </Link>
          <Link to="/login" className="hover:text-primary">
            Sign in
          </Link>
        </nav>
      </div>
      <div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-6 pb-8 text-[12px] text-muted-foreground">
        <p>© {year} PBPS MIS</p>
        <DeveloperFooter />
      </div>
    </footer>
  );
}
