<script lang="ts">
  import Icon from '$lib/components/Icon.svelte';
  import { getImageMetadata } from '$lib/image-metadata';
  import type { CallToAction, HeroContent } from '$lib/types';

  export let hero: HeroContent;
  export let reviewCta: CallToAction | undefined = undefined;

  $: titleParts = splitTitle(hero.title);
  $: mobileTitle = hero.mobileTitle?.trim() || `${hero.title} ${hero.highlight}`.trim();
  $: heroImage = getImageMetadata(hero.imageUrl);

  function splitTitle(title: string) {
    const trimmed = title.trim();

    if (trimmed.toLowerCase().endsWith(' in')) {
      return {
        lead: trimmed.slice(0, -3),
        connector: 'in'
      };
    }

    return {
      lead: trimmed,
      connector: ''
    };
  }
</script>

<section id="hero">
  <div class="hero-inner">
    <div class="hero-text">
      <h1 class="hero-heading">
        <span class="hero-heading-desktop">
          <span class="hero-title-main">{titleParts.lead}</span>
          {#if titleParts.connector}
            <span class="hero-title-connector"> {titleParts.connector}</span>
          {/if}
          <br />
          <span class="hero-title-highlight">{hero.highlight}</span>
        </span>
        <span class="hero-heading-mobile">{mobileTitle}</span>
      </h1>

      {#if hero.subtitle}
        <p class="hero-subtitle">{hero.subtitle}</p>
      {/if}

      {#if reviewCta}
        <a
          class="hero-trust-chip"
          href={reviewCta.href}
          target={reviewCta.external ? '_blank' : undefined}
          rel={reviewCta.external ? 'noopener' : undefined}
          aria-label="Read our five-star Google reviews"
        >
          <img
            class="hero-trust-logo"
            src="/images/google-g-logo.svg"
            alt=""
            width="18"
            height="19"
          />
          <span class="hero-trust-stars" aria-hidden="true">
            {#each Array(5) as _}
              <Icon name="fas fa-star" />
            {/each}
          </span>
          <span>{reviewCta.label}</span>
        </a>
      {/if}

      <div class="hero-buttons">
        <a href={hero.primaryCta.href} class="btn btn-yellow">{hero.primaryCta.label}</a>
        <a href={hero.secondaryCta.href} class="btn btn-outline">{hero.secondaryCta.label}</a>
      </div>
    </div>

    <div class="hero-img">
      <img
        src={hero.imageUrl}
        alt={hero.imageAlt}
        width={heroImage?.width}
        height={heroImage?.height}
        loading="eager"
        fetchpriority="high"
        decoding="async"
      />
    </div>
  </div>
</section>
