import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"

import { cn } from "@/lib/utils"

const typographyVariants = cva("", {
  variants: {
    variant: {
      h1: "font-arabic text-[22px] leading-[32px] font-bold",
      h2: "font-arabic text-[18px] leading-[28px] font-semibold",
      h3: "font-arabic text-[16px] leading-[24px] font-medium",
      body: "font-arabic text-[14px] leading-[22px] font-normal",
      caption: "font-arabic text-[12px] leading-[18px] font-normal",
      button: "font-arabic text-[15px] leading-[22.5px] font-normal tracking-normal text-center",
      price: "font-numeric text-[18px] leading-[26px] font-semibold",
      number: "font-numeric text-[14px] leading-[22px] font-normal",
    },
    color: {
      main: "text-main-text",
      secondary: "text-secondary-text",
      inherit: "",
    },
  },
  defaultVariants: {
    variant: "body",
    color: "main",
  },
})

const defaultElements = {
  h1: "h1",
  h2: "h2",
  h3: "h3",
  body: "p",
  caption: "span",
  button: "span",
  price: "span",
  number: "span",
} as const

// Prices and figures always render LTR (Inter digits), even inside an RTL page —
// bidi reordering alone doesn't keep compound content like "90 SAR" stable.
const forcedLtrVariants = new Set<TypographyVariant>(["price", "number"])

type TypographyVariant = NonNullable<VariantProps<typeof typographyVariants>["variant"]>

type TypographyProps<T extends React.ElementType> = {
  as?: T
  variant?: TypographyVariant
} & VariantProps<typeof typographyVariants> &
  Omit<React.ComponentPropsWithoutRef<T>, "as" | "color" | "variant">

function Typography<T extends React.ElementType = "p">({
  as,
  variant = "body",
  color = "main",
  className,
  dir,
  ...props
}: TypographyProps<T>) {
  const Comp = as || defaultElements[variant] || "p"
  const resolvedDir = dir ?? (forcedLtrVariants.has(variant) ? "ltr" : undefined)

  return (
    <Comp
      data-slot="typography"
      dir={resolvedDir}
      className={cn(typographyVariants({ variant, color, className }))}
      {...props}
    />
  )
}

export { Typography, typographyVariants }
