import type { ReactNode } from 'react'
import { useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Link } from 'react-router-dom'
import { getReleaseManifest } from '../auth/auth-api'
import { BrowserAuthMethodsGuide } from '../components/ui/BrowserAuthMethodsGuide'
import { HyperTwistButtonAnchor, HyperTwistButtonLink } from '../components/ui/HyperTwistButton'
import { ReleaseValidationSummary } from '../components/ui/ReleaseValidationSummary'
import type { ReleaseManifestPlatformView, ReleaseManifestView } from '../release-manifest'
import { resolveReleaseCommerceView, resolveReleaseManifestView } from '../release-manifest'
import {
  brandConfig,
  downloadTargets,
  mplSourceUrl,
  openSourceRepoUrl,
  planCatalog,
  publicDocsUrl,
  releaseNotesUrl,
} from '../site-config'
import {
  browserDesktopDecisionFaqs,
  browserDesktopRealityCards,
  controlProfileRosterCards,
  deliverySurfaceCards,
  higherDimensionalRuntimeGuideCards,
  inputAndDevicePostureCards,
  operatorDesktopQuickstartCards,
  publicManualRouteAtlasCards,
  runtimeControlGuideCards,
  simulatorManualCards,
} from '../site-data'
import {
  buildLoginPath,
  buildProtectedDownloadPath,
  buildRegisterPath,
  buildSupportPath,
  isExternalHref,
} from '../site-routes'

export type SupportTopicGuide = {
  title: string
  description: string
  steps: readonly string[]
  routeFocus: readonly string[]
  actions: ReadonlyArray<{
    label: string
    to: string
  }>
}

export const supportTopicGuidance: Record<string, SupportTopicGuide> = {
  'launch-readiness': {
    title: 'Launch readiness',
    description:
      'Use this path when you need the current website, pricing, download, and legal status before a wider public launch.',
    steps: [
      'Confirm public launch status, checkout readiness, and support contact first.',
      'Review the current desktop target plus packaged proof before promising a release externally.',
      'Keep notices and corresponding-source links visible before a wider launch.',
    ],
    routeFocus: [
      'Launch-status, pricing, and download pages explain public launch status and target selection.',
      'Public notices and terms pages carry the distribution and legal details.',
      'The public manual explains how the website and desktop app work together so launch messaging stays accurate.',
    ],
    actions: [
      { label: 'Open launch status', to: '/launch-status' },
      { label: 'Sign in for desktop downloads', to: buildLoginPath(buildProtectedDownloadPath('windows')) },
      { label: 'Sign in for notices', to: buildLoginPath('/app/notices') },
      { label: 'Open pricing', to: '/pricing' },
    ],
  },
  'operator-access': {
    title: 'Account access',
    description:
      'Use this path when you need sign-up help, account approval, subscription access, or the signed-in desktop download.',
    steps: [
      'Start with sign-in or signup, then confirm whether the issue is account access, entitlement, or desktop pairing.',
      'Use the signed-in dashboard and download center once sign-in succeeds so your account and release status stay attached.',
      'Escalate with the affected plan, requested platform, and whether access, pairing, or package delivery failed.',
    ],
    routeFocus: [
      'Login and signup preserve your next destination so you land in the right dashboard or download view.',
      'The public download page shows release status without exposing raw delivery links.',
      'The public manual explains when the website owns the next step and when the desktop app takes over.',
    ],
    actions: [
      { label: 'Sign in for desktop downloads', to: buildLoginPath(buildProtectedDownloadPath('windows')) },
      { label: 'Create account for desktop access', to: buildRegisterPath(buildProtectedDownloadPath('windows')) },
      { label: 'Open dashboard', to: buildLoginPath('/app') },
    ],
  },
  'studio-rollout': {
    title: 'Teams and studios',
    description:
      'Use this path for studio, classroom, or team planning, especially when higher-dimensional training and release readiness need to be reviewed together.',
    steps: [
      'Review packaged proof, notices, pricing, and delivery status together instead of as separate disconnected checks.',
      'Keep planning and account coordination separate from the simulator itself.',
      'Carry higher-dimensional readiness and the current XR/controller boundary into team decisions explicitly.',
    ],
    routeFocus: [
      'Release notes and the public manual explain recent website, desktop, and controls changes.',
      'Download and notices pages carry the current distribution status plus legal follow-through.',
      'Resources summarize higher-dimensional training paths and team playbooks for wider review.',
    ],
    actions: [
      { label: 'Sign in for notices', to: buildLoginPath('/app/notices') },
      { label: 'Sign in for browser access', to: buildLoginPath('/app/browser-access') },
      { label: 'Open release notes', to: '/changelog' },
      { label: 'Open resources', to: '/resources' },
    ],
  },
}

export const supportTopicDirectory = Object.entries(supportTopicGuidance).map(([topicKey, topic]) => ({
  topicKey,
  ...topic,
}))

export const explorerFallbackPlan = planCatalog.find((plan) => plan.key === 'explorer') ?? planCatalog[0]
export const operatorFallbackPlan = planCatalog.find((plan) => plan.key === 'operator') ?? planCatalog[1]
export const studioFallbackPlan = planCatalog.find((plan) => plan.key === 'studio') ?? planCatalog[2]

export const releaseCommerceFallback = {
  operatorCheckoutUrl: isExternalHref(operatorFallbackPlan.ctaHref) ? operatorFallbackPlan.ctaHref : '',
  studioCheckoutUrl: isExternalHref(studioFallbackPlan.ctaHref) ? studioFallbackPlan.ctaHref : '',
  planPriceOperator: operatorFallbackPlan.price,
  planPriceStudio: studioFallbackPlan.price,
}

export const downloadablePublicManualHref = '/manual/hypertwist-operator-manual.md'

export function buildPublicReleaseManifestFallback(supportEmail = brandConfig.contact.email) {
  return {
    downloadTargets,
    publicDocsUrl,
    releaseNotesUrl,
    correspondingSourceUrl: mplSourceUrl,
    openSourceRepoUrl,
    supportEmail,
  }
}

export function Section({
  title,
  description,
  children,
}: {
  title: string
  description?: string
  children: ReactNode
}) {
  return (
    <section className="page-section">
      <div className="section-heading">
        <h2>{title}</h2>
        {description ? <p>{description}</p> : null}
      </div>
      {children}
    </section>
  )
}

type StepOnlyCard = {
  title: string
  steps?: readonly string[]
  bullets?: readonly string[]
}

type PrincipleCard = {
  title: string
  description: string
}

type BulletCard = {
  title: string
  description: string
  bullets: readonly string[]
}

type StepCard = {
  title: string
  description: string
  steps: readonly string[]
}

type FaqCard = {
  question: string
  answer: string
}

type SupportTopicCard = (typeof supportTopicDirectory)[number]

type PublicManualRouteAtlasCard = (typeof publicManualRouteAtlasCards)[number]

export function usePublicReleaseManifestView(queryScope: string) {
  const releaseManifestQuery = useQuery({
    queryKey: ['release-manifest', queryScope],
    queryFn: getReleaseManifest,
    retry: false,
  })

  const releaseManifest = useMemo(
    () => resolveReleaseManifestView(releaseManifestQuery.data?.manifest, buildPublicReleaseManifestFallback()),
    [releaseManifestQuery.data?.manifest],
  )

  const windowsValidationPlatform = useMemo(
    () => releaseManifest.platforms.find((platform) => platform.platform_key === 'windows' && platform.validation_summary) ?? null,
    [releaseManifest],
  )

  return {
    releaseManifestQuery,
    releaseManifest,
    windowsValidationPlatform,
  }
}

export function DeliverySurfaceResponsibilitiesGrid({ limit }: { limit?: number }) {
  const surfaces = typeof limit === 'number' ? deliverySurfaceCards.slice(0, limit) : deliverySurfaceCards

  return (
    <div className="card-grid">
      {surfaces.map((surface) => (
        <article key={surface.title} className="card">
          <h3>{surface.title}</h3>
          <p>{surface.description}</p>
          <ul className="list top-gap">
            {surface.bullets.map((bullet) => (
              <li key={bullet}>{bullet}</li>
            ))}
          </ul>
        </article>
      ))}
    </div>
  )
}

export function BrowserDesktopRealitySection({
  title = 'Why HyperTwist gives you both a website and a desktop app',
  description = 'The website gets you in, keeps your account and downloads organized, and handles plans, updates, and help. The desktop app is where the full simulator experience lives.',
}: {
  title?: string
  description?: string
}) {
  return (
    <Section title={title} description={description}>
      <div className="card-grid">
        {browserDesktopRealityCards.map((card) => (
          <article key={card.title} className="card">
            <p className="status-pill status-pill--info">{card.posture}</p>
            <h3>{card.title}</h3>
            <p>{card.description}</p>
            <ul className="list top-gap">
              {card.bullets.map((bullet) => (
                <li key={bullet}>{bullet}</li>
              ))}
            </ul>
            <div className="button-row top-gap">
              <HyperTwistButtonLink tone="ghost" to={card.action.to}>
                {card.action.label}
              </HyperTwistButtonLink>
            </div>
          </article>
        ))}
      </div>
    </Section>
  )
}

const surfaceChoiceGuideCards = [
  {
    title: 'Stay on the website',
    posture: 'Public website',
    description: 'Use this when you are still exploring HyperTwist, reading the manual, comparing plans, or checking release status.',
    bullets: [
      'Best for product discovery, documentation, pricing, support, and release updates.',
      'Keeps launch details visible without exposing protected downloads on anonymous pages.',
    ],
    action: {
      to: '/docs',
      label: 'Open public manual',
    },
  },
  {
    title: 'Open your account dashboard',
    posture: 'Signed-in dashboard',
    description: 'Use this when your identity, plan, downloads, billing status, or desktop pairing starts to matter.',
    bullets: [
      'Best for account state, protected downloads, desktop-link pairing, and release updates tied to your plan.',
      'Keeps you inside signed-in routes instead of bouncing you back through anonymous guidance.',
    ],
    action: {
      to: '/app',
      label: 'Open dashboard',
    },
  },
  {
    title: 'Launch the desktop app',
    posture: 'Desktop simulator',
    description: 'Use this when you want the actual training loop, replay review, higher-dimensional maps, or the full simulator experience.',
    bullets: [
      'Best for classic-cube execution, dedicated 120‑cell and 5D sessions, and the strongest training fidelity.',
      'This is the real simulator experience that the website intentionally does not pretend to replace.',
    ],
    action: {
      to: '/download',
      label: 'Open download center',
    },
  },
] as const

export function SurfaceChoiceGuideSection({
  title = 'Choose the right HyperTwist surface',
  description,
}: {
  title?: string
  description?: string
}) {
  return (
    <Section title={title} description={description}>
      <div className="card-grid">
        {surfaceChoiceGuideCards.map((card) => (
          <article key={card.title} className="card">
            <p className="status-pill status-pill--info">{card.posture}</p>
            <h3>{card.title}</h3>
            <p>{card.description}</p>
            <ul className="list top-gap">
              {card.bullets.map((bullet) => (
                <li key={bullet}>{bullet}</li>
              ))}
            </ul>
            <div className="button-row top-gap">
              <HyperTwistButtonLink tone="ghost" to={card.action.to}>
                {card.action.label}
              </HyperTwistButtonLink>
            </div>
          </article>
        ))}
      </div>
    </Section>
  )
}

export function OperatorDesktopQuickstartSection({
  title = 'First real desktop session',
  description = 'This is the shortest path from website discovery into the real simulator: create your account, pair your install, verify the first session, and know exactly what is ready today.',
}: {
  title?: string
  description?: string
}) {
  return (
    <Section title={title} description={description}>
      <div className="card-grid">
        {operatorDesktopQuickstartCards.map((card) => (
          <article key={card.title} className="card">
            <h3>{card.title}</h3>
            <p>{card.description}</p>
            <ul className="list top-gap">
              {card.bullets.map((bullet) => (
                <li key={bullet}>{bullet}</li>
              ))}
            </ul>
          </article>
        ))}
      </div>
      <div className="button-row top-gap">
        <HyperTwistButtonLink tone="ghost" to="/download">
          Open download center
        </HyperTwistButtonLink>
        <HyperTwistButtonLink tone="ghost" to="/app">
          Open dashboard
        </HyperTwistButtonLink>
        <HyperTwistButtonLink tone="ghost" to="/docs">
          Open public manual
        </HyperTwistButtonLink>
      </div>
    </Section>
  )
}

export function DownloadableOperatorManualSection({
  title = 'Offline desktop guide',
  description = 'HyperTwist ships a downloadable guide so onboarding, controls, advanced puzzle guidance, and release notes can travel with the app instead of living only on the website.',
}: {
  title?: string
  description?: string
}) {
  return (
    <Section title={title} description={description}>
      <article className="card">
        <p>
          The downloadable guide bundles the first-session path, the website-versus-desktop split,
          signed-in access, controls, higher-dimensional guidance, and the current
          XR/controller status into one offline reference.
        </p>
        <ul className="list top-gap">
          <li>Use it for desktop-side onboarding, launch review, and support when the website is not the best reading surface.</li>
          <li>It stays aligned with the public manual instead of inventing a separate product story.</li>
          <li>It keeps the current headset and controller status explicit instead of flattening it into vague VR claims.</li>
        </ul>
        <div className="button-row top-gap">
          <HyperTwistButtonAnchor href={downloadablePublicManualHref} download>
            Download offline desktop guide
          </HyperTwistButtonAnchor>
          <HyperTwistButtonLink tone="ghost" to="/docs">
            Open public manual
          </HyperTwistButtonLink>
          <HyperTwistButtonLink tone="ghost" to="/getting-started">
            Open getting started
          </HyperTwistButtonLink>
        </div>
      </article>
    </Section>
  )
}

export function PrincipleCardSection({
  title,
  description,
  cards,
}: {
  title: string
  description?: string
  cards: readonly PrincipleCard[]
}) {
  return (
    <Section title={title} description={description}>
      <div className="card-grid">
        {cards.map((card) => (
          <article key={card.title} className="card">
            <h3>{card.title}</h3>
            <p>{card.description}</p>
          </article>
        ))}
      </div>
    </Section>
  )
}

export function SimulatorManualSection({
  title = 'Simulator manual',
  description = 'These are the current usage tracks for the desktop app itself.',
}: {
  title?: string
  description?: string
}) {
  return <BulletCardSection title={title} description={description} cards={simulatorManualCards} />
}

export function HigherDimensionalRuntimeGuideSection({
  title = 'Higher-dimensional family guide',
  description = 'These are the higher-dimensional puzzle families already represented in HyperTwist and where each one actually lives today.',
}: {
  title?: string
  description?: string
}) {
  return (
    <BulletCardSection
      title={title}
      description={description}
      cards={higherDimensionalRuntimeGuideCards}
    />
  )
}

export function InputAndDevicePostureSection({
  title = 'Input and device state',
  description = 'Public documentation should be explicit about the controls, devices, and current VR status instead of blurring groundwork and finished claims together.',
}: {
  title?: string
  description?: string
}) {
  return (
    <BulletCardSection
      title={title}
      description={description}
      cards={inputAndDevicePostureCards}
    />
  )
}

export function ControlProfileRosterSection({
  title = 'Selectable control and settings roster',
  description = 'This answers the practical user question: which settings, profiles, selectors, and saved preferences are already real today?',
}: {
  title?: string
  description?: string
}) {
  return (
    <BulletCardSection
      title={title}
      description={description}
      cards={controlProfileRosterCards}
    />
  )
}

export function RuntimeControlGuideSection({
  title = 'Runtime control guide',
  description = 'This manual section explains how to use the current desktop app without pretending the unfinished XR/controller branch is already complete.',
}: {
  title?: string
  description?: string
}) {
  return (
    <BulletCardSection
      title={title}
      description={description}
      cards={runtimeControlGuideCards}
    />
  )
}

export function BulletCardSection({
  title,
  description,
  cards,
}: {
  title: string
  description?: string
  cards: readonly BulletCard[]
}) {
  return (
    <Section title={title} description={description}>
      <div className="card-grid">
        {cards.map((card) => (
          <article key={card.title} className="card">
            <h3>{card.title}</h3>
            <p>{card.description}</p>
            <ul className="list top-gap">
              {card.bullets.map((bullet) => (
                <li key={bullet}>{bullet}</li>
              ))}
            </ul>
          </article>
        ))}
      </div>
    </Section>
  )
}

export function StepCardSection({
  title,
  description,
  cards,
}: {
  title: string
  description?: string
  cards: readonly StepCard[]
}) {
  return (
    <Section title={title} description={description}>
      <div className="card-grid">
        {cards.map((card) => (
          <article key={card.title} className="card">
            <h3>{card.title}</h3>
            <p>{card.description}</p>
            <ul className="list top-gap">
              {card.steps.map((step) => (
                <li key={step}>{step}</li>
              ))}
            </ul>
          </article>
        ))}
      </div>
    </Section>
  )
}

export function StepOnlyCardSection({
  title,
  description,
  cards,
}: {
  title: string
  description?: string
  cards: readonly StepOnlyCard[]
}) {
  return (
    <Section title={title} description={description}>
      <div className="card-grid">
        {cards.map((card) => (
          <article key={card.title} className="card">
            <h3>{card.title}</h3>
            <ul className="list top-gap">
              {(card.steps ?? card.bullets ?? []).map((step) => (
                <li key={step}>{step}</li>
              ))}
            </ul>
          </article>
        ))}
      </div>
    </Section>
  )
}

export function FaqCardSection({
  title,
  description,
  cards,
}: {
  title: string
  description?: string
  cards: readonly FaqCard[]
}) {
  return (
    <Section title={title} description={description}>
      <div className="card-grid">
        {cards.map((card) => (
          <article key={card.question} className="card">
            <h3>{card.question}</h3>
            <p>{card.answer}</p>
          </article>
        ))}
      </div>
    </Section>
  )
}

export function BrowserDesktopDecisionFaqSection({
  title = 'Common browser-versus-desktop questions',
  description = 'These are the direct product-boundary answers most people want before deciding whether the website is enough on its own or whether they should move into the native runtime.',
}: {
  title?: string
  description?: string
}) {
  return (
    <FaqCardSection
      title={title}
      description={description}
      cards={browserDesktopDecisionFaqs}
    />
  )
}

export function SupportTopicDirectorySection({
  title,
  description,
  topics,
  selectedTopicKey,
}: {
  title: string
  description?: string
  topics: readonly SupportTopicCard[]
  selectedTopicKey?: string | null
}) {
  return (
    <Section title={title} description={description}>
      <div className="card-grid">
        {topics.map((topic) => {
          const isSelected = selectedTopicKey === topic.topicKey

          return (
            <article
              key={topic.topicKey}
              className={`card${isSelected ? ' card--selected' : ''}`}
            >
              {isSelected ? <p className="status-pill status-pill--info">Selected help topic</p> : null}
              <h3>{topic.title}</h3>
              <p>{topic.description}</p>
              <p className="eyebrow top-gap">Next steps</p>
              <ul className="list top-gap">
                {topic.steps.map((step) => (
                  <li key={step}>{step}</li>
                ))}
              </ul>
              <p className="eyebrow top-gap">Manual and route focus</p>
              <ul className="list top-gap">
                {topic.routeFocus.map((item) => (
                  <li key={item}>{item}</li>
                ))}
              </ul>
              <div className="button-row top-gap">
                {topic.actions.map((action) => (
                  <HyperTwistButtonLink key={`${topic.topicKey}-${action.label}`} tone="ghost" to={action.to}>
                    {action.label}
                  </HyperTwistButtonLink>
                ))}
              </div>
            </article>
          )
        })}
      </div>
    </Section>
  )
}

export function PublicManualRouteAtlasSection({
  title = 'Public manual route atlas',
  description = 'Each public page has a different job inside HyperTwist. This atlas keeps the route set readable as a real manual instead of a flat landing site.',
  cards = publicManualRouteAtlasCards,
  limit,
}: {
  title?: string
  description?: string
  cards?: readonly PublicManualRouteAtlasCard[]
  limit?: number
}) {
  const visibleCards = typeof limit === 'number' ? cards.slice(0, limit) : cards

  return (
    <Section title={title} description={description}>
      <div className="card-grid">
        {visibleCards.map((card) => (
          <article key={card.route} className="card">
            <p className="status-pill status-pill--info">{card.route}</p>
            <h3>{card.title}</h3>
            <p>{card.description}</p>
            <ul className="list top-gap">
              {card.bullets.map((bullet) => (
                <li key={bullet}>{bullet}</li>
              ))}
            </ul>
            <div className="button-row top-gap">
              <HyperTwistButtonLink tone="ghost" to={card.route}>
                Open {card.title}
              </HyperTwistButtonLink>
            </div>
          </article>
        ))}
      </div>
    </Section>
  )
}

export function BrowserAuthMethodsSection({
  title = 'Browser account access methods',
  description = 'Keep the available sign-in options visible wherever people are being asked to create an account, buy access, pair the desktop app, or recover access.',
}: {
  title?: string
  description?: string
}) {
  return (
    <Section title={title} description={description}>
      <BrowserAuthMethodsGuide />
    </Section>
  )
}

export function PublicPackagedDesktopProofSection({
  platform,
  actions = [],
}: {
  platform: ReleaseManifestPlatformView | null
  actions?: ReadonlyArray<{ to: string; label: string }>
}) {
  if (!platform) {
    return null
  }

  return (
    <Section title="Current packaged desktop proof">
      <ReleaseValidationSummary platform={platform} />
      {actions.length > 0 ? (
        <div className="button-row top-gap">
          {actions.map((action) => (
            <HyperTwistButtonLink key={`${action.to}-${action.label}`} tone="ghost" to={action.to}>
              {action.label}
            </HyperTwistButtonLink>
          ))}
        </div>
      ) : null}
    </Section>
  )
}

type ReleaseAuthorityReference = {
  title: string
  description: string
  href: string | null
  configuredLabel: string
  missingLabel: string
  linkLabel: string
  download?: boolean
}

export function ReleaseAuthorityBundleSection({
  releaseManifest,
  title = 'Release references and source availability',
  description = 'Keep docs, release notes, source links, notices, and support in one place so buyers and teams can always see the full delivery story.',
}: {
  releaseManifest: ReturnType<typeof resolveReleaseManifestView>
  title?: string
  description?: string
}) {
  const references: readonly ReleaseAuthorityReference[] = [
    {
      title: 'Offline desktop guide',
      description:
        'A same-origin offline manual ships with the website so desktop-first onboarding, download help, and launch review do not depend on live browsing alone.',
      href: downloadablePublicManualHref,
      configuredLabel: 'Included',
      missingLabel: 'Add the offline desktop guide before wider launch',
      linkLabel: 'Download offline desktop guide (.md)',
      download: true,
    },
    {
      title: 'Public manual',
      description:
        'The public docs portal is the main manual for browser-versus-desktop boundaries, launch status, and simulator truth.',
      href: releaseManifest.public_docs_url,
      configuredLabel: 'Configured',
      missingLabel: 'Add public docs URL before wider launch',
      linkLabel: releaseManifest.public_docs_url || 'Add public docs URL before wider launch',
    },
    {
      title: 'Release notes feed',
      description:
        'Release notes keep public launch pages anchored to real browser, package, control-boundary, and distribution changes.',
      href: releaseManifest.release_notes_url,
      configuredLabel: 'Configured',
      missingLabel: 'Add release notes URL before wider launch',
      linkLabel: releaseManifest.release_notes_url || 'Add release notes URL before wider launch',
    },
    {
      title: 'Corresponding source',
      description:
        'Any MPL-covered shipped build needs a stable corresponding-source location for the exact distributed material.',
      href: releaseManifest.corresponding_source_url,
      configuredLabel: 'Configured',
      missingLabel: 'Add corresponding-source URL before wider launch',
      linkLabel:
        releaseManifest.corresponding_source_url || 'Add corresponding-source URL before wider launch',
    },
    {
      title: 'Open-source repo and notices reference',
      description:
        'The public repository and notices reference keeps release, legal, and redistribution details visible outside the simulator.',
      href: releaseManifest.open_source_repo_url,
      configuredLabel: 'Configured',
      missingLabel: 'Add public repo/notices URL before wider launch',
      linkLabel: releaseManifest.open_source_repo_url || 'Add public repo/notices URL before wider launch',
    },
    {
      title: 'Support contact',
      description:
        'Support contact belongs in the same bundle so account, download, notice, and launch questions never need improvised escalation paths.',
      href: releaseManifest.support_email ? `mailto:${releaseManifest.support_email}` : null,
      configuredLabel: 'Ready',
      missingLabel: 'Add support email before wider launch',
      linkLabel: releaseManifest.support_email || 'Add support email before wider launch',
    },
  ] as const

  return (
    <Section title={title} description={description}>
      <div className="card-grid">
        {references.map((reference) => {
          const configured = Boolean(reference.href)

          return (
            <article key={reference.title} className="card">
              <p className={`status-pill ${configured ? '' : 'status-pill--warn'}`}>
                {configured ? reference.configuredLabel : 'Pending'}
              </p>
              <h3>{reference.title}</h3>
              <p>{reference.description}</p>
              <p className="top-gap">
                {reference.href ? (
                  reference.download ? (
                    <a href={reference.href} download>
                      {reference.linkLabel}
                    </a>
                  ) : (
                    <a href={reference.href} target="_blank" rel="noreferrer">
                      {reference.linkLabel}
                    </a>
                  )
                ) : (
                  reference.missingLabel
                )}
              </p>
            </article>
          )
        })}
      </div>
    </Section>
  )
}

type PublicReleaseDecisionAction = {
  label: string
  to: string
}

type PublicReleaseDecisionCard = {
  badge: string
  title: string
  summary: string
  bullets: readonly string[]
  actions: readonly PublicReleaseDecisionAction[]
}

function describePublicReleaseTarget(platform: ReleaseManifestPlatformView) {
  const parts = [platform.platform]

  if (platform.version) {
    parts.push(`v${platform.version}`)
  }

  if (platform.channel) {
    parts.push(`(${platform.channel})`)
  }

  return parts.join(' ')
}

function buildPublicReleaseDecisionCards(releaseManifest: ReleaseManifestView): readonly PublicReleaseDecisionCard[] {
  const configuredTargets = releaseManifest.platforms.filter((platform) => platform.configured)
  const windowsTarget = releaseManifest.platforms.find((platform) => platform.platform_key === 'windows') ?? null
  const primaryTarget = configuredTargets.find((platform) => platform.platform_key === 'windows')
    ?? configuredTargets[0]
    ?? windowsTarget
  const releaseCommerce = resolveReleaseCommerceView(releaseManifest, releaseCommerceFallback)
  const supportEmail = releaseManifest.support_email || brandConfig.contact.email
  const configuredReferenceCount = [
    releaseManifest.public_docs_url,
    releaseManifest.release_notes_url,
    releaseManifest.corresponding_source_url,
    releaseManifest.open_source_repo_url,
    releaseManifest.support_email,
  ].filter(Boolean).length
  const checkoutConfigured = Boolean(
    releaseCommerce.operator_checkout_url || releaseCommerce.studio_checkout_url,
  )

  const releaseTargetCard: PublicReleaseDecisionCard = primaryTarget?.configured
    ? {
        badge: 'Desktop release target published',
        title: 'Need the desktop download?',
        summary:
          'The public site can confirm the current desktop release target, while the actual package still arrives through your signed-in download area.',
        bullets: [
          `Current public target: ${describePublicReleaseTarget(primaryTarget)}`,
          `Configured release targets: ${configuredTargets.length}/${releaseManifest.platforms.length}`,
          primaryTarget.validation_summary
            ? 'Public package proof is already attached to this release.'
            : 'This release is published, but public package proof is not attached yet.',
        ],
        actions: [
          { label: 'Sign in for desktop downloads', to: buildLoginPath(buildProtectedDownloadPath('windows')) },
          { label: 'Create account for desktop access', to: buildRegisterPath(buildProtectedDownloadPath('windows')) },
          { label: 'Open download center', to: '/download' },
        ],
      }
    : {
        badge: 'Package publication pending',
        title: 'Need the desktop download?',
        summary:
          'The public site can still explain the release path, but direct package delivery stays inside the signed-in flow until a published desktop target is active.',
        bullets: [
          `Configured release targets: ${configuredTargets.length}/${releaseManifest.platforms.length}`,
          `Primary default target: ${primaryTarget ? primaryTarget.platform : 'Windows desktop release pending publication'}`,
          `Support contact: ${supportEmail}`,
        ],
        actions: [
          { label: 'Sign in for desktop downloads', to: buildLoginPath(buildProtectedDownloadPath('windows')) },
          { label: 'Open download center', to: '/download' },
          { label: 'Open launch-readiness support', to: buildSupportPath('launch-readiness') },
        ],
      }

  const provisioningCard: PublicReleaseDecisionCard = checkoutConfigured
    ? {
        badge: 'Checkout or provisioning route ready',
        title: 'Need pricing, billing, or subscription help?',
        summary:
          'The website is where pricing starts. After that, the signed-in dashboard resolves plan access, downloads, and account follow-through.',
        bullets: [
          `Desktop plan checkout: ${releaseCommerce.operator_checkout_url ? 'configured' : 'manual help required'}`,
          `Studio plan checkout: ${releaseCommerce.studio_checkout_url ? 'configured' : 'manual help required'}`,
          'Keep pricing on the public site, then move into the signed-in dashboard for account-aware release work.',
        ],
        actions: [
          { label: 'Open pricing', to: '/pricing' },
          { label: 'Sign in for dashboard', to: buildLoginPath('/app') },
        ],
      }
    : {
        badge: 'Manual provisioning route',
        title: 'Need pricing, billing, or subscription help?',
        summary:
          'Pricing can still explain the delivery model, while account or support follow-through remains the right path until live checkout targets are active.',
        bullets: [
          `Desktop plan checkout: ${releaseCommerce.operator_checkout_url ? 'configured' : 'manual help required'}`,
          `Studio plan checkout: ${releaseCommerce.studio_checkout_url ? 'configured' : 'manual help required'}`,
          `Support contact: ${supportEmail}`,
        ],
        actions: [
          { label: 'Open pricing', to: '/pricing' },
          { label: 'Open access support', to: buildSupportPath('operator-access') },
        ],
      }

  const browserContinuityCard: PublicReleaseDecisionCard = {
    badge: 'Signed-in website follow-through',
    title: 'Need account access, pairing, or dashboard help?',
    summary:
      'The website handles your account, downloads, billing, legal details, and desktop pairing while the desktop app stays focused on training.',
    bullets: [
      'Use the signed-in dashboard for account status, release updates, and pairing follow-through.',
      'Use the signed-in browser-access route when you need account continuity rather than simulator execution.',
      'Move into the desktop app for the actual training loop, coaching, and higher-dimensional interaction.',
    ],
    actions: [
      { label: 'Sign in for dashboard', to: buildLoginPath('/app') },
      { label: 'Sign in for browser access', to: buildLoginPath('/app/browser-access') },
    ],
  }

  const noticesCard: PublicReleaseDecisionCard = {
    badge: configuredReferenceCount === 5 ? 'Release references configured' : 'Some release references are still pending',
    title: 'Need legal details, release notes, or source links?',
    summary:
      'Public notices and release references stay on the website first, while the signed-in notices area helps when those details need to stay attached to your account.',
    bullets: [
      `Configured public release references: ${configuredReferenceCount}/5`,
      'Keep notices, release notes, and corresponding-source status visible anywhere downloadable distribution is discussed.',
      `Support contact: ${supportEmail}`,
    ],
    actions: [
      { label: 'Review public notices', to: '/open-source-notices' },
      { label: 'Review release notes', to: '/changelog' },
      { label: 'Sign in for notices', to: buildLoginPath('/app/notices') },
    ],
  }

  return [releaseTargetCard, provisioningCard, browserContinuityCard, noticesCard]
}

function SurfaceActionLink({
  to,
  label,
  className,
}: {
  to: string
  label: string
  className?: string
}) {
  if (isExternalHref(to)) {
    return (
      <HyperTwistButtonAnchor className={className} tone="ghost" href={to} target="_blank" rel="noreferrer">
        {label}
      </HyperTwistButtonAnchor>
    )
  }

  return (
    <HyperTwistButtonLink className={className} tone="ghost" to={to}>
      {label}
    </HyperTwistButtonLink>
  )
}

export function PublicReleaseDecisionGuideSection({
  releaseManifest,
  title = 'Choose the next best step',
  description = 'These cards keep the public pages practical: they show whether the next step is pricing, account access, the desktop download, or the release details around it.',
}: {
  releaseManifest: ReleaseManifestView
  title?: string
  description?: string
}) {
  const cards = buildPublicReleaseDecisionCards(releaseManifest)

  return (
    <Section title={title} description={description}>
      <div className="card-grid">
        {cards.map((card) => (
          <article key={card.title} className="card">
            <p className="status-pill status-pill--info">{card.badge}</p>
            <h3>{card.title}</h3>
            <p>{card.summary}</p>
            <ul className="list top-gap">
              {card.bullets.map((bullet) => (
                <li key={bullet}>{bullet}</li>
              ))}
            </ul>
            <div className="button-row top-gap">
              {card.actions.map((action) => (
                <SurfaceActionLink key={`${card.title}-${action.label}`} to={action.to} label={action.label} />
              ))}
            </div>
          </article>
        ))}
      </div>
    </Section>
  )
}

export function PlanActionLink({ href, label }: { href: string; label: string }) {
  if (isExternalHref(href)) {
    return (
      <HyperTwistButtonAnchor full href={href} target="_blank" rel="noreferrer">
        {label}
      </HyperTwistButtonAnchor>
    )
  }

  return (
    <HyperTwistButtonLink full to={href}>
      {label}
    </HyperTwistButtonLink>
  )
}
