import { readFileSync } from "node:fs";
import { join } from "node:path";
import satori from "satori";
import sharp from "sharp";

const fontRegular = readFileSync(
  join(
    process.cwd(),
    "node_modules/@fontsource/exo-2/files/exo-2-latin-400-normal.woff",
  ),
);
const fontBold = readFileSync(
  join(
    process.cwd(),
    "node_modules/@fontsource/exo-2/files/exo-2-latin-700-normal.woff",
  ),
);

export async function renderOgImage(
  vNode: Parameters<typeof satori>[0],
): Promise<ArrayBuffer> {
  const svg = await satori(vNode, {
    width: 1200,
    height: 630,
    fonts: [
      {
        name: "Exo 2",
        data: fontRegular.buffer,
        weight: 400,
        style: "normal",
      },
      {
        name: "Exo 2",
        data: fontBold.buffer,
        weight: 700,
        style: "normal",
      },
    ],
  });
  const buf = await sharp(Buffer.from(svg)).png().toBuffer();
  return buf.buffer.slice(
    buf.byteOffset,
    buf.byteOffset + buf.byteLength,
  ) as ArrayBuffer;
}

/**
 * Crop + resize a source image file to exactly 1200×630 (centered) and
 * return it as a base64 JPEG data URI ready for Satori backgroundImage.
 */
export async function imageToOgDataUri(sourcePath: string): Promise<string> {
  const buf = await sharp(readFileSync(sourcePath))
    .resize(1200, 630, { fit: "cover", position: "centre" })
    .jpeg({ quality: 85 })
    .toBuffer();
  return `data:image/jpeg;base64,${buf.toString("base64")}`;
}

// Colors
const BG = "#111111";
const FG = "#f5f5f3";
const ACCENT = "#e8587a";

function truncate(str: string, max: number): string {
  return str.length > max ? `${str.slice(0, max - 1)}…` : str;
}

export type ArticleOgProps = {
  title: string;
  description: string;
  tags?: string[];
};

export function buildArticleVNode(
  props: ArticleOgProps,
): Parameters<typeof satori>[0] {
  const title = truncate(props.title, 70);
  const description = truncate(props.description, 120);

  return {
    type: "div",
    props: {
      style: {
        display: "flex",
        flexDirection: "column",
        width: "1200px",
        height: "630px",
        backgroundColor: BG,
        color: FG,
        fontFamily: "Exo 2",
      },
      children: [
        // Top accent bar
        {
          type: "div",
          props: {
            style: {
              display: "flex",
              width: "1200px",
              height: "6px",
              backgroundColor: ACCENT,
            },
          },
        },
        // Content
        {
          type: "div",
          props: {
            style: {
              display: "flex",
              flexDirection: "column",
              flex: "1",
              paddingTop: "64px",
              paddingRight: "80px",
              paddingBottom: "48px",
              paddingLeft: "80px",
              justifyContent: "space-between",
            },
            children: [
              // Title + description
              {
                type: "div",
                props: {
                  style: { display: "flex", flexDirection: "column" },
                  children: [
                    {
                      type: "div",
                      props: {
                        style: {
                          display: "flex",
                          fontSize: "18px",
                          color: ACCENT,
                          letterSpacing: "2px",
                          marginBottom: "20px",
                          textTransform: "uppercase",
                        },
                        children: "Article",
                      },
                    },
                    {
                      type: "div",
                      props: {
                        style: {
                          display: "flex",
                          fontSize: "56px",
                          fontWeight: 700,
                          color: FG,
                          lineHeight: "1.1",
                          marginBottom: "20px",
                        },
                        children: title,
                      },
                    },
                    {
                      type: "div",
                      props: {
                        style: {
                          display: "flex",
                          fontSize: "24px",
                          color: "rgba(245,245,243,0.65)",
                          lineHeight: "1.4",
                        },
                        children: description,
                      },
                    },
                  ],
                },
              },
              // Footer
              {
                type: "div",
                props: {
                  style: {
                    display: "flex",
                    justifyContent: "flex-end",
                    borderTop: "1px solid #333333",
                    paddingTop: "20px",
                  },
                  children: [
                    {
                      type: "div",
                      props: {
                        style: {
                          display: "flex",
                          fontSize: "22px",
                          fontWeight: 700,
                          color: FG,
                        },
                        children: "Adrian Altner",
                      },
                    },
                  ],
                },
              },
            ],
          },
        },
      ],
    },
  };
}

export type CollectionOgProps = {
  title: string;
  description: string;
  location?: string | undefined;
  coverDataUri?: string | undefined;
};

export function buildCollectionVNode(
  props: CollectionOgProps,
): Parameters<typeof satori>[0] {
  const title = truncate(props.title, 60);
  const hasImage = !!props.coverDataUri;

  if (hasImage) {
    return {
      type: "div",
      props: {
        style: {
          display: "flex",
          width: "1200px",
          height: "630px",
          backgroundImage: `url(${props.coverDataUri})`,
          backgroundSize: "cover",
          backgroundPosition: "center",
          fontFamily: "Exo 2",
          position: "relative",
        },
        children: [
          // Gradient overlay (full card, darker at bottom)
          {
            type: "div",
            props: {
              style: {
                display: "flex",
                position: "absolute",
                top: "0px",
                left: "0px",
                width: "1200px",
                height: "630px",
                backgroundImage:
                  "linear-gradient(to top, rgba(0,0,0,0.92) 0%, rgba(0,0,0,0.4) 50%, rgba(0,0,0,0.1) 100%)",
              },
            },
          },
          // Top accent bar
          {
            type: "div",
            props: {
              style: {
                display: "flex",
                position: "absolute",
                top: "0px",
                left: "0px",
                width: "1200px",
                height: "6px",
                backgroundColor: ACCENT,
              },
            },
          },
          // Bottom content
          {
            type: "div",
            props: {
              style: {
                display: "flex",
                position: "absolute",
                bottom: "0px",
                left: "0px",
                right: "0px",
                paddingTop: "32px",
                paddingRight: "64px",
                paddingBottom: "48px",
                paddingLeft: "64px",
                flexDirection: "column",
              },
              children: [
                // Location label
                ...(props.location
                  ? [
                      {
                        type: "div",
                        props: {
                          style: {
                            display: "flex",
                            fontSize: "18px",
                            color: ACCENT,
                            letterSpacing: "2px",
                            textTransform: "uppercase",
                            marginBottom: "12px",
                          },
                          children: truncate(props.location, 50),
                        },
                      },
                    ]
                  : []),
                // Title
                {
                  type: "div",
                  props: {
                    style: {
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "flex-end",
                    },
                    children: [
                      {
                        type: "div",
                        props: {
                          style: {
                            display: "flex",
                            fontSize: "64px",
                            fontWeight: 700,
                            color: "#ffffff",
                            lineHeight: "1.05",
                          },
                          children: title,
                        },
                      },
                      {
                        type: "div",
                        props: {
                          style: {
                            display: "flex",
                            fontSize: "20px",
                            fontWeight: 700,
                            color: "rgba(255,255,255,0.7)",
                            letterSpacing: "1px",
                            paddingBottom: "8px",
                          },
                          children: "Adrian Altner",
                        },
                      },
                    ],
                  },
                },
              ],
            },
          },
        ],
      },
    };
  }

  // Text-only fallback (no cover photo)
  return {
    type: "div",
    props: {
      style: {
        display: "flex",
        flexDirection: "column",
        width: "1200px",
        height: "630px",
        backgroundColor: BG,
        color: FG,
        fontFamily: "Exo 2",
      },
      children: [
        {
          type: "div",
          props: {
            style: {
              display: "flex",
              width: "1200px",
              height: "6px",
              backgroundColor: ACCENT,
            },
          },
        },
        {
          type: "div",
          props: {
            style: {
              display: "flex",
              flexDirection: "column",
              flex: "1",
              paddingTop: "64px",
              paddingRight: "80px",
              paddingBottom: "48px",
              paddingLeft: "80px",
              justifyContent: "space-between",
            },
            children: [
              {
                type: "div",
                props: {
                  style: { display: "flex", flexDirection: "column" },
                  children: [
                    {
                      type: "div",
                      props: {
                        style: {
                          display: "flex",
                          fontSize: "18px",
                          color: ACCENT,
                          letterSpacing: "2px",
                          marginBottom: "20px",
                          textTransform: "uppercase",
                        },
                        children: "Collection",
                      },
                    },
                    {
                      type: "div",
                      props: {
                        style: {
                          display: "flex",
                          fontSize: "64px",
                          fontWeight: 700,
                          color: FG,
                        },
                        children: title,
                      },
                    },
                  ],
                },
              },
              {
                type: "div",
                props: {
                  style: {
                    display: "flex",
                    justifyContent: "flex-end",
                    borderTop: "1px solid #333333",
                    paddingTop: "20px",
                  },
                  children: [
                    {
                      type: "div",
                      props: {
                        style: {
                          display: "flex",
                          fontSize: "22px",
                          fontWeight: 700,
                          color: FG,
                        },
                        children: "Adrian Altner",
                      },
                    },
                  ],
                },
              },
            ],
          },
        },
      ],
    },
  };
}

export type NoteOgProps = {
  coverDataUri?: string | undefined;
};

export function buildNoteVNode(
  props: NoteOgProps,
): Parameters<typeof satori>[0] {
  if (props.coverDataUri) {
    return {
      type: "div",
      props: {
        style: {
          display: "flex",
          width: "1200px",
          height: "630px",
          backgroundImage: `url(${props.coverDataUri})`,
          backgroundSize: "cover",
          backgroundPosition: "center",
        },
      },
    };
  }

  return {
    type: "div",
    props: {
      style: {
        display: "flex",
        width: "1200px",
        height: "630px",
        backgroundColor: BG,
      },
    },
  };
}

export type PhotoOgProps = {
  title: string;
  alt: string;
  date: string;
  location?: string | undefined;
  photoDataUri: string;
};

export function buildPhotoVNode(
  props: PhotoOgProps,
): Parameters<typeof satori>[0] {
  const title = truncate(props.title, 70);
  const dateFormatted = new Date(props.date).toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });

  return {
    type: "div",
    props: {
      style: {
        display: "flex",
        width: "1200px",
        height: "630px",
        backgroundImage: `url(${props.photoDataUri})`,
        backgroundSize: "cover",
        fontFamily: "Exo 2",
        position: "relative",
      },
      children: [
        // Gradient overlay (darker at bottom for text legibility)
        {
          type: "div",
          props: {
            style: {
              display: "flex",
              position: "absolute",
              top: "0px",
              left: "0px",
              width: "1200px",
              height: "630px",
              backgroundImage:
                "linear-gradient(to top, rgba(0,0,0,0.88) 0%, rgba(0,0,0,0.3) 50%, rgba(0,0,0,0.05) 100%)",
            },
          },
        },
        // Bottom content
        {
          type: "div",
          props: {
            style: {
              display: "flex",
              position: "absolute",
              bottom: "0px",
              left: "0px",
              right: "0px",
              paddingTop: "32px",
              paddingRight: "64px",
              paddingBottom: "48px",
              paddingLeft: "64px",
              flexDirection: "column",
            },
            children: [
              // Title
              {
                type: "div",
                props: {
                  style: {
                    display: "flex",
                    fontSize: "52px",
                    fontWeight: 700,
                    color: "#ffffff",
                    lineHeight: "1.05",
                    marginBottom: "16px",
                  },
                  children: title,
                },
              },
              // Date left, site name right
              {
                type: "div",
                props: {
                  style: {
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "flex-end",
                  },
                  children: [
                    {
                      type: "div",
                      props: {
                        style: {
                          display: "flex",
                          fontSize: "18px",
                          color: "rgba(255,255,255,0.6)",
                        },
                        children: dateFormatted,
                      },
                    },
                    {
                      type: "div",
                      props: {
                        style: {
                          display: "flex",
                          fontSize: "20px",
                          fontWeight: 700,
                          color: "rgba(255,255,255,0.7)",
                          letterSpacing: "1px",
                        },
                        children: "Adrian Altner",
                      },
                    },
                  ],
                },
              },
            ],
          },
        },
      ],
    },
  };
}
