---
import type { GetStaticPaths } from 'astro'
import BaseLayout from '../../../layouts/BaseLayout.astro'
import ModelHeroSection from '../../../components/models/ModelHeroSection.vue'
import { models, getModelBySlug } from '../../../config/models'
import { t } from '../../../i18n/translations'

export const getStaticPaths: GetStaticPaths = () => {
  return models.map((model) => ({
    params: { slug: model.slug }
  }))
}

const { slug } = Astro.params
const model = getModelBySlug(slug as string)!

if (model.canonicalSlug) {
  return Astro.redirect(`/p/supported-models/${model.canonicalSlug}`, 301)
}

const { displayName } = model
const canonicalURL = new URL(`/p/supported-models/${model.slug}`, Astro.site)

const dirDescriptions: Record<string, string> = {
  diffusion_models: 'a diffusion model that generates images or video from text and image prompts',
  checkpoints: 'an all-in-one checkpoint model that bundles a diffusion model, text encoder, and VAE',
  loras: 'a LoRA (Low-Rank Adaptation) that fine-tunes an existing model for a specific style or subject',
  controlnet: 'a ControlNet that steers image generation using structural guides like depth maps, edges, or poses',
  clip_vision: 'a CLIP Vision encoder that converts images into embeddings for conditioning or style transfer',
  vae: 'a VAE (Variational Autoencoder) that encodes and decodes latent representations',
  text_encoders: 'a text encoder that converts prompts into embeddings used to guide generation',
  audio_encoders: 'an audio encoder that converts audio into embeddings for audio-conditioned generation',
  upscale_models: 'an upscale model that increases image resolution while preserving or enhancing detail',
  latent_upscale_models: 'a latent upscale model that refines latents at higher resolution before decoding',
  style_models: 'a style model that transfers artistic style onto generated images',
  model_patches: 'a model patch that modifies or extends the behavior of an existing base model',
  partner_nodes: 'a cloud API model accessible through ComfyUI partner nodes without local hardware requirements'
}

const dirDesc = dirDescriptions[model.directory] ?? 'an AI model'
const whatIsDescription = `${displayName} is ${dirDesc}. You can run it locally in ComfyUI with full control over every parameter, or access it through Comfy Cloud. ComfyUI's node-based workflow editor lets you connect ${displayName} with ControlNets, LoRAs, upscalers, and custom nodes to build any pipeline you need. There are ${model.workflowCount} community workflow templates using ${displayName} on Comfy Hub, ready to load and customize.`

const softwareAppJsonLd = {
  '@context': 'https://schema.org',
  '@type': 'SoftwareApplication',
  name: displayName,
  applicationCategory: 'MultimediaApplication',
  operatingSystem: 'Any',
  url: canonicalURL.href,
  author: {
    '@type': 'Organization',
    name: 'Comfy Org',
    url: 'https://comfy.org'
  }
}

const breadcrumbJsonLd = {
  '@context': 'https://schema.org',
  '@type': 'BreadcrumbList',
  itemListElement: [
    {
      '@type': 'ListItem',
      position: 1,
      name: t('models.breadcrumb.home'),
      item: 'https://comfy.org'
    },
    {
      '@type': 'ListItem',
      position: 2,
      name: t('models.breadcrumb.models'),
      item: 'https://comfy.org/p/supported-models'
    },
    {
      '@type': 'ListItem',
      position: 3,
      name: displayName
    }
  ]
}

const faqJsonLd = {
  '@context': 'https://schema.org',
  '@type': 'FAQPage',
  mainEntity: [
    {
      '@type': 'Question',
      name: `What is ${displayName}?`,
      acceptedAnswer: {
        '@type': 'Answer',
        text: whatIsDescription
      }
    },
    {
      '@type': 'Question',
      name: `How do I use ${displayName} in ComfyUI?`,
      acceptedAnswer: {
        '@type': 'Answer',
        text: model.docsUrl
          ? `Follow the step-by-step tutorial at ${model.docsUrl}. You can also load any of the ${model.workflowCount} community workflow templates that use ${displayName} directly in ComfyUI.`
          : `Open ComfyUI and browse the ${model.workflowCount} community workflow templates that use ${displayName}. Load one as a starting point, then customize the nodes and parameters to fit your use case.`
      }
    },
    {
      '@type': 'Question',
      name: `How many ComfyUI workflows use ${displayName}?`,
      acceptedAnswer: {
        '@type': 'Answer',
        text: `There are ${model.workflowCount} community workflow templates that use ${displayName} on Comfy Hub. Each template is ready to run in ComfyUI and can be customized to suit your project.`
      }
    },
    {
      '@type': 'Question',
      name: `Is ${displayName} free to use in ComfyUI?`,
      acceptedAnswer: {
        '@type': 'Answer',
        text: `ComfyUI is free and open source. ${model.huggingFaceUrl ? `${displayName} weights are available to download from Hugging Face.` : `${displayName} is available as a cloud API through Comfy Cloud.`} You only pay for compute when running on Comfy Cloud; local inference on your own hardware is always free.`
      }
    }
  ]
}

const pageTitle = `${displayName} in ComfyUI`
const pageDescription = `Run ${displayName} in ComfyUI with full parameter control. ${model.workflowCount} community workflow templates, step-by-step tutorials, and free local inference.`
---

<BaseLayout
  title={`${pageTitle} — Comfy`}
  description={pageDescription}
  ogImage={model.thumbnailUrl}
>
  <Fragment slot="head">
    <script
      is:inline
      type="application/ld+json"
      set:html={JSON.stringify(softwareAppJsonLd)}
    />
    <script
      is:inline
      type="application/ld+json"
      set:html={JSON.stringify(breadcrumbJsonLd)}
    />
    <script
      is:inline
      type="application/ld+json"
      set:html={JSON.stringify(faqJsonLd)}
    />
  </Fragment>

  <ModelHeroSection
    displayName={displayName}
    huggingFaceUrl={model.huggingFaceUrl}
    docsUrl={model.docsUrl}
    blogUrl={model.blogUrl}
    hubSlug={model.hubSlug}
    workflowCount={model.workflowCount}
    directory={model.directory}
  />

  <section class="mx-auto max-w-7xl px-6 py-16 lg:px-8">
    <h2 class="text-2xl font-bold text-primary-comfy-canvas lg:text-3xl">
      {t('models.whatIs.heading').replace('{name}', displayName)}
    </h2>
    <p class="mt-4 max-w-3xl text-base/relaxed text-primary-comfy-canvas/70 lg:text-lg/relaxed">
      {whatIsDescription}
    </p>
    {model.docsUrl && (
      <a
        href={model.docsUrl}
        target="_blank"
        rel="noopener noreferrer"
        class="mt-6 inline-block text-primary-comfy-yellow hover:underline"
      >
        {t('models.whatIs.tutorialLink')}
      </a>
    )}
  </section>

  <section>
    {/* TODO: workflow gallery — pulls from hub API */}
  </section>

  <section>
    {/* TODO: shared HowComfyWorks component */}
  </section>
</BaseLayout>
