<script lang="ts">
  import { categories, totalCalculators } from '$lib/data/stats';
  import CategoryCard from '$lib/components/CategoryCard.svelte';
  import SearchBar from '$lib/components/SearchBar.svelte';
  import { buildSeoMeta, SITE_NAME, SITE_URL, toJsonLd } from '$lib/seo';

  const requiredCategoryFallbacks: Record<string, { label: string; icon: string }> = {
    fluids: { label: 'Fluids', icon: '💧' },
    magnetism: { label: 'Magnetism', icon: '🧲' },
  };

  const homepageCategories = {
    ...requiredCategoryFallbacks,
    ...categories,
  };

  const cats = Object.entries(homepageCategories).map(([key, meta]) => ({
    key,
    ...meta,
  }));
  const totalConversions = totalCalculators;
  const totalCategoriesCount = Object.keys(homepageCategories).length;
  const pageTitle = `${SITE_NAME} — Free Unit Conversion Calculators`;
  const pageDescription = 'Convert between hundreds of units instantly. Free online calculators for length, weight, temperature, volume, area, speed, energy, power, data and more.';
  const seo = buildSeoMeta({
    title: pageTitle,
    description: pageDescription,
    pathname: '/',
  });
  const websiteJsonLd = toJsonLd({
    '@context': 'https://schema.org',
    '@type': 'WebSite',
    name: SITE_NAME,
    description: pageDescription,
    url: SITE_URL,
  });
</script>

<svelte:head>
  <title>{pageTitle}</title>
  <meta name="description" content={pageDescription} />
  <meta name="robots" content={seo.robots} />
  <link rel="canonical" href={seo.canonical} />
  <meta property="og:type" content={seo.og.type} />
  <meta property="og:title" content={seo.og.title} />
  <meta property="og:description" content={seo.og.description} />
  <meta property="og:url" content={seo.og.url} />
  <meta property="og:site_name" content={seo.og.siteName} />
  <meta name="twitter:card" content={seo.twitter.card} />
  <meta name="twitter:title" content={seo.twitter.title} />
  <meta name="twitter:description" content={seo.twitter.description} />
  {@html `<script type="application/ld+json">${websiteJsonLd}</script>`}
</svelte:head>

<section class="hero">
  <h1>How Do You Convert?</h1>
  <p>Fast unit conversions with no ads.</p>
  <div class="search-center">
    <SearchBar idPrefix="home-search" />
  </div>
</section>

<div class="stats-row">
  <div class="stat">
    <div class="stat-num">{totalConversions}</div>
    <div class="stat-label">Converters</div>
  </div>
  <div class="stat">
    <div class="stat-num">{totalCategoriesCount}</div>
    <div class="stat-label">Categories</div>
  </div>
</div>

<section class="category-section">
  <div class="category-section__inner">
    <h2 class="section-heading">Browse by Category</h2>
    <div class="category-grid">
      {#each cats as cat}
        <CategoryCard icon={cat.icon} label={cat.label} href="/category/{cat.key}" />
      {/each}
    </div>
  </div>
</section>
