---
import type { ContentItem } from "../lib/content/types";
import StandardCard from "./StandardCard.astro";

type Props = {
  item: ContentItem;
  placement: string;
};

const { item, placement } = Astro.props;

function truncate(s: string, n: number) {
  const t = (s || "").trim();
  if (t.length <= n) return t;
  return `${t.slice(0, Math.max(0, n - 1)).trimEnd()}…`;
}
const d = new Date(item.publishedAt);
const dateLabel = Number.isFinite(d.valueOf())
  ? d.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" })
  : "";

const targetId = `card.${placement}.${item.source}.${item.id}`;
let domain = "";
try {
  domain = new URL(item.url).hostname;
} catch {
  domain = "";
}

const umamiType =
  item.source === "youtube"
    ? "video"
    : item.source === "podcast"
      ? "podcast_episode"
      : undefined;

const umamiTitle = umamiType ? truncate(item.title, 160) : undefined;

// Determine if card should open modal (youtube/podcast) or link normally (other sources)
const isModalTrigger = item.source === "youtube" || item.source === "podcast";
const mode = isModalTrigger ? "modal" : "link";

// Build link attrs based on mode
const linkAttrs = isModalTrigger
  ? {
      // Modal trigger: pass all item data via data-* attributes
      "data-item-id": item.id,
      "data-item-source": item.source,
      "data-item-url": item.url,
      "data-item-title": item.title,
      "data-item-summary": item.summary || "",
      "data-item-published-at": item.publishedAt,
      "data-item-thumbnail-url": item.thumbnailUrl || "",
      "data-item-audio-url": item.source === "podcast" ? item.audioUrl || "" : "",
      "data-item-views": item.metrics?.views?.toString() || "",
      // Umami tracking: media_preview instead of outbound_click
      "data-umami-event": "media_preview",
      "data-umami-event-target_id": targetId,
      "data-umami-event-placement": placement,
      "data-umami-event-title": umamiTitle,
      "data-umami-event-type": umamiType,
      "data-umami-event-source": item.source,
    }
  : {
      // Normal link: outbound_click tracking
      "data-umami-event": "outbound_click",
      "data-umami-event-target_id": targetId,
      "data-umami-event-placement": placement,
      "data-umami-event-target_url": item.url,
      "data-umami-event-title": umamiTitle,
      "data-umami-event-type": umamiType,
      "data-umami-event-domain": domain || "unknown",
      "data-umami-event-source": item.source,
      "data-umami-event-ui_placement": "content_card",
    };
---

<StandardCard
  href={isModalTrigger ? undefined : item.url}
  title={item.title}
  summary={item.summary}
  imageUrl={item.thumbnailUrl}
  dateLabel={dateLabel}
  viewsLabel={item.metrics?.views !== undefined ? `${item.metrics.views.toLocaleString()} views` : undefined}
  sourceLabel={item.source}
  isExternal={!isModalTrigger}
  mode={mode}
  linkAttrs={linkAttrs}
/>
