/* eslint-disable @next/next/no-img-element */
"use client";

// KotschAds-Renderer: holt Eigenwerbung (Apps, Webtools, Shop, Affiliate) von kotsch.tech
// und rendert sie im Toolaro-Neo-Brutalist-Look. Klick läuft über ad.url (zählt serverseitig).
// Verwaltung: kotsch.tech/admin/werbung — Änderungen sind hier in ≤60 s live, ohne Rebuild.

import { useEffect, useState } from "react";
import { Gift, Megaphone, ShoppingBag, Smartphone, Wrench } from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { fetchHouseAds, RAIL_BANNERS, type HouseAd } from "@/lib/ads";

const ICONS: Record<HouseAd["type"], LucideIcon> = {
  app: Smartphone,
  webtool: Wrench,
  shop: ShoppingBag,
  affiliate: Megaphone,
  custom: Gift,
};

function Card({ ad, vertical }: { ad: HouseAd; vertical: boolean }) {
  const Icon = ICONS[ad.type] ?? Gift;
  return (
    <a
      href={ad.url}
      target="_blank"
      rel="noopener"
      aria-label={`Empfehlung: ${ad.title}`}
      className={cn(
        "group block border-2 border-ink-primary bg-surface-base no-underline",
        "shadow-[4px_4px_0_rgb(var(--ink-primary))]",
        "transition-[transform,box-shadow] duration-[120ms] [transition-timing-function:steps(2)]",
        "hover:translate-x-[4px] hover:translate-y-[4px] hover:shadow-[0_0_0_rgb(var(--ink-primary))]"
      )}
    >
      <span className="block border-b-2 border-ink-primary bg-surface-sunken px-2 py-1 text-center font-mono text-[0.58rem] font-bold uppercase tracking-[0.18em] text-ink-secondary">
        Empfehlung
      </span>
      <span className={cn("flex gap-3 p-3", vertical ? "flex-col items-center text-center" : "flex-row items-center")}>
        {ad.video ? (
          <video
            src={ad.video}
            muted
            loop
            autoPlay
            playsInline
            className={cn("shrink-0 border-2 border-ink-primary object-cover", vertical ? "h-20 w-full" : "h-14 w-20")}
          />
        ) : ad.image ? (
          <img
            src={ad.image}
            alt=""
            loading="lazy"
            className={cn("shrink-0 rounded-lg border-2 border-ink-primary bg-white object-cover", vertical ? "h-14 w-14" : "h-12 w-12")}
          />
        ) : (
          <span className={cn("flex shrink-0 items-center justify-center rounded-lg border-2 border-ink-primary bg-brand-500 text-surface-base", vertical ? "h-14 w-14" : "h-12 w-12")}>
            <Icon className="h-6 w-6" aria-hidden />
          </span>
        )}
        <span className={cn("flex min-w-0 flex-col", vertical ? "items-center gap-1.5" : "items-start gap-1")}>
          <span className={cn("font-display font-bold leading-tight text-ink-primary", vertical ? "text-[0.8rem] line-clamp-2" : "text-sm")}>{ad.title}</span>
          {!vertical && ad.body && (
            <span className="font-mono text-[0.68rem] leading-snug text-ink-secondary line-clamp-1">{ad.body}</span>
          )}
          <span className="inline-block border-2 border-ink-primary bg-brand-500 px-2 py-0.5 font-mono text-[0.6rem] font-bold uppercase tracking-wide text-surface-base">
            {ad.cta} →
          </span>
        </span>
      </span>
    </a>
  );
}

export function DirectLinkBanner({
  slot,
  side,
  className,
}: {
  slot: "banner" | "sidebar" | "in-content" | "rail";
  side?: "left" | "right";
  className?: string;
}) {
  const [ads, setAds] = useState<HouseAd[]>([]);
  const count = slot === "rail" ? Math.max(1, RAIL_BANNERS[side ?? "right"] ?? 2) : 1;
  const zone = slot === "rail" ? "rail" : slot === "sidebar" ? "sidebar" : "inline";

  useEffect(() => {
    let alive = true;
    fetchHouseAds(zone, count).then((a) => {
      if (alive) setAds(a);
    });
    return () => {
      alive = false;
    };
  }, [zone, count]);

  if (!ads.length) return null;

  if (slot === "rail") {
    return (
      <div className={cn("my-6 flex w-full max-w-[160px] flex-col gap-4", className)}>
        {ads.map((ad) => (
          <Card key={ad.id} ad={ad} vertical />
        ))}
      </div>
    );
  }

  if (slot === "sidebar") {
    return (
      <div className={cn("my-6 w-full max-w-[300px]", className)}>
        <Card ad={ads[0]} vertical />
      </div>
    );
  }

  // banner / in-content: eine horizontale Karte
  return (
    <div className={cn("my-6 w-full", className)}>
      <Card ad={ads[0]} vertical={false} />
    </div>
  );
}
