import y from "node:fs";
import c from "node:path";
import { createRequire as Z } from "node:module";
import { pathToFileURL as q } from "node:url";
import { g as ee, a as te, c as se } from "../index-C_a29dA7.js";
import { mkdir as ne, writeFile as V, readFile as ae } from "node:fs/promises";
import { createHash as oe } from "node:crypto";
const re = "https://fonts.googleapis.com/css2", B = "normal", ie = 400, J = "Mozilla/5.0 (compatible; BeatUI Tailwind Plugin; +https://tempots.com)";
async function le(e) {
  const { projectRoot: t, requests: s, logger: n } = e;
  if (!s || s.length === 0)
    return null;
  const o = e.cacheDir ? c.resolve(e.cacheDir) : c.join(t, "node_modules", ".beatui", "google-fonts"), a = [], u = /* @__PURE__ */ new Map();
  await ne(o, { recursive: !0 }).catch((m) => {
    n?.(`Unable to create BeatUI Google Fonts cache directory: ${m}`);
  });
  for (const m of s)
    try {
      const d = Q(m), h = await ce({
        request: m,
        cssUrl: d,
        cacheRoot: o,
        logger: n
      });
      if (!h)
        continue;
      const T = await ge({
        cssText: h,
        cacheRoot: o,
        assetMap: u,
        logger: n
      });
      a.push(T);
    } catch (d) {
      n?.(
        `Unexpected error while downloading Google Font "${m.family}": ${String(d)}`
      );
    }
  return a.length === 0 || u.size === 0 ? null : {
    cssText: a.join(`
`),
    assets: Array.from(u.values())
  };
}
async function ce({
  request: e,
  cssUrl: t,
  cacheRoot: s,
  logger: n
}) {
  const o = c.join(s, ue(e, t));
  try {
    const a = await fetch(t, {
      headers: {
        "User-Agent": J
      }
    });
    if (!a.ok)
      throw new Error(
        `Failed to download Google Font CSS: ${a.status} ${a.statusText}`
      );
    const u = await a.text();
    return await V(o, u), u;
  } catch (a) {
    if (y.existsSync(o))
      try {
        const u = await ae(o, "utf8");
        return n?.(
          `Using cached Google Font CSS for ${e.family} because download failed.`
        ), u;
      } catch (u) {
        n?.(
          `Failed to read cached Google Font CSS for ${e.family}: ${u}`
        );
      }
    return n?.(
      `Unable to download Google Font CSS for ${e.family}: ${a}`
    ), null;
  }
}
function ue(e, t) {
  const s = oe("sha1").update(t).digest("hex").slice(0, 10);
  return `${e.family.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-") || "font"}-${s}.css`;
}
function Q(e) {
  const { family: t } = e, s = t.trim().replace(/\s+/g, " "), n = de(e.weights), o = fe(e.styles), a = new URLSearchParams();
  return a.append("family", me(s, n, o)), e.display && a.append("display", e.display), e.subsets && e.subsets.length > 0 && a.append("subset", e.subsets.join(",")), e.text && a.append("text", e.text), `${re}?${a.toString()}`;
}
function de(e) {
  return !e || e.length === 0 ? [] : Array.from(new Set(e)).sort((t, s) => t - s);
}
function fe(e) {
  if (!e || e.length === 0)
    return [B];
  const t = Array.from(new Set(e)), s = t.includes("italic"), n = t.includes("normal");
  return !s && !n && t.push(B), t.sort((o, a) => o === a ? 0 : o === "normal" ? -1 : 1);
}
function me(e, t, s) {
  if (t.length === 0 && s.every((d) => d === "normal"))
    return e;
  const n = s.includes("italic"), o = s.includes("normal"), a = t.length > 0 ? t : [ie];
  if (!n)
    return `${e}:wght@${a.join(";")}`;
  const u = /* @__PURE__ */ new Set();
  o && a.forEach((d) => {
    u.add(`0,${d}`);
  }), a.forEach((d) => {
    u.add(`1,${d}`);
  });
  const m = Array.from(u).sort((d, h) => {
    const [T, E] = d.split(",").map(Number), [R, U] = h.split(",").map(Number);
    return T - R || E - U;
  });
  return `${e}:ital,wght@${m.join(";")}`;
}
const he = /url\(([^)]+)\)/g;
async function ge({
  cssText: e,
  cacheRoot: t,
  assetMap: s,
  logger: n
}) {
  let o = e;
  const a = /* @__PURE__ */ new Set();
  let u;
  for (; (u = he.exec(e)) !== null; ) {
    const d = u[1].trim().replace(/^['"]|['"]$/g, "");
    d.startsWith("http") && a.add(d);
  }
  for (const m of a) {
    const d = await pe(m, t, s, n);
    if (!d)
      continue;
    const h = m.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"), T = new RegExp(`url\\((['"])${h}\\1\\)`, "g"), E = new RegExp(`url\\(${h}\\)`, "g");
    o = o.replace(T, `url(${d.placeholder})`), o = o.replace(E, `url(${d.placeholder})`);
  }
  return o;
}
async function pe(e, t, s, n) {
  const o = s.get(e);
  if (o)
    return o;
  let a;
  try {
    const h = new URL(e);
    a = c.basename(h.pathname);
  } catch (h) {
    return n?.(`Invalid Google Font URL skipped: ${e} (${h})`), null;
  }
  if (!a)
    return n?.(`Unable to derive file name for Google Font URL: ${e}`), null;
  const u = c.join(t, a), m = `__BEATUI_GOOGLE_FONT_${s.size}__`;
  if (!y.existsSync(u))
    try {
      const h = await fetch(e, {
        headers: {
          "User-Agent": J
        }
      });
      if (!h.ok)
        return n?.(
          `Failed to download Google Font asset ${a}: ${h.status} ${h.statusText}`
        ), null;
      const T = Buffer.from(await h.arrayBuffer());
      await V(u, T);
    } catch (h) {
      return n?.(
        `Unexpected error while downloading Google Font asset ${a}: ${String(h)}`
      ), null;
    }
  const d = {
    url: e,
    fileName: a,
    localPath: u,
    placeholder: m
  };
  return s.set(e, d), d;
}
function X(e) {
  const t = typeof e == "string" ? new URL(e) : e;
  if (t.protocol !== "file:")
    throw new TypeError(`Expected file URL, received: ${t.href}`);
  const s = t.hostname, n = s === "" || s === "localhost", o = decodeURIComponent(t.pathname);
  if (process.platform === "win32") {
    let a = o.replace(/\//g, "\\");
    return !n && s ? `\\\\${s}${a}` : (a.startsWith("\\") && (a = a.slice(1)), a);
  }
  return !n && s ? `//${s}${o}` : o;
}
function we(e) {
  return typeof e == "object" && e !== null;
}
function ye(e) {
  if (typeof e == "string")
    return e;
  if (typeof e == "function")
    return e.name;
  if (we(e)) {
    const t = e.name;
    if (typeof t == "string")
      return t;
    const s = e.postcssPlugin;
    if (typeof s == "string")
      return s;
  }
}
const D = "@tempots/beatui/tailwind.css", $ = "beatui.tailwind.css", b = c.dirname(X(import.meta.url)), L = Se(b) ?? b;
function M(e) {
  if (Object.keys(e).length === 0)
    return "";
  let t = `:root {
`;
  for (const [s, n] of Object.entries(e))
    t += `  ${s}: ${n};
`;
  return t += `}
`, t;
}
const W = [
  "tailwind.config.ts",
  "tailwind.config.js",
  "tailwind.config.mjs",
  "tailwind.config.cjs",
  "tailwind.config.mts",
  "tailwind.config.cts"
];
function Se(e) {
  let t = e;
  const s = c.parse(t).root;
  for (; t && t !== s; ) {
    const n = c.join(t, "package.json");
    if (y.existsSync(n))
      try {
        if (JSON.parse(y.readFileSync(n, "utf8"))?.name === "@tempots/beatui")
          return t;
      } catch {
      }
    t = c.dirname(t);
  }
  return null;
}
const z = /* @__PURE__ */ new Map();
function Fe(e) {
  const t = c.resolve(e), s = z.get(t);
  if (s) return s;
  const n = c.join(t, "package.json"), o = Z(
    y.existsSync(n) ? n : t
  );
  return z.set(t, o), o;
}
async function H(e, t) {
  const n = Fe(t).resolve(e);
  return await import(q(n).href);
}
function _(e, t) {
  const s = t ? [t, ...W] : W;
  for (const n of s) {
    const o = c.resolve(e, n);
    if (y.existsSync(o))
      return o;
  }
  return null;
}
function be(e) {
  if (e == null)
    return null;
  const t = typeof e == "string" ? e : e.id;
  if (!t)
    return null;
  const [s] = t.split("?");
  return s.startsWith("virtual:") || s.startsWith("\0") ? null : s.startsWith("/@fs/") ? decodeURIComponent(s.slice(4)) : s.startsWith("file://") ? X(s) : c.isAbsolute(s) ? s : null;
}
function $e(e) {
  const t = /* @__PURE__ */ new Set([
    c.resolve(b, $),
    c.resolve(b, "../", $),
    c.resolve(b, "../../", $),
    c.resolve(b, "tailwind.css"),
    c.resolve(b, "../tailwind.css"),
    c.resolve(b, "../../tailwind.css"),
    c.resolve(b, "../styles/tailwind.css"),
    c.resolve(b, "../../styles/tailwind.css"),
    c.resolve(L, "dist", $),
    c.resolve(L, $),
    c.resolve(L, "tailwind.css"),
    c.resolve(L, "src/styles/tailwind.css"),
    c.resolve(e, "node_modules/@tempots/beatui/tailwind.css")
  ]);
  for (const s of t)
    if (y.existsSync(s))
      return s;
  return null;
}
function Te(e) {
  return e ? Array.isArray(e) ? e : [e] : [];
}
function Ce(e, t) {
  let s = e;
  for (const [n, o] of t)
    s = s.split(n).join(o);
  return s;
}
async function ve(e, t) {
  const s = e.resolve;
  if (!s)
    return null;
  try {
    return await s.call(e, t, void 0, { skipSelf: !0 });
  } catch {
    return null;
  }
}
function Le(e = {}) {
  let t = process.cwd(), s = _(t, e.tailwindConfigPath) ?? null;
  const n = e.injectCss !== !1, o = e.darkClass ?? "dark", a = e.rtlAttribute ?? "dir", u = e.rtlValue ?? "rtl";
  let m = "/";
  const d = {
    semanticColors: e.semanticColors,
    semanticFonts: e.semanticFonts,
    semanticRadii: e.semanticRadii,
    semanticShadows: e.semanticShadows,
    semanticMotion: e.semanticMotion,
    semanticSpacing: e.semanticSpacing,
    semanticTextShadows: e.semanticTextShadows,
    fontFamilies: e.fontFamilies,
    includeCoreTokens: e.includeCoreTokens,
    includeSemanticTokens: e.includeSemanticTokens,
    extendTheme: e.extendTheme
  }, T = e.semanticColors != null || e.semanticFonts != null || e.semanticRadii != null || e.semanticShadows != null || e.semanticMotion != null || e.semanticSpacing != null || e.semanticTextShadows != null ? M(
    ee({
      colors: e.semanticColors,
      fonts: e.semanticFonts,
      radii: e.semanticRadii,
      shadows: e.semanticShadows,
      motion: e.semanticMotion,
      spacing: e.semanticSpacing,
      textShadows: e.semanticTextShadows
    })
  ) : "", E = e.fontFamilies ? M(
    te(e.fontFamilies)
  ) : "", R = Te(e.googleFonts);
  let U = "", j = [];
  const N = /* @__PURE__ */ new Map(), x = /* @__PURE__ */ new Map(), A = /* @__PURE__ */ new Map(), K = "/@beatui/google-fonts", I = [];
  let k = null, P = null, O = !1;
  const G = (f) => {
    const i = [T, E];
    return U && (f === "dev" ? i.push(
      Ce(U, N)
    ) : i.push(U)), i.filter((l) => l && l.length > 0).join(`
`);
  };
  return {
    name: "beatui-tailwind",
    enforce: "pre",
    async configResolved(f) {
      if (t = f.root, O = f.command === "build", s = _(t, e.tailwindConfigPath) ?? s, m = f.base && f.base !== "/" ? f.base.endsWith("/") ? f.base : `${f.base}/` : "/", n) {
        const i = await ve(
          this,
          D
        );
        P = be(i) ?? $e(t);
      }
      if (R.length > 0) {
        const i = Array.from(
          new Set(R.map(Q))
        ), l = await le({
          projectRoot: t,
          requests: R,
          logger: (r) => this.warn(`[BeatUI] ${r}`)
        });
        if (U = l?.cssText ?? "", j = l?.assets ?? [], N.clear(), x.clear(), A.clear(), I.length = 0, j.length > 0)
          for (const r of j) {
            const g = `${K}/${r.fileName}`;
            N.set(r.placeholder, g), A.set(g, r.localPath);
          }
        else
          I.push(...i);
      } else
        I.length = 0;
      s || this.warn(
        "[BeatUI] Tailwind config file not found. BeatUI preset will not be auto-registered. Specify tailwindConfigPath if your config lives elsewhere."
      ), n && !P && this.warn(
        "[BeatUI] Unable to resolve @tempots/beatui/tailwind.css. CSS will not be auto-injected."
      );
    },
    configureServer(f) {
      !n || P == null || (f.middlewares.use((i, l, r) => {
        const g = i.method ?? "GET";
        if (!["GET", "HEAD"].includes(g)) {
          r();
          return;
        }
        const w = (i.url ?? "").split("?")[0];
        if (!new Set(
          [
            `/${$}`,
            m === "/" ? null : `${m}${$}`
          ].filter((p) => !!p)
        ).has(w)) {
          r();
          return;
        }
        l.setHeader("Content-Type", "text/css");
        try {
          let p = y.readFileSync(P, "utf8");
          const C = G("dev");
          C && (p += `
${C}`), l.end(p);
        } catch (p) {
          f.config.logger.error(
            `[BeatUI] Failed to stream ${D}: ${String(p)}`
          ), l.statusCode = 500, l.end();
        }
      }), A.size > 0 && f.middlewares.use((i, l, r) => {
        const g = i.method ?? "GET";
        if (!["GET", "HEAD"].includes(g)) {
          r();
          return;
        }
        const w = (i.url ?? "").split("?")[0], S = w ? A.get(w) : void 0;
        if (!S) {
          r();
          return;
        }
        l.setHeader("Content-Type", "font/woff2"), y.createReadStream(S).on("error", () => {
          l.statusCode = 500, l.end();
        }).pipe(l);
      }));
    },
    buildStart() {
      if (!O || !n || P == null) return;
      x.clear(), k = null;
      const f = P;
      let i = y.readFileSync(f, "utf8");
      const l = G("raw");
      if (l && (i += `
${l}`), k = this.emitFile({
        type: "asset",
        fileName: $,
        source: i
      }), j.length > 0)
        for (const r of j)
          try {
            const g = y.readFileSync(r.localPath), w = this.emitFile({
              type: "asset",
              name: `assets/${r.fileName}`,
              source: g
            });
            x.set(r.placeholder, w);
          } catch (g) {
            this.warn(
              `[BeatUI] Failed to include Google Font asset ${r.fileName}: ${String(
                g
              )}`
            );
          }
    },
    async config(f) {
      const i = se(d), l = f.css, r = {};
      typeof l == "object" && l !== null && Object.assign(r, l);
      const g = r.postcss;
      let w = {};
      typeof g == "object" && g !== null && (w = { ...g });
      const S = w.plugins;
      let p = [];
      Array.isArray(S) ? p = [...S] : S && (p = [S]), s || (s = _(t, e.tailwindConfigPath) ?? null);
      let C;
      try {
        const F = await H(
          "@tailwindcss/postcss",
          t
        );
        C = F.default ?? F;
      } catch {
      }
      if (typeof C != "function")
        try {
          const F = await H(
            "tailwindcss",
            t
          );
          C = F.default ?? F;
        } catch (F) {
          const v = F instanceof Error && F.message ? ` (${F.message})` : "";
          this.warn(
            `[BeatUI] Unable to load Tailwind CSS automatically. Install \`@tailwindcss/postcss\` (Tailwind v4) or \`tailwindcss\` (legacy) in your project.${v}`
          );
        }
      if (typeof C == "function") {
        if (!p.some(
          (v) => ye(v) === "tailwindcss"
        ))
          try {
            const v = C({
              config: s ?? {
                presets: [i]
              }
            });
            p.push(v);
          } catch (v) {
            const Y = v instanceof Error && v.message ? ` (${v.message})` : "";
            this.warn(
              `[BeatUI] Failed to initialize Tailwind automatically. Install \`@tailwindcss/postcss\` (Tailwind v4) or register Tailwind manually.${Y}`
            );
          }
      } else C != null && this.warn(
        "[BeatUI] Unable to load Tailwind CSS automatically. Received unexpected module shape."
      );
      return {
        define: {
          "import.meta.env.BEATUI_TAILWIND_PRESET": JSON.stringify(i)
        },
        css: {
          ...r,
          postcss: {
            ...w,
            plugins: p
          }
        }
      };
    },
    generateBundle(f, i) {
      if (!O || !k)
        return;
      const l = this.getFileName(k), r = i[l];
      if (!r || r.type !== "asset" || typeof r.source != "string")
        return;
      let g = r.source;
      for (const [w, S] of x) {
        const p = this.getFileName(S);
        g = g.split(w).join(p);
      }
      r.source = g;
    },
    transformIndexHtml(f) {
      const i = [];
      if (n && P) {
        const r = m === "/" ? `/${$}` : `${m}${$}`;
        i.push({
          tag: "link",
          attrs: {
            rel: "stylesheet",
            href: r
          },
          injectTo: "head-prepend"
        });
      }
      I.length > 0 && i.push(
        {
          tag: "link",
          attrs: {
            rel: "preconnect",
            href: "https://fonts.googleapis.com"
          },
          injectTo: "head"
        },
        {
          tag: "link",
          attrs: {
            rel: "preconnect",
            href: "https://fonts.gstatic.com",
            crossorigin: ""
          },
          injectTo: "head"
        },
        ...I.map((r) => ({
          tag: "link",
          attrs: {
            rel: "stylesheet",
            href: r,
            "data-beatui-google-font": ""
          },
          injectTo: "head"
        }))
      );
      const l = `
        (() => {
          const apply = () => {
            const root = document.documentElement
            const target = document.body
            if (!target) return
            const hasDark = root.classList.contains('${o.replace(/'/g, "\\'")}')
            target.classList.toggle('b-dark', hasDark)
            target.classList.toggle('b-light', !hasDark)
            const dirValue = root.getAttribute('${a.replace(/'/g, "\\'")}')
            const isRtl = dirValue === '${u.replace(/'/g, "\\'")}'
            target.classList.toggle('b-rtl', isRtl)
            target.classList.toggle('b-ltr', !isRtl)
          }
          if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', apply, { once: true })
          } else {
            apply()
          }
          const observer = new MutationObserver(apply)
          observer.observe(document.documentElement, {
            attributes: true,
            attributeFilter: ['class', '${a.replace(/'/g, "\\'")}'],
          })
        })();
      `;
      return i.push({
        tag: "script",
        attrs: { type: "module" },
        children: l,
        injectTo: "body"
      }), { html: f, tags: i };
    }
  };
}
export {
  Le as beatuiTailwindPlugin,
  Le as default
};
