import { useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Link } from 'react-router-dom'
import { getAuthHealth } from '../../auth/auth-api'
import { buildLiveLaunchBlockerDetails, resolvePublicLaunchStatusSummary } from '../../public-launch'
import { launchReadiness } from '../../site-config'
import { buildProtectedDownloadPath } from '../../site-routes'
import { HyperTwistButtonLink } from './HyperTwistButton'

function buildMarketingLaunchStatusSummary(
  ready: boolean,
  liveBlockerDetails: string[],
  missingLabels: string[],
) {
  if (ready) {
    return 'Account access, release references, checkout, notices, and desktop delivery are aligned for the current public lane.'
  }

  const unresolvedCount = Math.max(liveBlockerDetails.length, missingLabels.length)
  const accessNote = unresolvedCount > 0
    ? 'Some release and commerce steps are still handled through signed-in dashboard or support follow-up.'
    : 'Release access is intentionally routed through account-aware dashboard surfaces.'

  return `HyperTwist is in account-gated early access. ${accessNote}`
}

function usePublicLaunchStatus() {
  const authHealthQuery = useQuery({
    queryKey: ['auth-health', 'public-launch-status'],
    queryFn: getAuthHealth,
    retry: false,
  })
  const launchStatus = useMemo(() => (
    resolvePublicLaunchStatusSummary(authHealthQuery.data, undefined, launchReadiness)
  ), [authHealthQuery.data])

  const checklist = launchStatus.checklist
  const ready = launchStatus.ready
  const missingLabels = useMemo(() => {
    const labels = launchStatus.missingLabels.map((label) => label.toLowerCase())

    if (authHealthQuery.isLoading || authHealthQuery.isError) {
      labels.push('live auth runtime verification')
      labels.push('release-manifest authority confirmation')
    }

    return labels
  }, [authHealthQuery.isError, authHealthQuery.isLoading, launchStatus.missingLabels])
  const liveBlockerDetails = useMemo(() => (
    buildLiveLaunchBlockerDetails(authHealthQuery.data, launchStatus)
  ), [authHealthQuery.data, launchStatus])

  return {
    authHealthQuery,
    checklist,
    liveBlockerDetails,
    missingLabels,
    ready,
    launchStatus,
  }
}

export function MarketingLaunchStatusBanner() {
  const { liveBlockerDetails, missingLabels, ready } = usePublicLaunchStatus()

  return (
    <article className="callout site-status-banner">
      <div className="status-row">
        <p className={`status-pill${ready ? ' status-pill--success' : ''}`}>
          {ready ? 'Public launch ready' : 'Early access'}
        </p>
        <strong>Public site status</strong>
      </div>
      <p>{buildMarketingLaunchStatusSummary(ready, liveBlockerDetails, missingLabels)}</p>
      <div className="status-row">
        <Link className="inline-link" to="/launch-status">
          View access status
        </Link>
        <Link className="inline-link" to={buildProtectedDownloadPath('windows')}>
          Open signed-in downloads
        </Link>
      </div>
    </article>
  )
}

export function PublicLaunchStatus({
  title = 'Current public launch status',
}: {
  title?: string
}) {
  const { authHealthQuery, launchStatus, liveBlockerDetails, ready } = usePublicLaunchStatus()

  return (
    <article className="callout">
      <p className={`status-pill${ready ? ' status-pill--success' : ''}`}>
        {ready ? 'Public launch ready' : 'Account-gated early access'}
      </p>
      <h3>{title}</h3>
      <p>
        {ready
          ? 'HyperTwist can route visitors from public product pages through account access, checkout, protected downloads, and notices.'
          : 'HyperTwist is available as an account-gated desktop-first product lane. Public pages explain the software, while signed-in dashboard routes handle download access, subscription state, and desktop pairing.'}
      </p>
      <ul className="list">
        <li>Desktop app access: routed through account creation or sign-in before package delivery.</li>
        <li>Browser version: available as the public/protected account, docs, release, pricing, and pairing shell, not as simulator parity.</li>
        <li>Subscription access: managed on the website/dashboard and handed to the downloadable through desktop-link pairing.</li>
        <li>Download authority: protected dashboard first; anonymous public pages explain targets without exposing raw package delivery.</li>
        <li>Operator checkout: {launchStatus.targets.operatorCheckoutTarget ? 'available from the configured Paddle route' : 'available through account/support follow-up until the public checkout route is switched on'}.</li>
        <li>Studio checkout: {launchStatus.targets.studioCheckoutTarget ? 'available from the configured Paddle route' : 'available through account/support follow-up until the public checkout route is switched on'}.</li>
      </ul>
      {ready && liveBlockerDetails.length > 0 ? (
        <div className="callout top-gap">
          <p>Current runtime notes</p>
          <ul className="list">
            {liveBlockerDetails.map((item) => (
              <li key={item}>{item}</li>
            ))}
          </ul>
        </div>
      ) : null}
      {authHealthQuery.isLoading ? (
        <p>Checking current account and release access status.</p>
      ) : null}
      {authHealthQuery.isError ? (
        <p className="form-error">
          Live access-status lookup is unavailable right now. Public product guidance remains visible; use sign-in or support for account-aware follow-through.
        </p>
      ) : null}
      {!ready ? (
        <div className="button-row top-gap">
          <HyperTwistButtonLink tone="ghost" to={buildProtectedDownloadPath('windows')}>
            Open signed-in downloads
          </HyperTwistButtonLink>
          <HyperTwistButtonLink tone="ghost" to="/app/notices">
            Open protected notices
          </HyperTwistButtonLink>
        </div>
      ) : null}
    </article>
  )
}
