import "../index.css"
import { Meta, Title } from "@solidjs/meta"
import { ProviderIcon } from "@opencode-ai/ui/provider-icon"
import { geoEquirectangular, geoPath } from "d3-geo"
import { scaleSqrt } from "d3-scale"
import countryCodesSource from "i18n-iso-countries/codes.json?raw"
import { feature, mesh } from "topojson-client"
import countriesTopologySource from "world-atlas/countries-50m.json?raw"
import {
  getStatsModelData,
  type CountryEntry,
  type ModelPeerEntry,
  type ModelUsagePoint,
  type StatsModelData,
  type UsageRange,
} from "@opencode-ai/stats-core/domain/home"
import { createAsync, query, useParams } from "@solidjs/router"
import { createMemo, createSignal, For, onMount, Show, type JSX } from "solid-js"
import { getRequestEvent } from "solid-js/web"
import type { FeatureCollection, GeometryObject, GeoJsonProperties } from "geojson"
import type { GeometryCollection, Topology } from "topojson-specification"
import { LocaleLinks } from "../../component/locale-links"
import { useI18n } from "../../context/i18n"
import { useLanguage } from "../../context/language"
import { localizedUrl } from "../../lib/language"
import {
  findModelCatalogEntry,
  formatCatalogLabName,
  getModelCatalog,
  type ModelCatalog,
  type ModelCatalogCost,
  type ModelCatalogEntry,
} from "../model-catalog"
import { SectionHeading } from "../section-heading"
import { runStatsEffect } from "../../stats-runtime"
import { setStatsPageCacheHeaders } from "../stats-cache"
import {
  applyThemePreference,
  Footer,
  getGitHubStars,
  Header,
  isThemePreference,
  themeStorageKey,
  type HeaderLink,
  type ThemePreference,
} from "../stats-shell"

const statsUnfurlPath = "banner.png"
const geoMapWidth = 960
const geoMapHeight = 430
const shortMonths = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"] as const

type IsoCountryCode = readonly [string, string, string]
type WorldCountryProperties = GeoJsonProperties & { name?: string }
type WorldTopology = Topology<{ countries: GeometryCollection<WorldCountryProperties> }>

const countryNumericIds = new Map(
  (JSON.parse(countryCodesSource) as IsoCountryCode[]).map((country) => [country[0], country[2]] as const),
)
const worldTopology = JSON.parse(countriesTopologySource) as WorldTopology
const worldCountryGeometries: GeometryCollection<WorldCountryProperties> = {
  ...worldTopology.objects.countries,
  geometries: worldTopology.objects.countries.geometries.filter((country) => String(country.id ?? "") !== "010"),
}
const worldCountries = feature<WorldCountryProperties>(worldTopology, worldCountryGeometries) as FeatureCollection<
  GeometryObject,
  WorldCountryProperties
>
const worldProjection = geoEquirectangular().fitExtent(
  [
    [10, 12],
    [geoMapWidth - 10, geoMapHeight - 12],
  ],
  worldCountries,
)
const worldPath = geoPath(worldProjection)
const worldCountryPaths = worldCountries.features.map((country) => ({
  id: String(country.id ?? "").padStart(3, "0"),
  path: worldPath(country) ?? "",
  marker: geoCountryMarker(country),
}))
const worldBorderPath = worldPath(mesh(worldTopology, worldCountryGeometries, (a, b) => a !== b)) ?? ""

const getModelData = query(async (lab: string, model: string) => {
  "use server"
  return runStatsEffect(getStatsModelData(model, lab))
}, "getStatsModelData")

export default function StatsModel() {
  const i18n = useI18n()
  const language = useLanguage()
  const event = getRequestEvent()
  setStatsPageCacheHeaders(event?.response.headers)
  const params = useParams()
  const labParam = createMemo(() => params.lab ?? "")
  const modelParam = createMemo(() => params.model ?? "")
  const catalog = createAsync(() => getModelCatalog())
  const catalogEntry = createMemo(() => {
    const data = catalog()
    if (!data) return undefined
    return findModelCatalogEntry(data, modelParam(), labParam()) ?? null
  })
  const stats = createAsync(() => {
    const entry = catalogEntry()
    if (catalog() === undefined || entry === undefined) return Promise.resolve(undefined)
    if (!entry && (!labParam() || !modelParam())) return Promise.resolve(null)
    return getModelData(labParam(), entry?.slug ?? modelParam())
  })
  const githubStars = createAsync(() => getGitHubStars())
  const [themePreference, setThemePreference] = createSignal<ThemePreference>("system")
  const modelName = createMemo(() => catalogEntry()?.name ?? stats()?.model ?? modelParam() ?? i18n.t("model.fallback"))
  const labName = createMemo(() => formatCatalogLabName(catalogEntry()?.lab ?? stats()?.provider ?? labParam()))
  const modelTitle = createMemo(() => i18n.t("model.title", { model: modelName() }))
  const modelDescription = createMemo(() => i18n.t("model.description", { model: modelName() }))
  const modelPath = createMemo(
    () =>
      `/data/${catalogEntry()?.id ?? [labParam(), stats()?.slug ?? modelParam()].filter((part) => part.length > 0).join("/")}`,
  )
  const modelUrl = createMemo(() => localizedUrl(language.locale(), modelPath()))
  const statsUnfurlUrl = new URL(statsUnfurlPath, localizedUrl("en", "/data/")).toString()
  const modelHeaderLinks = createMemo<readonly HeaderLink[]>(() => [
    { href: "#overview", label: i18n.t("nav.overview") },
    { href: "#momentum", label: i18n.t("model.momentum") },
    { href: "#efficiency", label: i18n.t("nav.efficiency") },
    { href: "#geo-breakdown", label: i18n.t("nav.geoBreakdown") },
    { href: "#peers", label: i18n.t("nav.peers") },
  ])
  const modelFooterLinks = createMemo<readonly HeaderLink[]>(() => [
    { href: import.meta.env.BASE_URL, label: i18n.t("nav.dataHome") },
    { href: `${import.meta.env.BASE_URL}#top-models`, label: i18n.t("nav.topModels") },
    { href: `${import.meta.env.BASE_URL}#session-cost`, label: i18n.t("nav.sessionCost") },
    { href: `${import.meta.env.BASE_URL}#token-cost`, label: i18n.t("nav.tokenCost") },
    { href: `${import.meta.env.BASE_URL}#cache-ratio`, label: i18n.t("nav.cacheRatio") },
    { href: `${import.meta.env.BASE_URL}#market-share`, label: i18n.t("nav.marketShare") },
    { href: `${import.meta.env.BASE_URL}#geo-breakdown`, label: i18n.t("nav.geoBreakdown") },
  ])
  const updateThemePreference = (preference: ThemePreference) => {
    applyThemePreference(preference)
    setThemePreference(preference)
    if (typeof window === "undefined") return
    window.localStorage.setItem(themeStorageKey, preference)
  }

  onMount(() => {
    if (typeof window === "undefined") return
    const preference = window.localStorage.getItem(themeStorageKey)
    const nextPreference = isThemePreference(preference) ? preference : "system"
    applyThemePreference(nextPreference)
    setThemePreference(nextPreference)
  })

  return (
    <main data-page="stats" data-theme={themePreference()}>
      <Title>{modelTitle()}</Title>
      <Meta name="description" content={modelDescription()} />
      <LocaleLinks path={modelPath()} />
      <Meta property="og:type" content="website" />
      <Meta property="og:site_name" content="OpenCode" />
      <Meta property="og:title" content={modelTitle()} />
      <Meta property="og:description" content={modelDescription()} />
      <Meta property="og:url" content={modelUrl()} />
      <Meta property="og:image" content={statsUnfurlUrl} />
      <Meta property="og:image:type" content="image/png" />
      <Meta property="og:image:width" content="1200" />
      <Meta property="og:image:height" content="630" />
      <Meta property="og:image:alt" content={i18n.t("app.unfurlAlt")} />
      <Meta name="twitter:card" content="summary_large_image" />
      <Meta name="twitter:title" content={modelTitle()} />
      <Meta name="twitter:description" content={modelDescription()} />
      <Meta name="twitter:image" content={statsUnfurlUrl} />
      <Meta name="twitter:image:alt" content={i18n.t("app.unfurlAlt")} />
      <Header githubStars={githubStars() ?? "150K"} links={modelHeaderLinks()} brandHref={import.meta.env.BASE_URL} />
      <div data-component="container">
        <div data-component="content">
          <Show when={catalogEntry() || stats() !== undefined} fallback={<ModelLoading />}>
            <Show when={catalogEntry() || stats()} fallback={<ModelNotFound lab={labParam()} model={modelParam()} />}>
              <>
                <ModelHero
                  data={stats() ?? null}
                  catalog={catalogEntry() ?? null}
                  catalogData={catalog() ?? null}
                  labName={labName()}
                />
                <ModelOverview catalog={catalogEntry() ?? null} />
                <ModelMomentumSection data={stats() ?? null} />
                <ModelEfficiencySection data={stats() ?? null} catalog={catalogEntry() ?? null} />
                <ModelGeoBreakdownSection data={stats()?.country ?? emptyCountryRecord()} />
                <ModelPeersSection data={stats() ?? null} />
              </>
            </Show>
          </Show>
        </div>
        <Footer
          themePreference={themePreference()}
          onThemePreferenceChange={updateThemePreference}
          links={modelFooterLinks()}
        />
      </div>
    </main>
  )
}

function ModelLoading() {
  const i18n = useI18n()
  const language = useLanguage()
  return (
    <>
      <section id="overview" data-section="model-hero">
        <div data-slot="model-hero-grid">
          <div data-slot="model-hero-copy">
            <a data-slot="model-back-link" href={language.route(import.meta.env.BASE_URL)}>
              {i18n.t("footer.modelData")}
            </a>
            <h1>
              <a data-slot="heading-link" href="#overview">
                {i18n.t("model.loadingTitle")}
              </a>
            </h1>
            <p>{i18n.t("model.loadingDescription")}</p>
          </div>
        </div>
      </section>
      <section data-section="model-panel">
        <ModelEmptyState title={i18n.t("model.loadingTitle")} description={i18n.t("model.loadingProfile")} />
      </section>
    </>
  )
}

function ModelNotFound(props: { lab: string; model: string }) {
  const i18n = useI18n()
  const language = useLanguage()
  return (
    <>
      <section id="overview" data-section="model-hero">
        <div data-slot="model-hero-grid">
          <div data-slot="model-hero-copy">
            <a data-slot="model-back-link" href={language.route(import.meta.env.BASE_URL)}>
              {i18n.t("footer.modelData")}
            </a>
            <h1>
              <a data-slot="heading-link" href="#overview">
                {props.model || i18n.t("model.fallback")}
              </a>
            </h1>
            <p>{i18n.t("model.noMatched", { id: props.lab ? `${props.lab}/${props.model}` : props.model })}</p>
          </div>
        </div>
      </section>
      <section data-section="model-panel">
        <ModelEmptyState title={i18n.t("model.noDataTitle")} description={i18n.t("model.noDataDescription")} />
      </section>
    </>
  )
}

function ModelHero(props: {
  data: StatsModelData | null
  catalog: ModelCatalogEntry | null
  catalogData: ModelCatalog | null
  labName: string
}) {
  const i18n = useI18n()
  const language = useLanguage()
  const labId = () => props.catalog?.lab ?? props.data?.provider ?? props.labName
  const modelName = () => props.catalog?.name ?? props.data?.model ?? i18n.t("model.fallback")
  const weights = () => props.catalog?.weights[0]
  const labs = () => props.catalogData?.labs ?? []
  const labModels = () =>
    props.catalogData?.labs.find((lab) => lab.id === providerSlug(labId()))?.models ??
    (props.catalog ? [props.catalog] : [])
  return (
    <section id="overview" data-section="model-hero">
      <nav data-component="model-hero-breadcrumb" aria-label="Data breadcrumb">
        <a data-slot="model-hero-crumb" href={language.route(import.meta.env.BASE_URL)}>
          Data
        </a>
        <span data-slot="model-hero-separator">/</span>
        <Show
          when={labs().length > 0}
          fallback={
            <span data-slot="model-hero-crumb" data-current="true">
              <span>{props.labName}</span>
              <ChevronDownIcon />
            </span>
          }
        >
          <details data-component="model-hero-menu">
            <summary data-slot="model-hero-crumb" data-current="true">
              <span>{props.labName}</span>
              <ChevronDownIcon />
            </summary>
            <div data-slot="model-hero-options">
              <For each={labs()}>
                {(lab) => (
                  <a
                    data-slot="model-hero-option"
                    data-current={lab.id === providerSlug(labId()) ? "true" : undefined}
                    href={language.route(`${import.meta.env.BASE_URL}${lab.id}`)}
                  >
                    {lab.name}
                  </a>
                )}
              </For>
            </div>
          </details>
        </Show>
        <span data-slot="model-hero-separator">/</span>
        <Show
          when={labModels().length > 0}
          fallback={
            <span data-slot="model-hero-crumb" data-current="true" aria-current="page">
              <span>{modelName()}</span>
              <ChevronDownIcon />
            </span>
          }
        >
          <details data-component="model-hero-menu">
            <summary data-slot="model-hero-crumb" data-current="true" aria-current="page">
              <span>{modelName()}</span>
              <ChevronDownIcon />
            </summary>
            <div data-slot="model-hero-options">
              <For each={labModels()}>
                {(model) => (
                  <a
                    data-slot="model-hero-option"
                    data-current={model.id === props.catalog?.id ? "true" : undefined}
                    href={language.route(`${import.meta.env.BASE_URL}${model.id}`)}
                  >
                    {model.name}
                  </a>
                )}
              </For>
            </div>
          </details>
        </Show>
      </nav>
      <div data-slot="model-hero-title-row">
        <span data-slot="model-hero-avatar">
          <ProviderIcon aria-hidden="true" id={getProviderIconId(labId())} />
        </span>
        <h1>{modelName()}</h1>
        <div data-slot="model-hero-actions">
          <Show when={props.catalog?.openWeights && weights()}>
            {(weight) => (
              <a data-slot="model-hero-action" href={weight().url} target="_blank" rel="noopener noreferrer">
                <ModelHeroActionIcon kind="weights" />
                <span>Model weights</span>
              </a>
            )}
          </Show>
        </div>
      </div>
      <div data-slot="model-hero-pattern" aria-hidden="true" />
      <Show
        when={props.data}
        fallback={
          <p data-slot="model-hero-state">
            <span>Listed</span>
            <span>across the shared model catalog.</span>
          </p>
        }
      >
        {(data) => (
          <p data-slot="model-hero-rankline">
            <span>Ranked</span>
            <span data-slot="model-hero-rank-group">
              <span data-slot="model-hero-pill">{formatHeroRank(data().rank)}</span>
              <ModelHeroSparkline data={data()} />
            </span>
            <span>across last week's</span>
            <span data-slot="model-hero-pill">OpenCode Go</span>
            <span>usage with</span>
            <span data-slot="model-hero-pill">{formatPercent(data().tokenShare)}</span>
            <span>of observed</span>
            <span data-slot="model-hero-pill">2M</span>
            <span>volume.</span>
          </p>
        )}
      </Show>
    </section>
  )
}

function ModelHeroActionIcon(props: { kind: "weights" | "compare" }) {
  if (props.kind === "weights")
    return (
      <svg data-slot="model-hero-action-icon" viewBox="0 0 16 16" aria-hidden="true" fill="none">
        <path d="M5.5 4.5H4.5V11.5H11.5V10.5" stroke="currentColor" stroke-linecap="square" />
        <path d="M8.5 4.5H11.5V7.5" stroke="currentColor" stroke-linecap="square" />
        <path d="M11.25 4.75L7.25 8.75" stroke="currentColor" stroke-linecap="square" />
      </svg>
    )
  return (
    <svg data-slot="model-hero-action-icon" viewBox="0 0 16 16" aria-hidden="true" fill="none">
      <rect x="3.5" y="3.5" width="3" height="3" stroke="currentColor" />
      <rect x="9.5" y="3.5" width="3" height="3" stroke="currentColor" />
      <rect x="3.5" y="9.5" width="3" height="3" stroke="currentColor" />
      <rect x="9.5" y="9.5" width="3" height="3" stroke="currentColor" />
    </svg>
  )
}

function ModelHeroSparkline(props: { data: StatsModelData }) {
  const values = () => props.data.usage.slice(-14).map((point) => point.tokens)
  return (
    <span data-slot="model-hero-sparkline" aria-hidden="true">
      <svg viewBox="0 0 36 24" fill="none">
        <path d={sparklineAreaPath(values())} fill="currentColor" opacity="0.14" />
        <path d={sparklineLinePath(values())} stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" />
      </svg>
    </span>
  )
}

function ChevronDownIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" fill="none">
      <path d="M4.75 6.25L8 9.5L11.25 6.25" stroke="currentColor" stroke-width="1.5" />
    </svg>
  )
}

function ModelOverview(props: { catalog: ModelCatalogEntry | null }) {
  const i18n = useI18n()
  const language = useLanguage()
  const specs = createMemo(() => [
    {
      label: i18n.t("model.context"),
      value: formatCatalogLimit(props.catalog?.limit?.context, i18n.t("home.unknown")),
    },
    {
      label: i18n.t("model.output"),
      value: formatCatalogLimit(props.catalog?.limit?.output, i18n.t("home.unknown")),
    },
    {
      label: i18n.t("model.knowledge"),
      value: formatCatalogMonth(props.catalog?.knowledge, language.tag(language.locale()), i18n.t("home.unknown")),
    },
    {
      label: i18n.t("model.release"),
      value: formatCatalogMonth(props.catalog?.releaseDate, language.tag(language.locale()), i18n.t("home.unknown")),
    },
    {
      label: i18n.t("model.inputs"),
      value: formatCatalogModalities(
        props.catalog?.modalities.input ?? [],
        language.tag(language.locale()),
        i18n.t("home.unknown"),
      ),
    },
  ])
  return (
    <section id="model-overview" data-section="model-specs" aria-label={i18n.t("nav.overview")}>
      <For each={specs()}>
        {(spec) => (
          <div data-component="model-spec">
            <span>{spec.label}</span>
            <strong>{spec.value}</strong>
          </div>
        )}
      </For>
    </section>
  )
}

function ModelMomentumSection(props: { data: StatsModelData | null }) {
  const i18n = useI18n()
  const language = useLanguage()
  return (
    <section id="momentum" data-section="model-momentum">
      <h2 data-slot="model-momentum-title">
        <a href="#momentum">{i18n.t("model.momentum")}.</a>
        <span>{i18n.t("model.overviewDescription")}</span>
      </h2>
      <div data-slot="model-momentum-pattern" aria-hidden="true" />
      <Show
        when={props.data}
        fallback={
          <ModelEmptyState title={i18n.t("model.noSummaryTitle")} description={i18n.t("model.noSummaryDescription")} />
        }
      >
        {(data) => (
          <>
            <MomentumChart data={data()} locale={language.tag(language.locale())} />
            <div data-slot="model-momentum-metrics">
              <MomentumMetric label={i18n.t("model.uniqueUsers")} value={formatUsers(data().totals.uniqueUsers)} />
              <MomentumMetric
                label={capitalizeLabel(i18n.t("model.completedSessions"))}
                value={formatInteger(data().totals.sessions)}
              />
              <MomentumMetric label={i18n.t("model.tokenShare")} value={formatPercent(data().tokenShare)} />
              <MomentumMetric
                label="Rank"
                value={formatRankLabel(data().rank)}
                watermark={formatRankLabel(data().rank)}
              />
            </div>
          </>
        )}
      </Show>
    </section>
  )
}

function MomentumChart(props: { data: StatsModelData; locale: string }) {
  const chart = createMemo(() => momentumChart(props.data.usage, props.data.updatedAt))
  const changeState = createMemo(() => (props.data.tokenChange < 0 ? "negative" : "positive"))
  return (
    <div data-component="model-momentum-chart" role="img" aria-label="Recent model token momentum">
      <div data-slot="model-momentum-summary">
        <div data-slot="model-momentum-total">
          <strong>{formatTokens(props.data.totals.tokens)} tokens</strong>
          <span data-state={changeState()}>{formatChange(props.data.tokenChange)}</span>
        </div>
        <p>
          <span>{formatMomentumDate(chart().startDate, props.locale, props.data.updatedAt)}</span>
          <span aria-hidden="true">→</span>
          <span>{formatMomentumDate(chart().endDate, props.locale, props.data.updatedAt)}</span>
        </p>
      </div>
      <div data-slot="model-momentum-plot">
        <svg viewBox="0 0 1200 370" preserveAspectRatio="none" aria-hidden="true">
          <path data-slot="model-momentum-line-muted" d={chart().previousPath} />
          <path data-slot="model-momentum-line-active" d={chart().currentPath} />
          <For each={chart().markers}>
            {(marker) => (
              <rect
                data-slot="model-momentum-marker"
                data-active={marker.active ? "true" : undefined}
                x={marker.x - 3}
                y={marker.y - 3}
                width="6"
                height="6"
              />
            )}
          </For>
        </svg>
        <span data-slot="model-momentum-end" data-state={changeState()} style={chart().endStyle}>
          <i />
          {formatChange(props.data.tokenChange)}
        </span>
      </div>
      <div data-slot="model-momentum-months" aria-hidden="true">
        <For each={momentumMonthLabels(chart().startDate, props.locale, props.data.updatedAt)}>
          {(month) => <span style={{ left: `${month.x}%` }}>{month.label}</span>}
        </For>
      </div>
    </div>
  )
}

function MomentumMetric(props: { label: string; value: string; watermark?: string }) {
  return (
    <div data-component="model-momentum-metric">
      <Show when={props.watermark}>{(watermark) => <em aria-hidden="true">{watermark()}</em>}</Show>
      <span>{props.label}</span>
      <strong>{props.value}</strong>
    </div>
  )
}

function ModelEfficiencySection(props: { data: StatsModelData | null; catalog: ModelCatalogEntry | null }) {
  const i18n = useI18n()
  return (
    <section id="efficiency" data-section="model-panel">
      <SectionTitle
        href="#efficiency"
        title={i18n.t("nav.efficiency")}
        description={i18n.t("model.efficiencyDescription")}
      />
      <Show
        when={props.data}
        fallback={
          <ModelEmptyState
            title={i18n.t("model.noEfficiencyTitle")}
            description={i18n.t("model.noEfficiencyDescription")}
          />
        }
      >
        {(data) => (
          <div data-component="model-metric-grid" data-variant="dense">
            <MetricCard
              label={i18n.t("model.cost")}
              value={formatMoney(data().totals.cost)}
              detail={i18n.t("model.totalSpend")}
            />
            <MetricCard
              label={i18n.t("model.costPerMillion")}
              value={
                props.catalog?.cost ? formatCatalogPrice(props.catalog.cost) : formatMoney(data().totals.costPerMillion)
              }
              detail={props.catalog?.cost ? i18n.t("model.inputOutput") : i18n.t("model.observedTokens")}
            />
            <MetricCard
              label={i18n.t("model.costSession")}
              value={formatSessionCost(data().totals.costPerSession)}
              detail={i18n.t("model.average")}
            />
            <MetricCard
              label={i18n.t("model.tokensSession")}
              value={formatTokens(data().totals.tokensPerSession)}
              detail={i18n.t("model.average")}
            />
            <MetricCard
              label={i18n.t("model.cacheRatio")}
              value={formatPercent(data().totals.cacheRatio)}
              detail={i18n.t("model.inputTokens")}
            />
          </div>
        )}
      </Show>
    </section>
  )
}

function ModelGeoBreakdownSection(props: { data: Record<UsageRange, CountryEntry[]> }) {
  const i18n = useI18n()
  const language = useLanguage()
  const [activeCountry, setActiveCountry] = createSignal<string>()
  const data = createMemo(() => props.data["2M"])
  const countryById = createMemo(
    () =>
      new Map(
        data().flatMap((country) => {
          const id = countryNumericId(country.country)
          return id ? [[id, country] as const] : []
        }),
      ),
  )
  const maxTokens = createMemo(() => Math.max(0, ...data().map((country) => country.tokens)) || 1)
  const topCountries = createMemo(() => data().slice(0, 15))
  const active = createMemo(() => data().find((country) => country.country === activeCountry()) ?? data()[0])

  return (
    <section
      id="geo-breakdown"
      data-section="geo-breakdown"
      onPointerLeave={(event) => {
        if (event.pointerType === "touch") return
        setActiveCountry(undefined)
      }}
    >
      <SectionTitle
        href="#geo-breakdown"
        title={i18n.t("nav.geoBreakdown")}
        description={i18n.t("model.geoDescription")}
      />
      <Show
        when={data().length > 0}
        fallback={<ModelEmptyState title={i18n.t("model.noGeoTitle")} description={i18n.t("model.noGeoDescription")} />}
      >
        <div data-component="geo-breakdown">
          <div data-slot="geo-map-panel">
            <GeoWorldMap
              countryById={countryById()}
              activeCountry={activeCountry()}
              maxTokens={maxTokens()}
              onActiveCountryChange={setActiveCountry}
            />
            <Show when={active()}>
              {(country) => (
                <div data-slot="geo-active-country">
                  <span>#{String(country().rank).padStart(2, "0")}</span>
                  <strong>{formatCountryName(country().country, language.tag(language.locale()), i18n)}</strong>
                  <p>
                    <b>{formatGeoTokens(country().tokens)}</b>
                    <em>{formatGeoShare(country().share)}</em>
                  </p>
                </div>
              )}
            </Show>
          </div>
          <GeoCountryList
            data={topCountries()}
            activeCountry={activeCountry()}
            maxTokens={maxTokens()}
            onActiveCountryChange={setActiveCountry}
          />
        </div>
      </Show>
    </section>
  )
}

function GeoWorldMap(props: {
  countryById: Map<string, CountryEntry>
  activeCountry: string | undefined
  maxTokens: number
  onActiveCountryChange: (country: string | undefined) => void
}) {
  const i18n = useI18n()
  const opacityScale = createMemo(() => scaleSqrt().domain([0, props.maxTokens]).range([0.26, 0.96]).clamp(true))
  const countryOpacity = (country: CountryEntry | undefined) => {
    if (!country) return 0
    const opacity = opacityScale()(country.tokens)
    if (!props.activeCountry || props.activeCountry === country.country) return opacity
    return Math.max(0.18, opacity * 0.36)
  }

  return (
    <svg
      data-component="geo-world-map"
      viewBox={`0 0 ${geoMapWidth} ${geoMapHeight}`}
      role="img"
      aria-label={i18n.t("model.worldMap")}
    >
      <title>{i18n.t("home.geoMapTitle")}</title>
      <g data-slot="geo-countries">
        <For each={worldCountryPaths}>
          {(country) => {
            const entry = () => props.countryById.get(country.id)
            return (
              <path
                d={country.path}
                data-country-id={country.id}
                data-has-data={entry() ? "true" : undefined}
                data-active={entry()?.country === props.activeCountry ? "true" : undefined}
                style={{ "--geo-country-opacity": String(countryOpacity(entry())) } as JSX.CSSProperties}
                aria-hidden="true"
                onPointerEnter={() => {
                  const item = entry()
                  if (!item) return
                  props.onActiveCountryChange(item.country)
                }}
                onClick={() => {
                  const item = entry()
                  if (!item) return
                  props.onActiveCountryChange(item.country)
                }}
              />
            )
          }}
        </For>
      </g>
      <g data-slot="geo-country-markers">
        <For each={worldCountryPaths}>
          {(country) => {
            const entry = () => props.countryById.get(country.id)
            return (
              <Show when={country.marker && entry() ? country.marker : undefined}>
                {(marker) => (
                  <circle
                    cx={marker().x}
                    cy={marker().y}
                    r={entry()?.country === props.activeCountry ? 3.4 : 2.4}
                    data-active={entry()?.country === props.activeCountry ? "true" : undefined}
                    style={{ "--geo-country-opacity": String(countryOpacity(entry())) } as JSX.CSSProperties}
                    aria-hidden="true"
                    onPointerEnter={() => {
                      const item = entry()
                      if (!item) return
                      props.onActiveCountryChange(item.country)
                    }}
                    onClick={() => {
                      const item = entry()
                      if (!item) return
                      props.onActiveCountryChange(item.country)
                    }}
                  />
                )}
              </Show>
            )
          }}
        </For>
      </g>
      <path data-slot="geo-borders" d={worldBorderPath} aria-hidden="true" />
    </svg>
  )
}

function GeoCountryList(props: {
  data: CountryEntry[]
  activeCountry: string | undefined
  maxTokens: number
  onActiveCountryChange: (country: string | undefined) => void
}) {
  const i18n = useI18n()
  const language = useLanguage()
  const opacityScale = createMemo(() => scaleSqrt().domain([0, props.maxTokens]).range([0.26, 0.96]).clamp(true))

  return (
    <ol data-component="geo-country-list">
      <For each={props.data}>
        {(country) => (
          <li>
            <button
              type="button"
              data-active={props.activeCountry === country.country ? "true" : undefined}
              style={{ "--geo-row-opacity": String(opacityScale()(country.tokens)) } as JSX.CSSProperties}
              aria-label={`${formatCountryName(country.country, language.tag(language.locale()), i18n)} ${formatGeoTokens(country.tokens)} ${formatGeoShare(country.share)}`}
              onClick={() => props.onActiveCountryChange(country.country)}
              onPointerEnter={() => props.onActiveCountryChange(country.country)}
              onFocus={() => props.onActiveCountryChange(country.country)}
            >
              <span>{String(country.rank).padStart(2, "0")}</span>
              <i />
              <strong>{formatCountryName(country.country, language.tag(language.locale()), i18n)}</strong>
              <em>{formatGeoTokens(country.tokens)}</em>
              <b>{formatGeoShare(country.share)}</b>
            </button>
          </li>
        )}
      </For>
    </ol>
  )
}

function ModelPeersSection(props: { data: StatsModelData | null }) {
  const i18n = useI18n()
  return (
    <section id="peers" data-section="model-panel">
      <SectionTitle href="#peers" title={i18n.t("nav.peers")} description={i18n.t("model.peersDescription")} />
      <Show
        when={props.data?.peers.length}
        fallback={
          <ModelEmptyState title={i18n.t("model.noPeersTitle")} description={i18n.t("model.noPeersDescription")} />
        }
      >
        <ol data-component="model-peer-list">
          <For each={props.data?.peers ?? []}>
            {(peer) => <PeerRow peer={peer} active={peer.model === props.data?.model} />}
          </For>
        </ol>
      </Show>
    </section>
  )
}

function MetricCard(props: { label: string; value: string; detail: string; state?: "positive" | "negative" }) {
  return (
    <article data-component="model-metric" data-state={props.state}>
      <span>{props.label}</span>
      <strong>{props.value}</strong>
      <p>{props.detail}</p>
    </article>
  )
}

function PeerRow(props: { peer: ModelPeerEntry; active: boolean }) {
  const language = useLanguage()
  return (
    <li>
      <a
        href={language.route(`${import.meta.env.BASE_URL}${providerSlug(props.peer.provider)}/${props.peer.slug}`)}
        data-active={props.active ? "true" : undefined}
      >
        <span>{String(props.peer.rank).padStart(2, "0")}</span>
        <ProviderIcon aria-hidden="true" id={getProviderIconId(props.peer.author)} />
        <strong>{props.peer.model}</strong>
        <em>{props.peer.author}</em>
        <b>{formatTokens(props.peer.tokens)}</b>
      </a>
    </li>
  )
}

function SectionTitle(props: { href: string; title: string; description: string }) {
  return <SectionHeading href={props.href} title={props.title} description={props.description} />
}

function ModelEmptyState(props: { title: string; description: string; compact?: boolean }) {
  return (
    <div data-component="empty-state" data-compact={props.compact ? "true" : undefined}>
      <strong>{props.title}</strong>
      <p>{props.description}</p>
    </div>
  )
}

function getProviderIconId(author: string) {
  if (author === "MiniMax") return "minimax"
  if (author === "Moonshot") return "moonshotai"
  if (author === "Zhipu") return "zhipuai"
  return author.toLowerCase().replace(/[^a-z0-9]+/g, "")
}

function emptyCountryRecord(): Record<UsageRange, CountryEntry[]> {
  return {
    "1D": [],
    "1W": [],
    "2W": [],
    "1M": [],
    "2M": [],
    "3M": [],
    YTD: [],
    ALL: [],
  }
}

function countryNumericId(country: string) {
  return countryNumericIds.get(country.toUpperCase())?.padStart(3, "0")
}

function geoCountryMarker(country: (typeof worldCountries.features)[number]) {
  const bounds = worldPath.bounds(country)
  const [x, y] = worldPath.centroid(country)
  if (!Number.isFinite(x) || !Number.isFinite(y)) return undefined
  if (bounds[1][0] - bounds[0][0] >= 3 && bounds[1][1] - bounds[0][1] >= 3) return undefined
  return { x, y }
}

function formatCountryName(country: string, locale: string, i18n: ReturnType<typeof useI18n>) {
  const code = country.toUpperCase()
  if (code === "ZZ") return i18n.t("home.unknown")
  if (!countryNumericId(code)) return code
  return new Intl.DisplayNames([locale], { type: "region" }).of(code) ?? code
}

function formatGeoTokens(value: number) {
  return formatTokens(value * 1_000_000_000_000)
}

function formatGeoShare(value: number) {
  return `${value.toFixed(value > 0 && value < 1 ? 1 : 0)}%`
}

function momentumChart(data: ModelUsagePoint[], updatedAt: string | null) {
  const fallbackDate = updatedAt ? formatMomentumDateLabel(updatedAt) : "JAN 1"
  const points =
    data.length > 1 ? data : [data[0] ?? emptyUsagePoint(fallbackDate), data[0] ?? emptyUsagePoint(fallbackDate)]
  const max = Math.max(1, ...points.map((point) => point.tokens))
  const split = Math.max(1, Math.floor((points.length - 1) / 2))
  const coordinates = points.map((point, index) => ({
    date: point.date,
    tokens: point.tokens,
    x: (index / Math.max(1, points.length - 1)) * 1200,
    y: 364 - (point.tokens / max) * 364,
  }))
  const end = coordinates[coordinates.length - 1]
  return {
    startDate: coordinates[0].date,
    endDate: end.date,
    previousPath: smoothLinePath(coordinates.slice(0, split + 1)),
    currentPath: smoothLinePath(coordinates.slice(split)),
    markers: [
      { ...coordinates[0], active: false },
      { ...coordinates[split], active: true },
      { ...end, active: true },
    ],
    endStyle: {
      "--momentum-end-x": `${Math.min(94, Math.max(0, ((end.x + 8) / 1200) * 100))}%`,
      "--momentum-end-y": `${Math.min(96, Math.max(0, ((end.y - 7) / 370) * 100))}%`,
    } as JSX.CSSProperties,
  }
}

function emptyUsagePoint(date: string): ModelUsagePoint {
  return { date, tokens: 0, users: 0, sessions: 0, cost: 0 }
}

function smoothLinePath(points: { x: number; y: number }[]) {
  if (points.length === 0) return ""
  if (points.length === 1) return `M${formatSparklinePoint(points[0].x)} ${formatSparklinePoint(points[0].y)}`
  return points
    .map((point, index) => {
      if (index === 0) return `M${formatSparklinePoint(point.x)} ${formatSparklinePoint(point.y)}`
      const previous = points[index - 1]
      const next = points[index + 1] ?? point
      const beforePrevious = points[index - 2] ?? previous
      const controlStart = {
        x: previous.x + (point.x - beforePrevious.x) / 6,
        y: previous.y + (point.y - beforePrevious.y) / 6,
      }
      const controlEnd = {
        x: point.x - (next.x - previous.x) / 6,
        y: point.y - (next.y - previous.y) / 6,
      }
      return `C${formatSparklinePoint(controlStart.x)} ${formatSparklinePoint(controlStart.y)} ${formatSparklinePoint(controlEnd.x)} ${formatSparklinePoint(controlEnd.y)} ${formatSparklinePoint(point.x)} ${formatSparklinePoint(point.y)}`
    })
    .join(" ")
}

function momentumMonthLabels(startDate: string, locale: string, updatedAt: string | null) {
  const start = parseMomentumDate(startDate, updatedAt)
  const first = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() - 1, 1))
  return Array.from({ length: 5 }, (_, index) => {
    const date = new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth() + index, 1))
    return {
      label: new Intl.DateTimeFormat(locale, { month: "short", timeZone: "UTC" }).format(date).toUpperCase(),
      x: index === 4 ? 98 : index * 24.5,
    }
  })
}

function formatMomentumDate(date: string, locale: string, updatedAt: string | null) {
  return new Intl.DateTimeFormat(locale, {
    month: "short",
    day: "numeric",
    year: "numeric",
    timeZone: "UTC",
  })
    .format(parseMomentumDate(date, updatedAt))
    .toUpperCase()
}

function parseMomentumDate(date: string, updatedAt: string | null): Date {
  const iso = /^(\d{4})-(\d{2})-(\d{2})/.exec(date)
  if (iso) return new Date(Date.UTC(Number(iso[1]), Number(iso[2]) - 1, Number(iso[3])))

  const label = /^([A-Za-z]{3})\s+(\d{1,2})$/.exec(date.trim())
  const month = label ? shortMonths.findIndex((item) => item.toLowerCase() === label[1].toLowerCase()) : -1
  if (!label || month < 0) return new Date(Date.UTC(1970, 0, 1))

  const anchor = updatedAt ? parseMomentumDate(updatedAt, null) : new Date(Date.UTC(1970, 0, 1))
  const year = month > anchor.getUTCMonth() + 1 ? anchor.getUTCFullYear() - 1 : anchor.getUTCFullYear()
  return new Date(Date.UTC(year, month, Number(label[2])))
}

function formatMomentumDateLabel(date: string) {
  const parsed = parseMomentumDate(date, null)
  if (parsed.getUTCFullYear() === 1970) return "JAN 1"
  return `${shortMonths[parsed.getUTCMonth()]} ${parsed.getUTCDate()}`
}

function formatRankLabel(rank: number | null) {
  if (rank === null) return "--"
  return `#${String(rank).padStart(2, "0")}`
}

function capitalizeLabel(value: string) {
  return value.charAt(0).toUpperCase() + value.slice(1)
}

function formatRankMove(change: number) {
  if (change > 0) return `+${change}`
  return `${change}`
}

function formatHeroRank(rank: number | null) {
  if (rank === null) return "--"
  return String(rank).padStart(2, "0")
}

function sparklineLinePath(values: number[]) {
  return sparklinePoints(values)
    .map(
      (point, index) => `${index === 0 ? "M" : "L"}${formatSparklinePoint(point.x)} ${formatSparklinePoint(point.y)}`,
    )
    .join(" ")
}

function sparklineAreaPath(values: number[]) {
  const points = sparklinePoints(values)
  return `M${formatSparklinePoint(points[0].x)} 18 ${points
    .map((point) => `L${formatSparklinePoint(point.x)} ${formatSparklinePoint(point.y)}`)
    .join(" ")} L${formatSparklinePoint(points[points.length - 1].x)} 18 Z`
}

function sparklinePoints(values: number[]) {
  const normalized = values.length > 1 ? values : [values[0] ?? 0, values[0] ?? 0]
  const min = Math.min(...normalized)
  const max = Math.max(...normalized)
  return normalized.map((value, index) => ({
    x: 8 + (index / Math.max(1, normalized.length - 1)) * 20,
    y: min === max ? 12 : 18 - ((value - min) / (max - min)) * 12,
  }))
}

function formatSparklinePoint(value: number) {
  return Number(value.toFixed(2)).toString()
}

function formatModelRankMoveLabel(data: StatsModelData, i18n: ReturnType<typeof useI18n>) {
  if (data.rank === null) return i18n.t("model.noUsageLastWeek")
  if (data.previousRank === null) return i18n.t("model.newThisWeek")
  const change = data.previousRank - data.rank
  if (change === 0) return i18n.t("model.sameAsPreviousWeek")
  return i18n.t("model.vsPreviousWeek", { change: formatRankMove(change) })
}

function formatTokens(value: number) {
  if (value >= 1_000_000_000_000)
    return `${trimNumber(value / 1_000_000_000_000, value >= 10_000_000_000_000 ? 0 : 1)}T`
  if (value >= 1_000_000_000) return `${trimNumber(value / 1_000_000_000, value >= 10_000_000_000 ? 0 : 1)}B`
  if (value >= 1_000_000) return `${trimNumber(value / 1_000_000, value >= 10_000_000 ? 0 : 1)}M`
  if (value >= 1_000) return `${trimNumber(value / 1_000, value >= 10_000 ? 0 : 1)}K`
  return String(Math.round(value))
}

function formatCatalogLimit(value: number | undefined, unknown: string) {
  return value === undefined ? unknown : formatTokens(value)
}

function formatCatalogMonth(value: string | undefined, locale: string, unknown: string) {
  if (!value) return unknown
  const match = /^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/.exec(value)
  if (!match) return value
  return new Intl.DateTimeFormat(locale, {
    month: match[2] ? "short" : undefined,
    year: "numeric",
    timeZone: "UTC",
  }).format(new Date(Date.UTC(Number(match[1]), match[2] ? Number(match[2]) - 1 : 0, 1)))
}

function formatCatalogModalities(values: string[], locale: string, unknown: string) {
  if (values.length === 0) return unknown
  const labels = values.map((value) => value.replace(/[-_]/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase()))
  if (labels.length === 1) return labels[0] ?? unknown
  return new Intl.ListFormat(locale, { style: "long", type: "conjunction" }).format(labels)
}

function formatInteger(value: number) {
  return new Intl.NumberFormat("en").format(value)
}

function formatUsers(value: number) {
  if (value >= 1_000_000) return `${trimNumber(value / 1_000_000, value >= 10_000_000 ? 0 : 1)}M`
  if (value >= 1_000) return `${trimNumber(value / 1_000, value >= 10_000 ? 0 : 1)}K`
  return formatInteger(Math.round(value))
}

function formatPercent(value: number) {
  return `${value.toFixed(value > 0 && value < 10 ? 1 : 0)}%`
}

function formatMoney(value: number) {
  if (value >= 1_000_000) return `$${trimNumber(value / 1_000_000, value >= 10_000_000 ? 0 : 1)}M`
  if (value >= 1_000) return `$${trimNumber(value / 1_000, value >= 10_000 ? 0 : 1)}K`
  return `$${value.toFixed(value >= 10 ? 0 : 2)}`
}

function formatCatalogPrice(value: ModelCatalogCost) {
  return `${formatModelPrice(value.input)} / ${formatModelPrice(value.output)}`
}

function formatModelPrice(value: number) {
  if (value > 0 && value < 0.01) return `$${value.toFixed(4)}`
  return formatMoney(value)
}

function formatSessionCost(value: number) {
  return `$${value.toFixed(value > 0 && value < 0.01 ? 4 : 2)}`
}

function formatChange(value: number) {
  if (value > 0) return `+${value}%`
  return `${value}%`
}

function trimNumber(value: number, digits: number) {
  return Number(value.toFixed(digits)).toLocaleString("en")
}

function providerSlug(provider: string) {
  return provider
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .replace(/-{2,}/g, "-")
}
