/**
 * V3 social card — sport icon + league badge + country flag.
 * satori (HTML/CSS → SVG) → resvg (SVG → PNG).
 */

import satori from "satori";
import { Resvg } from "@resvg/resvg-js";
import * as fs from "fs";
import * as path from "path";

const OUTPUT_DIR = path.join(process.cwd(), "public", "predictions");
const ASSETS_DIR = path.join(process.cwd(), "src", "modules", "social-poster", "assets");
const ARIAL = fs.readFileSync("C:/Windows/Fonts/arial.ttf");
const ARIAL_BOLD = fs.readFileSync("C:/Windows/Fonts/arialbd.ttf");
const ARIAL_BLACK = fs.existsSync("C:/Windows/Fonts/ariblk.ttf")
  ? fs.readFileSync("C:/Windows/Fonts/ariblk.ttf")
  : ARIAL_BOLD;

function loadAsset(name: string): string {
  const p = path.join(ASSETS_DIR, name);
  if (!fs.existsSync(p)) return "";
  const svg = fs.readFileSync(p, "utf-8");
  return `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`;
}

interface Pick { market: string; pick: string; confidence: number; odds: number; }
interface Card {
  sport: "football" | "basketball";
  leagueName: string;
  leagueCode?: string;       // e.g. "UCL", "SL"
  countryName: string;
  countryCode?: string;      // "TR" | "ES" | "EU" | ...
  matchDate: string;
  homeTeam: string;
  awayTeam: string;
  htScore: string;
  ftScore: string;
  scoreConfidence: number;
  picks: Pick[];
}

type N = string | { type: string; props: { style?: any; children?: any; src?: string; width?: number; height?: number } };
const h = (type: string, style: any, ...children: N[]): N => ({
  type,
  props: { style, children: children.length === 1 ? children[0] : children },
});

// ── INLINE SVG GENERATORS (no network, embedded as data URIs) ────────────

function dataUri(svg: string): string {
  return `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`;
}

function ballSvg(sport: "football" | "basketball"): string {
  // Use Twemoji (Twitter's MIT-licensed emoji set) — recognized everywhere.
  return loadAsset(sport === "basketball" ? "basketball.svg" : "football.svg");
}

const FLAG_MAP: Record<string, string> = {
  TR: "flag-tr.svg",
  EU: "flag-eu.svg",
  GB: "flag-gb.svg", UK: "flag-gb.svg", EN: "flag-gb.svg",
  ES: "flag-es.svg",
  IT: "flag-it.svg",
  DE: "flag-de.svg",
  FR: "flag-fr.svg",
  US: "flag-us.svg",
};

function flagSvg(code: string): string {
  const c = (code || "").toUpperCase();
  const file = FLAG_MAP[c];
  if (!file) {
    // Generic dark badge with country code
    const fallback = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40">
      <rect width="60" height="40" rx="4" fill="#374151"/>
      <text x="30" y="26" font-size="14" font-weight="bold" font-family="Arial" fill="white" text-anchor="middle">${c}</text>
    </svg>`;
    return dataUri(fallback);
  }
  return loadAsset(file);
}

function leagueBadgeSvg(code: string, color: string, size = 70): string {
  // Shield/circle with league initials
  return dataUri(`
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80" width="${size}" height="${size}">
      <defs>
        <radialGradient id="g" cx="35%" cy="30%">
          <stop offset="0%" stop-color="${color}"/>
          <stop offset="100%" stop-color="#1F2937"/>
        </radialGradient>
      </defs>
      <path d="M 40 4 L 72 14 L 72 42 Q 72 64 40 76 Q 8 64 8 42 L 8 14 Z"
            fill="url(#g)" stroke="${color}" stroke-width="2.5"/>
      <text x="40" y="52" font-size="${code.length > 3 ? 18 : 26}" font-weight="900"
            font-family="Arial" fill="white" text-anchor="middle">${code.slice(0, 4)}</text>
    </svg>`);
}

// ── CARD ─────────────────────────────────────────────────────────────────

function buildCard(c: Card): N {
  const isBasket = c.sport === "basketball";
  const accent = isBasket ? "#F59E0B" : "#22C55E";
  const accentDark = isBasket ? "#92400E" : "#14532D";
  const away = "#3B82F6";
  const awayDark = "#1E3A8A";
  const sportLabel = isBasket ? "BASKETBOL TAHMİNİ" : "FUTBOL TAHMİNİ";
  const halfLabel = isBasket ? "İLK DEVRE" : "İLK YARI";
  const leagueCode = (c.leagueCode || c.leagueName.split(" ").map(w => w[0]).join("")).toUpperCase();
  const countryCode = (c.countryCode || "EU").toUpperCase();

  const avatar = (name: string, c1: string, c2: string) =>
    h("div", {
      display: "flex", alignItems: "center", justifyContent: "center",
      width: 180, height: 180, borderRadius: 180,
      background: `linear-gradient(135deg, ${c1} 0%, ${c2} 100%)`,
      fontSize: 110, fontWeight: 900, color: "white",
      boxShadow: "0 20px 50px rgba(0,0,0,0.55), inset 0 -6px 0 rgba(0,0,0,0.22)",
    }, (name.match(/\p{L}/u)?.[0] || "?").toUpperCase());

  const teamColumn = (name: string, c1: string, c2: string) =>
    h("div", {
      display: "flex", flexDirection: "column", alignItems: "center", width: 280,
    },
      avatar(name, c1, c2),
      h("div", {
        display: "flex", marginTop: 18, fontSize: 28, fontWeight: 900,
        color: "white", textAlign: "center", lineHeight: 1.05,
        maxWidth: 280, justifyContent: "center",
      }, name),
    );

  const scoreBlock = h("div", {
    display: "flex", flexDirection: "column", alignItems: "center",
  },
    // Sport icon (BIG, this is the visual distinction)
    h("div", { display: "flex", marginBottom: 8 },
      h("img", { width: 110, height: 110 } as any, ...[]) as any,
    ),
    h("div", {
      display: "flex", fontSize: 12, color: "rgba(255,255,255,0.4)",
      letterSpacing: 4, fontWeight: 700, marginBottom: 6,
    }, "MAÇ SONU"),
    h("div", {
      display: "flex", fontSize: 92, fontWeight: 900, color: "white",
      lineHeight: 1, letterSpacing: -3,
    }, c.ftScore),
    h("div", {
      display: "flex", marginTop: 12, fontSize: 16, color: accent,
      fontWeight: 800, background: `${accent}22`, padding: "6px 14px",
      borderRadius: 10, letterSpacing: 1,
    }, `${halfLabel} ${c.htScore}`),
  );
  // Replace the placeholder img with actual ball image
  ((scoreBlock as any).props.children[0] as any).props.children = {
    type: "img",
    props: { src: ballSvg(c.sport), width: 110, height: 110, style: { width: 110, height: 110 } },
  };

  const pickRow = (p: Pick, idx: number) =>
    h("div", {
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "18px 24px", marginBottom: 11,
      background: "rgba(255,255,255,0.045)",
      borderLeft: `5px solid ${accent}`,
      borderRadius: 12,
    },
      h("div", { display: "flex", alignItems: "center", flexGrow: 1 },
        h("div", {
          display: "flex", justifyContent: "center", alignItems: "center",
          width: 40, height: 40, marginRight: 16, borderRadius: 8,
          background: `${accent}22`, color: accent, fontSize: 22, fontWeight: 900,
        }, String(idx + 1)),
        h("div", { display: "flex", flexDirection: "column" },
          h("div", { display: "flex", fontSize: 26, fontWeight: 800, color: "white", lineHeight: 1.1 }, p.market),
          h("div", { display: "flex", marginTop: 4, fontSize: 16, color: "rgba(255,255,255,0.5)" }, `Oran ${p.odds.toFixed(2)}`),
        ),
      ),
      h("div", {
        display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: 34, fontWeight: 900, color: accent,
        background: `${accent}15`,
        padding: "6px 16px", borderRadius: 10,
        border: `1px solid ${accent}`,
      }, `%${p.confidence}`),
    );

  // Helper for inline <img>
  const img = (src: string, w: number, hh: number) => ({
    type: "img",
    props: { src, width: w, height: hh, style: { width: w, height: hh } },
  } as any);

  return h("div", {
    width: 1080, height: 1080,
    display: "flex", flexDirection: "column",
    padding: "44px 56px",
    background: "linear-gradient(180deg, #0F172A 0%, #020617 100%)",
    color: "white",
    fontFamily: "Arial",
  },
    // ── HEADER: league badge + flag + name + date ──
    h("div", {
      display: "flex", alignItems: "center", justifyContent: "space-between",
      marginBottom: 28,
    },
      h("div", { display: "flex", alignItems: "center" },
        img(leagueBadgeSvg(leagueCode, accent), 64, 64),
        h("div", { display: "flex", flexDirection: "column", marginLeft: 16 },
          h("div", { display: "flex", alignItems: "center" },
            img(flagSvg(countryCode), 30, 20),
            h("div", {
              display: "flex", marginLeft: 10, fontSize: 14, color: "rgba(255,255,255,0.55)",
              letterSpacing: 2, fontWeight: 700,
            }, `${sportLabel}  ·  ${c.countryName.toUpperCase()}`),
          ),
          h("div", {
            display: "flex", marginTop: 4, fontSize: 28, fontWeight: 900, color: "white",
          }, c.leagueName),
        ),
      ),
      h("div", {
        display: "flex", fontSize: 16, color: "rgba(255,255,255,0.6)",
        background: "rgba(255,255,255,0.05)",
        padding: "10px 16px", borderRadius: 10,
        border: "1px solid rgba(255,255,255,0.1)", fontWeight: 600,
      }, c.matchDate),
    ),

    // ── TEAMS + SCORE ──
    h("div", {
      display: "flex", alignItems: "center", justifyContent: "space-between",
      marginBottom: 26, paddingLeft: 6, paddingRight: 6,
    },
      teamColumn(c.homeTeam, accent, accentDark),
      scoreBlock,
      teamColumn(c.awayTeam, away, awayDark),
    ),

    // ── PICKS TITLE ──
    h("div", {
      display: "flex", alignItems: "center", justifyContent: "space-between",
      marginBottom: 14, paddingLeft: 6, paddingRight: 6,
    },
      h("div", { display: "flex", fontSize: 22, fontWeight: 900, color: "white", letterSpacing: 2 }, "EN İYİ 3 TAHMİN"),
      h("div", { display: "flex", alignItems: "center" },
        h("div", { display: "flex", fontSize: 13, color: "rgba(255,255,255,0.55)", fontWeight: 700, marginRight: 8 }, "SKOR GÜVENİ"),
        h("div", { display: "flex", fontSize: 22, fontWeight: 900, color: accent }, `%${c.scoreConfidence}`),
      ),
    ),

    // ── PICKS LIST ──
    h("div", { display: "flex", flexDirection: "column" },
      ...c.picks.slice(0, 3).map((p, i) => pickRow(p, i)),
    ),

    // ── FOOTER ──
    h("div", {
      display: "flex", marginTop: "auto", alignItems: "center", justifyContent: "space-between",
      paddingTop: 20, borderTop: "1px solid rgba(255,255,255,0.08)",
    },
      h("div", { display: "flex", alignItems: "center" },
        img(ballSvg(c.sport), 28, 28),
        h("div", { display: "flex", marginLeft: 10, fontSize: 15, color: "rgba(255,255,255,0.5)", fontWeight: 600 }, "AI Destekli Maç Tahmini"),
      ),
      h("div", { display: "flex", fontSize: 20, color: "white", fontWeight: 900, letterSpacing: 2 }, "iddaai.com"),
    ),
  );
}

async function renderCard(c: Card, name: string) {
  const svg = await satori(buildCard(c) as any, {
    width: 1080,
    height: 1080,
    fonts: [
      { name: "Arial", data: ARIAL, weight: 400, style: "normal" },
      { name: "Arial", data: ARIAL_BOLD, weight: 700, style: "normal" },
      { name: "Arial", data: ARIAL_BLACK, weight: 900, style: "normal" },
    ],
  });
  const png = new Resvg(svg).render().asPng();
  const out = path.join(OUTPUT_DIR, `v3-${name}.png`);
  fs.writeFileSync(out, png);
  console.log(`  → ${out}`);
}

async function main() {
  if (!fs.existsSync(OUTPUT_DIR)) fs.mkdirSync(OUTPUT_DIR, { recursive: true });

  await renderCard({
    sport: "basketball",
    leagueName: "Şampiyonlar Ligi",
    leagueCode: "UCL",
    countryName: "Avrupa",
    countryCode: "EU",
    matchDate: "25 May 2026, 21:00",
    homeTeam: "Unicaja Malaga",
    awayTeam: "AEK",
    htScore: "40-35",
    ftScore: "88-75",
    scoreConfidence: 90,
    picks: [
      { market: "Toplam Sayı Üst 160.5", pick: "Üst", confidence: 85, odds: 1.85 },
      { market: "Ev Sahibi Toplam Üst 82.5", pick: "Üst", confidence: 83, odds: 1.78 },
      { market: "Handikap Ev Sahibi -5.5", pick: "1", confidence: 78, odds: 1.92 },
    ],
  }, "basket-unicaja-aek");

  await renderCard({
    sport: "football",
    leagueName: "Süper Lig",
    leagueCode: "SL",
    countryName: "Türkiye",
    countryCode: "TR",
    matchDate: "26 May 2026, 20:00",
    homeTeam: "Galatasaray",
    awayTeam: "Fenerbahçe",
    htScore: "1-0",
    ftScore: "2-1",
    scoreConfidence: 72,
    picks: [
      { market: "Maç Sonucu - Ev Sahibi", pick: "1", confidence: 68, odds: 2.15 },
      { market: "Üst 2.5 Gol", pick: "Üst", confidence: 61, odds: 1.92 },
      { market: "Karşılıklı Gol", pick: "Var", confidence: 58, odds: 1.75 },
    ],
  }, "football-gs-fb");
}

main().catch((e) => { console.error(e); process.exit(1); });
