import { conversionKind } from '@/shared/pairs'
import { FormatChip } from '@/shared/brand'
import { RAW_INPUTS, FORMATS, type Format } from '@/shared/formats'
import { SOURCE_FORMATS, CATEGORIES, pairsFromFormat, sourceFormatForPath, type CategoryId } from '@/shared/catalog'
import { PAIRS, pairBySlug, pairLabel, relatedPairs, targetsFor, type Pair } from '@/shared/pairs'
import { ArrowRightIcon } from 'lucide-react'
import { useState, type ComponentType, type ReactNode } from 'react'
import { AccountIsland } from './account/island'
import { ConverterFrame, FaqList, PairCard, Steps, TrustStrip } from './components/site'
import { MEASURED, MEASURED_ON, type Measured } from './content/measured'
import { contentFor } from './content/pair-content'
import { SITE_FAQ } from './content/site-faq'
import { Breadcrumb, Container, Hero, Shell, updatedLabel } from './layout'

export interface PageMeta {
  path: string
  title: string
  description: string
  /** Kept out of search results and the sitemap. */
  noindex?: boolean
  /** A guide or benchmark (listed under Guides in llms.txt). */
  guide?: boolean
  breadcrumb?: string
  pair?: Pair
  category?: CategoryId
  format?: Format
}

const STATIC: PageMeta[] = [
  { path: '/benchmarks/page-image-quality', title: 'Office and PDF to PNG/JPG: Printed Page Quality Tests · Tabmorph', description: 'Original page geometry and ICC controls, actual offline browser downloads, physical-resolution metadata and independent readers. CloudConvert quality unverified.', breadcrumb: 'Page image tests', guide: true },
  { path: '/benchmarks/rtf-pdf-quality', title: 'RTF to PDF Tests: Layout, Text and Embedded Images · Tabmorph', description: 'Original RTF fixtures, actual offline browser PDFs and independent readers. Concrete page, font and image limits; CloudConvert comparisons remain unverified.', breadcrumb: 'RTF PDF tests', guide: true },
  { path: '/benchmarks/rtf-content-quality', title: 'RTF Text, HTML and Markdown: Original-File Quality Tests · Tabmorph', description: 'Two original RTF sources, three same-input CloudConvert references and independent Unicode, formatting, table, image and link checks. Review concrete body-extraction limits.', breadcrumb: 'RTF content tests', guide: true },
  { path: '/benchmarks/odf-pdf-quality', title: 'OpenDocument PDF Tests: ODT, ODS and ODP Layout · Tabmorph', description: 'Original standards-valid ODF fixtures and real offline browser PDFs, checked by independent readers for text, pages, images and links. CloudConvert comparisons remain unverified.', breadcrumb: 'OpenDocument PDF tests', guide: true },
  { path: '/benchmarks/word-editable-quality', title: 'Editable RTF, DOCX and ODT Tests and Limits · Tabmorph', description: 'Original source documents, offline browser exports, independent readers and concrete fidelity limits. CloudConvert quality remains unverified.', breadcrumb: 'Editable document tests', guide: true },
  { path: '/benchmarks/doc-import-quality', title: 'DOC Import Tests and Fidelity Limits · Tabmorph', description: 'Independent binary Word source controls, actual outputs, backgrounds, pictures and retained limitations. Competitive quality remains unverified.', breadcrumb: 'DOC import tests', guide: true },
  { path: '/benchmarks/doc-quality', title: 'DOC Export Tests, Version Checks and Limits · Tabmorph', description: 'Original document controls, independent DOC readers, version metadata and exact embedded images. Comparative quality remains unverified.', breadcrumb: 'DOC export tests', guide: true },
  { path: '/benchmarks/table-pdf-quality', title: 'CSV and TSV PDF Tests: Literal Values, Pagination and Reader Limits · Tabmorph', description: 'Actual isolated browser table PDFs, independent CSV, OOXML and PDF readers, complete cell checks, page settings and retained Unicode extraction limitations. CloudConvert quality is unverified.', breadcrumb: 'Table PDF tests', guide: true },
  { path: '/benchmarks/postscript-quality', title: 'EPS and PostScript Tests: Raster Pixels and Native Rendering · Tabmorph', description: 'Independent ASCII85, zlib, Pillow and Ghostscript checks for EPS and PS exports. Review actual browser downloads, image placement, pixel limits and unverified competitive quality.', breadcrumb: 'EPS and PostScript tests', guide: true },
  { path: '/benchmarks/office-quality', title: 'Office PDF Tests: Excel Dates, Fonts and CloudConvert Comparisons · Tabmorph', description: 'Same-input Office PDF comparisons with CloudConvert, 672 separate Excel value references, original font checks and retained historical-date, reader and quota limitations.', breadcrumb: 'Office PDF tests', guide: true },
  {path:'/benchmarks/spreadsheet-quality',title:'Spreadsheet Conversion Tests: Dates, Number Formats and Saved Values · Tabmorph',description:'Independent Excel and ODS readers, original fixtures, retained number-format fixes and XLSM macro omission. Review tested date systems and concrete formatting limits.',breadcrumb:'Spreadsheet conversion tests',guide:true},
  {path:'/benchmarks/epub-quality',title:'EPUB Tests: Reading Order, Unicode and Package Validity · Tabmorph',description:'Independent EPUB 2/3 fixtures, W3C EPUBCheck, document content and embedded-image tests, retained Markdown fixes and concrete reflow limits.',breadcrumb:'EPUB conversion tests',guide:true},
  { path: '/benchmarks/svg-quality', title: 'SVG and SVGZ Tests: Original Size, Document Bytes and Rendering · Tabmorph', description: 'Independent gzip and native resvg checks, original-size SVG fixes, rendering-size curves and PDF limitations. Download reproducible source files and measurements.', breadcrumb: 'SVG and SVGZ tests', guide: true },
  { path: '/benchmarks/icns-quality', title: 'Mac Icon Tests: ICNS Sizes, Native Readers and TIFF Alpha · Tabmorph', description: 'Independent Apple iconutil and Pillow checks for ICNS export, Retina sizes, transparency and legacy entries. Retained TIFF alpha fixes and unverified competitive status.', breadcrumb: 'Mac icon tests', guide: true },
  { path: '/benchmarks/photoshop-quality', title: 'PSD and PSB Tests: Pixels, RAW Precision and Preview Limits · Tabmorph', description: 'Independent PSD sample and layer checks, PSB saved-composite tests and concrete reader limits. Download synthetic files and inspect 16-bit RAW exports and unverified competitive status.', breadcrumb: 'Photoshop image tests', guide: true },
  { path: '/benchmarks/text-pdf-quality', title: 'Text to PDF Tests: Unicode, Fonts and Page Bounds · Tabmorph', description: 'Reproducible text PDF tests with native readers, embedded font outlines and HarfBuzz positioning. Download before and after outputs and review supported scripts and limitations.', breadcrumb: 'Text PDF tests', guide: true },
  { path: '/benchmarks/video-quality', title: 'Video Conversion Tests: Detail, Timing, HDR and Audio · Tabmorph', description: 'Independent video decoding, sample and timing checks, quality-size curves and one identical-file CloudConvert reference. Review the retained H.264 gap and downloadable evidence.', breadcrumb: 'Video conversion tests', guide: true },
  { path: '/benchmarks/archive-quality', title: 'Archive Conversion Tests: Names, Links and Metadata · Tabmorph', description: 'Three same-file archive comparisons with CloudConvert, independent output readers and downloadable sources. See Unicode ZIP behavior, symbolic links, metadata losses and offline archive limits.', breadcrumb: 'Archive conversion tests', guide: true },
  { path: '/', title: 'Tabmorph: Convert Files Privately in Your Browser', description: 'Free file converter that never uploads your files. HEIC to JPG, WebP to PNG, PDF to PNG, PNG to PDF and more, converted on your device.' },
  { path: '/all-converters', title: 'Free File Converters by Source Format · Tabmorph', description: 'Choose your source file format, then select a supported output. Browse free video, audio, RAW, image, PDF, document, data and archive converters. Files stay on your device.', breadcrumb: 'All converters' },
  { path: '/how-it-works', title: 'How Tabmorph Converts Files Without Uploading Them', description: 'Tabmorph converts files inside your browser tab. Here is how it works, how to check that nothing is uploaded, and why the converter runs in its own frame.', breadcrumb: 'How it works' },
  { path: '/privacy', title: 'Privacy · Tabmorph', description: 'Tabmorph never uploads, stores or sees your files. What the site does and doesn’t collect.', breadcrumb: 'Privacy' },
  { path: '/licenses', title: 'Open-Source Licenses · Tabmorph', description: 'The open-source software Tabmorph uses to convert files in your browser, with licenses and source code links.', breadcrumb: 'Licenses' },
  { path: '/about', title: 'About Tabmorph', description: 'Tabmorph is a small, independent file converter built so that converting a file never means uploading it.', breadcrumb: 'About' },
  { path: '/benchmarks/raw-quality', title: 'RAW Quality Tests: Highlights and Portrait Orientation · Tabmorph', description: 'Three same-file RAW comparisons with CloudConvert: calibrated 16-bit DNG values, highlight clipping and portrait orientation in Chromium and WebKit. Download evidence and hashes.', breadcrumb: 'RAW quality tests', guide: true },
  { path: '/benchmarks/jpeg-quality', title: 'JPEG Quality: Full Color, Compact and CloudConvert Tests · Tabmorph', description: 'Six same-file JPEG comparisons with original sources, downloads, PSNR/SSIM, color sampling and file-size curves. Compare Full color and Compact settings with measured limits.', breadcrumb: 'JPEG quality tests', guide: true },
  { path: '/benchmarks/audio-quality', title: 'Audio Quality Tests: Tabmorph vs CloudConvert · Tabmorph', description: 'Four same-file audio tests with independent PCM decoding: FLAC preservation, 24-bit AIFF retention and matched 192 kbps MP3. Download source files, outputs and hashes.', breadcrumb: 'Audio quality tests', guide: true },
  { path: '/guides/raw-to-jpg-or-16-bit-png', title: 'RAW to JPG, 16-bit PNG or TIFF: Precision and Settings · Tabmorph', description: 'Render camera RAW privately to JPG or true 16-bit PNG/TIFF. Compare precision, white balance, exposure, camera support and memory limits, with downloadable test fixtures.', breadcrumb: 'RAW image precision and settings', guide: true },
  { path: '/heic-vs-jpg-vs-png', title: 'HEIC vs JPG vs PNG: File Size, Speed and Quality Compared · Tabmorph', description: 'Choose HEIC, JPG or PNG for sharing, editing and web images. Understand compression, transparency, color detail and why output sizes vary, with reproducible JPEG tests.', breadcrumb: 'HEIC vs JPG vs PNG', guide: true },
  { path: '/guides/stop-iphone-saving-heic', title: 'How to Stop Your iPhone Saving Photos as HEIC · Tabmorph', description: 'Switch your iPhone camera to JPG in Settings → Camera → Formats, what you give up, and how to convert the HEIC photos you already have.', breadcrumb: 'Stop your iPhone saving HEIC', guide: true },
  { path: '/guides/check-if-a-converter-uploads-your-files', title: 'How to Check Whether a File Converter Uploads Your Files · Tabmorph', description: 'Two tests anyone can do in a minute, the Wi-Fi test and the browser’s Network tab, plus the warning signs that a converter sends your files to a server.', breadcrumb: 'Does a converter upload your files?', guide: true },
  { path: '/login', title: 'Sign In · Tabmorph', description: 'Sign in to Tabmorph with a link sent to your email.', noindex: true },
  { path: '/admin', title: 'Admin · Tabmorph', description: 'Tabmorph admin panel.', noindex: true },
]

function sourcePageMeta(f: Format): PageMeta {
  return { path: `/${f}-converter`, title: `${FORMATS[f].label} Converter: Free Online Tools · Tabmorph`, description: `Convert ${FORMATS[f].label} files to supported output formats with free browser tools. Choose an output, review settings and format limits, and convert on your device.`, breadcrumb: `${FORMATS[f].label} converter`, format: f }
}

export const PAGES: PageMeta[] = [
  ...STATIC,
  ...CATEGORIES.map((c) => {
    const source = sourceFormatForPath(c.path)
    return source ? sourcePageMeta(source) : { path: c.path, title: `Free ${c.label} Online, No Upload · Tabmorph`, description: c.description, breadcrumb: c.label, category: c.id }
  }),
  ...SOURCE_FORMATS.filter((f) => !CATEGORIES.some((c) => c.path === `/${f}-converter`)).map(sourcePageMeta),
  ...PAIRS.map((p) => {
    const c = contentFor(p)
    return { path: `/${p.slug}`, title: c.title, description: c.description, noindex: !p.index, breadcrumb: pairLabel(p), pair: p }
  }),
]

export const pageFor = (path: string) => PAGES.find((p) => p.path === (path.replace(/\/$/, '') || '/'))

export function HomePage() {
  const popular = PAIRS.filter((p) => p.index).sort((a, b) => (b.volume ?? 0) - (a.volume ?? 0)).slice(0, 12)
  return (
    <Shell>
      <Hero
        eyebrow={<span className="rounded-full border bg-card px-3 py-1 text-xs font-medium text-muted-foreground">Free · No upload · Works offline</span>}
        h1="Convert files without uploading them"
        lead="Audio, camera RAW, photos, PDFs, fonts, spreadsheets and more, converted right in your browser. Your files stay on your device."
      >
        <ConverterFrame slug="" title="Tabmorph file converter" />
      </Hero>
      <Container className="mt-16 space-y-20">
        <TrustStrip />
        <CategoryLinks />
        <section aria-labelledby="popular">
          <div className="flex items-end justify-between gap-4">
            <h2 id="popular" className="text-2xl font-semibold tracking-tight">
              Popular converters
            </h2>
            <a href="/all-converters" className="flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground">
              All converters <ArrowRightIcon className="size-3.5" />
            </a>
          </div>
          <div className="mt-6 grid gap-3 sm:grid-cols-2">
            {popular.map((p) => (
              <PairCard key={p.slug} pair={p} />
            ))}
          </div>
        </section>
        <PrivacyExplainer />
        <FaqList faq={SITE_FAQ} />
      </Container>
    </Shell>
  )
}

function PrivacyExplainer() {
  return (
    <section aria-labelledby="private" className="grid gap-8 rounded-3xl border bg-card p-6 sm:p-8 md:grid-cols-2 md:items-center">
      <div>
        <h2 id="private" className="text-2xl font-semibold tracking-tight">
          Private by design, not by promise
        </h2>
        <p className="mt-3 text-[15px] leading-relaxed text-muted-foreground">
          Most converters upload your file to a server. Tabmorph does the work in your browser instead. The converter also runs on its own site inside this page, so nothing else on the page can see what you drop into it.
        </p>
        <a href="/how-it-works" className="mt-4 inline-flex items-center gap-1 text-sm font-medium underline-offset-4 hover:underline">
          How it works <ArrowRightIcon className="size-3.5" />
        </a>
      </div>
      <div aria-hidden className="rounded-2xl border border-dashed p-4">
        <p className="font-mono text-xs text-muted-foreground">tabmorph.com · the page you’re reading</p>
        <div className="mt-3 rounded-xl border-2 border-brand/50 bg-brand-soft/50 p-4">
          <p className="font-mono text-xs font-semibold text-accent-foreground">tabmorph.app · the converter</p>
          <div className="mt-3 flex items-center gap-2 text-sm">
            <span className="rounded-md bg-card px-2 py-1 shadow-sm">photo.heic</span>
            <ArrowRightIcon className="size-3.5 text-muted-foreground" />
            <span className="rounded-md bg-card px-2 py-1 shadow-sm">photo.jpg</span>
          </div>
          <p className="mt-3 text-xs text-muted-foreground">Your file stays in here, on your device.</p>
        </div>
      </div>
    </section>
  )
}

export function PairPage({ pair }: { pair: Pair }) {
  const c = contentFor(pair)
  const from = FORMATS[pair.from]
  const to = FORMATS[pair.to]
  const related = relatedPairs(pair, 6)
  return (
    <Shell>
      <Hero
        eyebrow={
          <span className="flex items-center gap-2">
            <FormatChip format={pair.from} />
            <ArrowRightIcon className="size-3.5 text-muted-foreground" aria-hidden />
            <FormatChip format={pair.to} />
          </span>
        }
        h1={c.h1}
        lead={c.lead}
      >
        <ConverterFrame slug={pair.slug} title={`${pairLabel(pair)} converter`} />
      </Hero>
      <Container className="mt-16 space-y-20">
        <TrustStrip />
        <Steps steps={c.steps} heading={`How to convert ${from.label} to ${to.label}`} />
        {MEASURED[pair.slug] && <MeasuredFacts m={MEASURED[pair.slug]!} heading={`${from.label} to ${to.label}: size and speed`} />}
        {c.sections.length > 0 && (
          <section className="grid gap-4 md:grid-cols-2">
            {c.sections.map((s) => (
              <div key={s.title} className="rounded-2xl border bg-card p-6">
                <h2 className="text-lg font-semibold tracking-tight">{s.title}</h2>
                <p className="mt-2 text-[15px] leading-relaxed text-muted-foreground">{s.body}</p>
              </div>
            ))}
          </section>
        )}
        <section aria-labelledby="formats">
          <h2 id="formats" className="text-2xl font-semibold tracking-tight">
            About the formats
          </h2>
          <div className="mt-6 grid gap-4 sm:grid-cols-2">
            {[pair.from, pair.to].map((f) => (
              <div key={f} className="rounded-2xl border bg-card p-6">
                <FormatChip format={f} />
                <p className="mt-3 text-[15px] leading-relaxed text-muted-foreground">{FORMATS[f].about}</p>
              </div>
            ))}
          </div>
        </section>
        <LearnMore pair={pair} />
        <FaqList faq={c.faq} />
        {related.length > 0 && (
          <section aria-labelledby="related">
            <h2 id="related" className="text-2xl font-semibold tracking-tight">
              Related converters
            </h2>
            <div className="mt-6 grid gap-3 sm:grid-cols-2">
              {related.map((p) => (
                <PairCard key={p.slug} pair={p} />
              ))}
            </div>
          </section>
        )}
        <div className="text-sm text-muted-foreground">
          <Breadcrumb label={pairLabel(pair)} />
          <p className="mt-2">Updated {updatedLabel}</p>
        </div>
      </Container>
    </Shell>
  )
}

/** Guides and the benchmark that relate to a converter page. */
function LearnMore({ pair }: { pair: Pair }) {
  const links = [
    ...(conversionKind(pair.from,pair.to)==='text-image' ? [{href:'https://tabmorph.app/benchmarks/text-image1/',label:'Text and Markdown page image tests and limitations'}] : []),
    ...(pair.from==='html' && ['odt','doc','rtf','pdf','docx','epub'].includes(pair.to) ? [{href:'https://tabmorph.app/benchmarks/html-metadata1/',label:'HTML title, author and language tests'}] : []),
    ...(conversionKind(pair.from,pair.to)==='text-office' && pair.from==='html' ? [{href:'https://tabmorph.app/benchmarks/html-office1/',label:'HTML document export tests and limitations'}] : []),
    ...(conversionKind(pair.from,pair.to)==='text-office' && pair.from!=='html' ? [{href:'https://tabmorph.app/benchmarks/text-office1/',label:'Plain text and Markdown document tests and limitations'}] : []),
    ...(pair.from === 'txt' && pair.to === 'md' ? [{ href: 'https://tabmorph.app/benchmarks/text-markdown1/', label: 'Plain-text Markdown tests, CloudConvert references and limitations' }] : []),
    ...(pair.from==='doc' ? [{href:'/benchmarks/doc-import-quality',label:'DOC import tests and limits'}] : []),
    ...(conversionKind(pair.from,pair.to)==='office-editable' ? [{href:pair.to==='doc'?'/benchmarks/doc-quality':'/benchmarks/word-editable-quality',label:'Editable document tests and limits'}] : []),
    ...(['office-image','table-image','pdf-to-image'].includes(conversionKind(pair.from,pair.to)||'') ? [{href:'/benchmarks/page-image-quality',label:'Printed page image tests and limits'}] : []),
    ...(pair.from === 'rtf' && pair.to === 'pdf' ? [{ href: '/benchmarks/rtf-pdf-quality', label: 'RTF PDF tests and concrete limitations' }] : []),
    ...(pair.from === 'rtf' && ['txt','html','md'].includes(pair.to) ? [{ href: '/benchmarks/rtf-content-quality', label: 'RTF content comparisons and concrete limitations' }] : []),
    ...(['odt','ods','odp'].includes(pair.from) && pair.to === 'pdf' ? [{ href: '/benchmarks/odf-pdf-quality', label: 'OpenDocument PDF tests and concrete package limitations' }] : []),
    ...(['csv','tsv'].includes(pair.from) && pair.to === 'pdf' ? [{ href: '/benchmarks/table-pdf-quality', label: 'Table PDF tests: literal values, pagination and independent reader limits' }] : []),
    ...(['docx','xlsx','pptx'].includes(pair.from) && pair.to === 'pdf' ? [{ href: '/benchmarks/office-quality', label: 'Office PDF comparisons: original Excel values, fonts and retained CloudConvert gaps' }] : []),
    ...(['xlsx','xlsm','xls','ods'].includes(pair.from)||['xlsx','xls','ods'].includes(pair.to)||pair.to==='html'&&['csv','tsv','json'].includes(pair.from)?[{href:'/benchmarks/spreadsheet-quality',label:'Spreadsheet tests: number formats, date systems, formulas and macro omission'}]:[]),
    ...(['epub','html','md','docx','odt'].includes(pair.from)||pair.to==='epub'||pair.to==='docx'? [{href:'/benchmarks/epub-quality',label:'EPUB and document tests: reading order, preserved content and package validity'}]:[]),
    ...(['eps', 'ps'].includes(pair.to) ? [{ href: '/benchmarks/postscript-quality', label: 'EPS and PS tests: complete raster checks, native rendering and placement limits' }] : []),
    ...(['svg', 'svgz'].includes(pair.from) || pair.to === 'svgz' ? [{ href: '/benchmarks/svg-quality', label: 'SVG and SVGZ tests: original size, document preservation and rendering limits' }] : []),
    ...(pair.to === 'icns' || pair.from === 'icns' || pair.to === 'tiff' || pair.from === 'tiff' ? [{ href: '/benchmarks/icns-quality', label: 'Mac icon and TIFF alpha tests: native readers, size slots and transparency' }] : []),
    ...(pair.to === 'psd' || pair.from === 'psb' || pair.from === 'psd' ? [{ href: '/benchmarks/photoshop-quality', label: 'PSD and PSB tests: layers, RAW sample precision and preview limits' }] : []),
    ...(pair.from === 'txt' && pair.to === 'pdf' ? [{ href: '/benchmarks/text-pdf-quality', label: 'Text PDF tests: supported characters, glyph positioning and page bounds' }] : []),
    ...(['jpg', 'jfif'].includes(pair.to) ? [{ href: '/benchmarks/jpeg-quality', label: 'JPEG Full color and Compact: measured fidelity and file-size tradeoffs' }] : []),
    ...(RAW_INPUTS.includes(pair.from) ? [{ href: '/benchmarks/raw-quality', label: 'RAW highlight and orientation tests with identical CloudConvert sources' }, { href: '/guides/raw-to-jpg-or-16-bit-png', label: 'RAW to JPG or 16-bit PNG/TIFF: precision, settings and tested cameras' }] : []),
    ...(FORMATS[pair.to].kind === 'audio' ? [{ href: '/benchmarks/audio-quality', label: 'Audio quality tests: source files, outputs and independent measurements' }] : []),
    ...(FORMATS[pair.to].kind === 'video' || FORMATS[pair.from].kind === 'video' && pair.to === 'gif' ? [{ href: '/benchmarks/video-quality', label: 'Video tests: picture detail, timing, HDR, audio and measured limitations' }] : []),
    ...(FORMATS[pair.from].kind === 'archive' ? [{ href: '/benchmarks/archive-quality', label: 'Archive tests: Unicode names, links, metadata and choosing an output' }] : []),
    ...(pair.from === 'heic' ? [{ href: '/guides/stop-iphone-saving-heic', label: 'How to stop your iPhone saving photos as HEIC' }] : []),
    ...(MEASURED[pair.slug] ? [{ href: '/heic-vs-jpg-vs-png', label: 'HEIC vs JPG vs PNG: size, speed and quality compared' }] : []),
    { href: '/guides/check-if-a-converter-uploads-your-files', label: 'How to check whether a converter uploads your files' },
  ]
  return (
    <section aria-labelledby="learn">
      <h2 id="learn" className="text-2xl font-semibold tracking-tight">
        Learn more
      </h2>
      <ul className="mt-4 space-y-2 text-[15px]">
        {links.map((l) => (
          <li key={l.href}>
            <a href={l.href} className="inline-flex items-center gap-1.5 font-medium underline-offset-4 hover:underline">
              {l.label}
              <ArrowRightIcon className="size-3.5" aria-hidden />
            </a>
          </li>
        ))}
      </ul>
    </section>
  )
}

/** Measured sizes and speeds (content/measured.ts), led by a one-sentence answer for readers and AI answers. */
function MeasuredFacts({ m, heading }: { m: Measured; heading: string }) {
  const [label, before, after, time] = m.columns ?? ['Test file', 'Before', 'After', 'Time']
  return (
    <section aria-labelledby="measured">
      <h2 id="measured" className="text-2xl font-semibold tracking-tight">
        {heading}
      </h2>
      <p className="mt-3 text-[15px] leading-relaxed text-muted-foreground">{m.answer}</p>
      <div className="mt-6 overflow-x-auto rounded-2xl border bg-card">
        <table className="w-full text-left text-sm">
          <thead className="bg-muted/50 text-xs text-muted-foreground uppercase">
            <tr>
              <th className="px-4 py-3 font-medium">{label}</th>
              <th className="px-4 py-3 text-right font-medium whitespace-nowrap">{before}</th>
              <th className="px-4 py-3 text-right font-medium whitespace-nowrap">{after}</th>
              <th className="px-4 py-3 text-right font-medium whitespace-nowrap">{time}</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {m.rows.map((r, i) => (
              <tr key={i}>
                <td className="px-4 py-2.5">{r[0]}</td>
                <td className="px-4 py-2.5 text-right whitespace-nowrap tabular-nums">{r[1]}</td>
                <td className="px-4 py-2.5 text-right font-medium whitespace-nowrap tabular-nums">{r[2]}</td>
                <td className="px-4 py-2.5 text-right whitespace-nowrap tabular-nums">{r[3]}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <p className="mt-3 text-xs leading-relaxed text-muted-foreground">
        Historical measurements {MEASURED_ON}. Output sizes and timing vary with the file and current codec version. {m.note} Phones and older computers take longer.
      </p>
    </section>
  )
}

function CategoryLinks() {
  return <section aria-label="Browse by category" className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
    {CATEGORIES.map((c) => {
      const source = sourceFormatForPath(c.path)
      const count = source ? pairsFromFormat(source).length : PAIRS.filter(c.test).length
      return <a key={c.id} href={c.path} className="rounded-2xl border bg-card p-5 hover:border-brand/40">
        <h2 className="font-semibold">{source ? `${FORMATS[source].label} converter` : c.label}</h2><p className="mt-1 text-sm text-muted-foreground">{count} free tools <span aria-hidden>→</span></p>
      </a>
    })}
  </section>
}

function SisterSite() {
  return <aside className="rounded-2xl border bg-muted/30 p-5 text-sm text-muted-foreground">Working with subtitles, timed transcripts or editing projects? <a href="https://cutconvert.com" className="font-medium text-foreground underline underline-offset-4">Visit our sister site CutConvert</a> for caption and post-production converters.</aside>
}

export function AllConvertersPage() {
  const [query, setQuery] = useState('')
  const matches = SOURCE_FORMATS.filter((f) => `${FORMATS[f].label} ${FORMATS[f].accept.join(' ')} ${FORMATS[f].about}`.toLowerCase().includes(query.trim().toLowerCase()))
  return (
    <Shell>
      <Hero h1="All converters" lead="Choose the format you’re converting from. On the next page, select an output or browse its supported conversions. Every file stays on your device." />
      <Container className="mt-12 space-y-12">
        <div>
          <label htmlFor="converter-search" className="text-sm font-medium">Find a source format</label>
          <input id="converter-search" type="search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Try CR3, PNG, MP4 or ZIP" className="mt-2 block w-full rounded-xl border bg-card px-4 py-3" />
          <p role="status" className="mt-2 text-sm text-muted-foreground">{matches.length} source {matches.length === 1 ? 'format' : 'formats'} · free, no account required</p>
        </div>
        <section aria-labelledby="source-formats">
          <h2 id="source-formats" className="text-xl font-semibold">Convert from</h2>
          <div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">{matches.map((f) => {
            const outputs = targetsFor(f).length
            return <a key={f} href={`/${f}-converter`} className="group rounded-2xl border bg-card p-5 transition-colors hover:border-brand/40 hover:bg-muted/30">
              <div className="flex items-center justify-between gap-3"><h3 className="font-semibold">{FORMATS[f].label} converter</h3><ArrowRightIcon className="size-4 shrink-0 text-muted-foreground" aria-hidden /></div>
              <p className="mt-2 text-sm text-muted-foreground">{outputs} output {outputs === 1 ? 'format' : 'formats'}</p>
            </a>
          })}</div>
        </section>
        {matches.length === 0 && <p>No source formats match this search. Try a file extension such as PNG or XLSX.</p>}
        <SisterSite />
      </Container>
    </Shell>
  )
}

export function CatalogPage({ meta }: { meta: PageMeta }) {
  const category = CATEGORIES.find((c) => c.id === meta.category)
  const source = meta.format ?? sourceFormatForPath(meta.path)
  const format = source ? FORMATS[source] : undefined
  const pairs = source ? pairsFromFormat(source) : PAIRS.filter(category!.test)
  const groups = [{ label: format ? `Convert from ${format.label}` : `Available ${category!.label.toLowerCase()}`, pairs }]
  return <Shell>
    <Hero h1={format ? `${format.label} converter` : category!.label} lead={format ? `Choose a ${format.label} file and the format you want to convert it to. Free, private conversion on your device.` : category!.description}>
      {source && targetsFor(source).length > 0 && <ConverterFrame slug={`${source}-converter`} title={`${FORMATS[source].label} converter`} />}
    </Hero>
    <Container className="mt-12 space-y-12">
      <p className="text-muted-foreground">{pairs.length} supported conversions. Free to use, with no account or watermark. Every file is processed on your device.</p>
      {format && <section className="space-y-3 text-muted-foreground"><h2 className="text-xl font-semibold text-foreground">About {format.label} files</h2><p>{format.about}</p></section>}
      {groups.filter((g) => g.pairs.length).map((g) => <section key={g.label}>
        <h2 className="text-xl font-semibold">{g.label}</h2>
        <div className="mt-4 grid gap-3 sm:grid-cols-2">{g.pairs.map((p) => <PairCard key={p.slug} pair={p} />)}</div>
      </section>)}
      <TrustStrip />
      <section className="space-y-3 text-[15px] leading-relaxed text-muted-foreground">
        <h2 className="text-xl font-semibold text-foreground">Choose the right output</h2>
        <p>Open a converter for instructions, settings and the details that survive the conversion. Images, workbook formulas, document formatting and archive metadata have different limits; each tool explains its behavior before you add files.</p>
        <a href="/all-converters" className="inline-block font-medium text-foreground underline underline-offset-4">Browse all converters and formats</a>
      </section>
      <SisterSite />
    </Container>
  </Shell>
}

export function NotFoundPage() {
  return (
    <Shell>
      <Hero h1="Page not found" lead="That page doesn’t exist. You can still drop any file here to convert it.">
        <ConverterFrame slug="" title="Tabmorph file converter" />
      </Hero>
    </Shell>
  )
}

/** `Page` is the route chunk for this path, if it has one (routes.ts), already loaded. */
export function pageBody(path: string, Page?: ComponentType): ReactNode {
  const meta = pageFor(path)
  if (!meta) return <NotFoundPage />
  if (Page) return <Page />
  if (meta.pair) return <PairPage pair={pairBySlug(meta.pair.slug)!} />
  if (meta.category || meta.format) return <CatalogPage meta={meta} />
  switch (meta.path) {
    case '/':
      return <HomePage />
    case '/all-converters':
      return <AllConvertersPage />
    case '/login':
      return <AccountIsland view="login" />
    case '/admin':
      return <AccountIsland view="admin" />
    default:
      return <NotFoundPage />
  }
}
