import { fetchBlogPost } from '@/lib/server-blog';
import { formatTeamDisplayName } from '@/lib/team-display';

function escapeXml(value: string): string {
  return value
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}

function truncate(value: string, max: number): string {
  if (value.length <= max) return value;
  return `${value.slice(0, Math.max(0, max - 1)).trimEnd()}...`;
}

export async function GET(
  _request: Request,
  context: { params: Promise<{ sport: string; slug: string }> }
) {
  const { sport, slug } = await context.params;
  const post = await fetchBlogPost(slug);
  const awayTeam = formatTeamDisplayName(post?.away_team);
  const homeTeam = formatTeamDisplayName(post?.home_team);

  const title = truncate(post?.title || 'Rainmaker Sports', 110);
  const subtitle = truncate(
    post?.excerpt || post?.meta_description || `${awayTeam || 'Away'} at ${homeTeam || 'Home'} preview and market context.`,
    170
  );
  const matchup = awayTeam && homeTeam
    ? `${awayTeam} @ ${homeTeam}`
    : `${sport.toUpperCase()} Rain Wire`;

  const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" width="1200" height="675" viewBox="0 0 1200 675" role="img" aria-label="${escapeXml(title)}">
      <defs>
        <linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stop-color="#090b11"/>
          <stop offset="55%" stop-color="#141924"/>
          <stop offset="100%" stop-color="#1d2432"/>
        </linearGradient>
        <linearGradient id="accent" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stop-color="#f97316"/>
          <stop offset="100%" stop-color="#22c55e"/>
        </linearGradient>
      </defs>
      <rect width="1200" height="675" fill="url(#bg)"/>
      <circle cx="1030" cy="96" r="142" fill="rgba(249,115,22,0.14)"/>
      <circle cx="150" cy="130" r="120" fill="rgba(74,158,255,0.12)"/>
      <rect x="0" y="0" width="1200" height="10" fill="url(#accent)"/>
      <text x="70" y="92" fill="#fb923c" font-size="28" font-family="Outfit, Arial, sans-serif" font-weight="700" letter-spacing="5">${escapeXml(sport.toUpperCase())} RAIN WIRE</text>
      <foreignObject x="70" y="128" width="860" height="280">
        <div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;height:100%;align-items:flex-start;font-family:Outfit,Arial,sans-serif;color:#ffffff;font-size:60px;line-height:1.06;font-weight:800;">
          ${escapeXml(title)}
        </div>
      </foreignObject>
      <foreignObject x="70" y="420" width="780" height="140">
        <div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;height:100%;align-items:flex-start;font-family:Outfit,Arial,sans-serif;color:rgba(255,255,255,0.78);font-size:28px;line-height:1.34;font-weight:500;">
          ${escapeXml(subtitle)}
        </div>
      </foreignObject>
      <text x="70" y="615" fill="rgba(255,255,255,0.56)" font-size="22" font-family="Outfit, Arial, sans-serif" font-weight="700" letter-spacing="4">MATCHUP</text>
      <text x="70" y="648" fill="#ffffff" font-size="34" font-family="Outfit, Arial, sans-serif" font-weight="700">${escapeXml(matchup)}</text>
      <text x="1130" y="636" text-anchor="end" fill="#f97316" font-size="32" font-family="Outfit, Arial, sans-serif" font-weight="800">Rainmaker Sports</text>
    </svg>
  `;

  return new Response(svg, {
    headers: {
      'Content-Type': 'image/svg+xml; charset=utf-8',
      'Cache-Control': 'public, max-age=3600, s-maxage=3600',
    },
  });
}
