<script lang="ts">
  import { onMount } from 'svelte';
  import Icon from '$lib/components/Icon.svelte';
  import type { CallToAction, HeroContent } from '$lib/types';
  import { trackAb, type AbContext } from '$lib/ab';

  export let hero: HeroContent;
  export let reviewCta: CallToAction | undefined = undefined;
  export let primaryCtaOverride: CallToAction | undefined = undefined;
  export let ab: AbContext | undefined = undefined;

  $: primaryCta = primaryCtaOverride ?? hero.primaryCta;

  onMount(() => {
    if (ab) trackAb({ ...ab, event_type: 'exposure', meta: { surface: 'hero' } });
  });

  function handlePrimaryCtaClick() {
    if (ab) trackAb({ ...ab, event_type: 'cta_click', meta: { surface: 'hero_primary' } });
  }

  $: titleParts = splitTitle(hero.title);
  $: mobileTitle = hero.mobileTitle?.trim() || `${hero.title} ${hero.highlight}`.trim();
  $: mobileLead = mobileTitle.includes(hero.highlight)
    ? mobileTitle.slice(0, mobileTitle.lastIndexOf(hero.highlight))
    : mobileTitle;
  $: accessibleTitle = `${titleParts.lead}${titleParts.connector ? ` ${titleParts.connector}` : ''} ${hero.highlight}`.trim();
  $: proofItems = (hero.subtitleChips ?? []).slice(0, 3);

  const trustStars = Array.from({ length: 5 });

  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: ''
    };
  }

  function linkTarget(external?: boolean) {
    return external ? '_blank' : undefined;
  }

  function linkRel(external?: boolean) {
    return external ? 'noopener' : undefined;
  }
</script>

<section id="hero" data-track-location="hero">
  <!-- hero-img is a direct child of #hero so it can be absolutely
       positioned relative to the section on mobile without being
       constrained by hero-inner's stacking context -->
  <div class="hero-img">
    <picture>
      {#if hero.desktopImageWebpUrl}
        <source media="(min-width: 769px)" srcset={hero.desktopImageWebpUrl} type="image/webp" />
      {/if}
      {#if hero.desktopImageUrl}
        <source media="(min-width: 769px)" srcset={hero.desktopImageUrl} />
      {/if}
      {#if hero.imageWebpUrl}
        <source srcset={hero.imageWebpUrl} type="image/webp" />
      {/if}
      <img
        src={hero.imageUrl}
        alt={hero.imageAlt}
        width={hero.imageWidth ?? undefined}
        height={hero.imageHeight ?? undefined}
        loading="eager"
        fetchpriority="high"
      />
    </picture>
  </div>

  <div class="hero-inner">
    <div class="hero-text">
      {#if hero.kicker}
        <p class="hero-kicker">{hero.kicker}</p>
      {/if}

      <h1 class="hero-heading">
        <span class="visually-hidden">{accessibleTitle}</span>
        <span class="hero-heading-desktop" aria-hidden="true">
          <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" aria-hidden="true">
          {mobileLead}<span class="hero-title-highlight">{hero.highlight}</span>
        </span>
      </h1>

      {#if hero.seoHeading}
        <h2 class="hero-seo-heading">{hero.seoHeading}</h2>
      {/if}

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

      {#if proofItems.length || reviewCta}
        <div class="hero-chips" aria-label="Why owners choose Goodwalk">
          {#each proofItems as chip}
            <span class="hero-chip">
              <Icon name={chip.icon} />
              {chip.label}
            </span>
          {/each}
          {#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"
              data-track-event="social_proof_click"
              data-track-type="hero_reviews"
              data-track-label={reviewCta.label}
            >
              <span class="hero-trust-mark" aria-hidden="true">
                <img
                  class="hero-trust-logo"
                  src="/images/google-g-logo.svg"
                  alt=""
                  width="16"
                  height="17"
                />
              </span>
              <span class="hero-trust-stars" aria-hidden="true">
                {#each trustStars as _, index}
                  <Icon name="fas fa-star" className={`hero-trust-star hero-trust-star-${index + 1}`} />
                {/each}
              </span>
              <span class="hero-trust-label">{reviewCta.label}</span>
            </a>
          {/if}
        </div>
      {/if}

      <div class="hero-buttons">
        <a
          href={primaryCta.href}
          target={linkTarget(primaryCta.external)}
          rel={linkRel(primaryCta.external)}
          class="btn btn-yellow btn-with-arrow btn-hide-arrow-mobile"
          on:click={handlePrimaryCtaClick}
          data-track-event="cta_click"
          data-track-type="hero_primary"
          data-track-label={primaryCta.label}
        >
          {primaryCta.label}
          <Icon name="fas fa-arrow-right" />
        </a>
        <a
          href={hero.secondaryCta.href}
          target={linkTarget(hero.secondaryCta.external)}
          rel={linkRel(hero.secondaryCta.external)}
          class="hero-secondary-link"
          data-track-event="cta_click"
          data-track-type="hero_secondary"
          data-track-label={hero.secondaryCta.label}
        >
          {hero.secondaryCta.label}
          <Icon name="fas fa-arrow-down" className="hero-cta-arrow" />
        </a>
      </div>
    </div>
  </div>
</section>
