import S from "node:fs";
import u from "node:path";
import { g as z, a as V, b as H, c as J, d as Q } from "../index-D2_J_-XS.js";
import { mkdir as X, writeFile as k, readFile as K } from "node:fs/promises";
import { createHash as Y } from "node:crypto";
const Z = "https://fonts.googleapis.com/css2", x = "normal", q = 400, D = "Mozilla/5.0 (compatible; BeatUI Tailwind Plugin; +https://tempots.com)";
async function ee(e) {
  const { projectRoot: s, requests: t, logger: r } = e;
  if (!t || t.length === 0)
    return null;
  const a = e.cacheDir ? u.resolve(e.cacheDir) : u.join(s, "node_modules", ".beatui", "google-fonts"), n = [], d = /* @__PURE__ */ new Map();
  await X(a, { recursive: !0 }).catch((g) => {
    r?.(`Unable to create BeatUI Google Fonts cache directory: ${g}`);
  });
  for (const g of t)
    try {
      const i = M(g), l = await te({
        request: g,
        cssUrl: i,
        cacheRoot: a,
        logger: r
      });
      if (!l)
        continue;
      const y = await ie({
        cssText: l,
        cacheRoot: a,
        assetMap: d,
        logger: r
      });
      n.push(y);
    } catch (i) {
      r?.(
        `Unexpected error while downloading Google Font "${g.family}": ${String(i)}`
      );
    }
  return n.length === 0 || d.size === 0 ? null : {
    cssText: n.join(`
`),
    assets: Array.from(d.values())
  };
}
async function te({
  request: e,
  cssUrl: s,
  cacheRoot: t,
  logger: r
}) {
  const a = u.join(t, se(e, s));
  try {
    const n = await fetch(s, {
      headers: {
        "User-Agent": D
      }
    });
    if (!n.ok)
      throw new Error(
        `Failed to download Google Font CSS: ${n.status} ${n.statusText}`
      );
    const d = await n.text();
    return await k(a, d), d;
  } catch (n) {
    if (S.existsSync(a))
      try {
        const d = await K(a, "utf8");
        return r?.(
          `Using cached Google Font CSS for ${e.family} because download failed.`
        ), d;
      } catch (d) {
        r?.(
          `Failed to read cached Google Font CSS for ${e.family}: ${d}`
        );
      }
    return r?.(
      `Unable to download Google Font CSS for ${e.family}: ${n}`
    ), null;
  }
}
function se(e, s) {
  const t = Y("sha1").update(s).digest("hex").slice(0, 10);
  return `${e.family.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-") || "font"}-${t}.css`;
}
function M(e) {
  const { family: s } = e, t = s.trim().replace(/\s+/g, " "), r = ne(e.weights), a = re(e.styles), n = new URLSearchParams();
  return n.append("family", ae(t, r, a)), e.display && n.append("display", e.display), e.subsets && e.subsets.length > 0 && n.append("subset", e.subsets.join(",")), e.text && n.append("text", e.text), `${Z}?${n.toString()}`;
}
function ne(e) {
  return !e || e.length === 0 ? [] : Array.from(new Set(e)).sort((s, t) => s - t);
}
function re(e) {
  if (!e || e.length === 0)
    return [x];
  const s = Array.from(new Set(e)), t = s.includes("italic"), r = s.includes("normal");
  return !t && !r && s.push(x), s.sort((a, n) => a === n ? 0 : a === "normal" ? -1 : 1);
}
function ae(e, s, t) {
  if (s.length === 0 && t.every((i) => i === "normal"))
    return e;
  const r = t.includes("italic"), a = t.includes("normal"), n = s.length > 0 ? s : [q];
  if (!r)
    return `${e}:wght@${n.join(";")}`;
  const d = /* @__PURE__ */ new Set();
  a && n.forEach((i) => {
    d.add(`0,${i}`);
  }), n.forEach((i) => {
    d.add(`1,${i}`);
  });
  const g = Array.from(d).sort((i, l) => {
    const [y, F] = i.split(",").map(Number), [T, v] = l.split(",").map(Number);
    return y - T || F - v;
  });
  return `${e}:ital,wght@${g.join(";")}`;
}
const oe = /url\(([^)]+)\)/g;
async function ie({
  cssText: e,
  cacheRoot: s,
  assetMap: t,
  logger: r
}) {
  let a = e;
  const n = /* @__PURE__ */ new Set();
  let d;
  for (; (d = oe.exec(e)) !== null; ) {
    const i = d[1].trim().replace(/^['"]|['"]$/g, "");
    i.startsWith("http") && n.add(i);
  }
  for (const g of n) {
    const i = await le(g, s, t, r);
    if (!i)
      continue;
    const l = g.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"), y = new RegExp(`url\\((['"])${l}\\1\\)`, "g"), F = new RegExp(`url\\(${l}\\)`, "g");
    a = a.replace(y, `url(${i.placeholder})`), a = a.replace(F, `url(${i.placeholder})`);
  }
  return a;
}
async function le(e, s, t, r) {
  const a = t.get(e);
  if (a)
    return a;
  let n;
  try {
    const l = new URL(e);
    n = u.basename(l.pathname);
  } catch (l) {
    return r?.(`Invalid Google Font URL skipped: ${e} (${l})`), null;
  }
  if (!n)
    return r?.(`Unable to derive file name for Google Font URL: ${e}`), null;
  const d = u.join(s, n), g = `__BEATUI_GOOGLE_FONT_${t.size}__`;
  if (!S.existsSync(d))
    try {
      const l = await fetch(e, {
        headers: {
          "User-Agent": D
        }
      });
      if (!l.ok)
        return r?.(
          `Failed to download Google Font asset ${n}: ${l.status} ${l.statusText}`
        ), null;
      const y = Buffer.from(await l.arrayBuffer());
      await k(d, y);
    } catch (l) {
      return r?.(
        `Unexpected error while downloading Google Font asset ${n}: ${String(l)}`
      ), null;
    }
  const i = {
    url: e,
    fileName: n,
    localPath: d,
    placeholder: g
  };
  return t.set(e, i), i;
}
function B(e) {
  const s = typeof e == "string" ? new URL(e) : e;
  if (s.protocol !== "file:")
    throw new TypeError(`Expected file URL, received: ${s.href}`);
  const t = s.hostname, r = t === "" || t === "localhost", a = decodeURIComponent(s.pathname);
  if (process.platform === "win32") {
    let n = a.replace(/\//g, "\\");
    return !r && t ? `\\\\${t}${n}` : (n.startsWith("\\") && (n = n.slice(1)), n);
  }
  return !r && t ? `//${t}${a}` : a;
}
const L = "@tempots/beatui/tailwind.css", b = "beatui.tailwind.css", w = u.dirname(B(import.meta.url)), O = ce(w) ?? w;
function j(e) {
  if (Object.keys(e).length === 0)
    return "";
  let s = `:root {
`;
  for (const [t, r] of Object.entries(e))
    s += `  ${t}: ${r};
`;
  return s += `}
`, s;
}
function ce(e) {
  let s = e;
  const t = u.parse(s).root;
  for (; s && s !== t; ) {
    const r = u.join(s, "package.json");
    if (S.existsSync(r))
      try {
        if (JSON.parse(S.readFileSync(r, "utf8"))?.name === "@tempots/beatui")
          return s;
      } catch {
      }
    s = u.dirname(s);
  }
  return null;
}
function ue(e) {
  if (e == null)
    return null;
  const s = typeof e == "string" ? e : e.id;
  if (!s)
    return null;
  const [t] = s.split("?");
  return t.startsWith("virtual:") || t.startsWith("\0") ? null : t.startsWith("/@fs/") ? decodeURIComponent(t.slice(4)) : t.startsWith("file://") ? B(t) : u.isAbsolute(t) ? t : null;
}
function de(e) {
  const s = /* @__PURE__ */ new Set([
    u.resolve(w, b),
    u.resolve(w, "../", b),
    u.resolve(w, "../../", b),
    u.resolve(w, "tailwind.css"),
    u.resolve(w, "../tailwind.css"),
    u.resolve(w, "../../tailwind.css"),
    u.resolve(w, "../styles/tailwind.css"),
    u.resolve(w, "../../styles/tailwind.css"),
    u.resolve(O, "dist", b),
    u.resolve(O, b),
    u.resolve(O, "tailwind.css"),
    u.resolve(O, "src/styles/tailwind.css"),
    u.resolve(e, "node_modules/@tempots/beatui/tailwind.css")
  ]);
  for (const t of s)
    if (S.existsSync(t))
      return t;
  return null;
}
function fe(e) {
  return e ? Array.isArray(e) ? e : [e] : [];
}
function he(e, s) {
  let t = e;
  for (const [r, a] of s)
    t = t.split(r).join(a);
  return t;
}
async function me(e, s) {
  if (e == null || typeof e != "object")
    return null;
  const t = e.resolve;
  if (!t)
    return null;
  try {
    return await t.call(e, s, void 0, { skipSelf: !0 });
  } catch {
    return null;
  }
}
function Se(e = {}) {
  let s = process.cwd();
  const t = e.injectCss !== !1, r = e.rtlAttribute ?? "dir", a = e.rtlValue ?? "rtl";
  let n = "/";
  const g = e.semanticColors != null || e.semanticFonts != null || e.semanticRadii != null || e.semanticShadows != null || e.semanticMotion != null || e.semanticSpacing != null || e.semanticTextShadows != null ? j(
    z({
      colors: e.semanticColors,
      fonts: e.semanticFonts,
      radii: e.semanticRadii,
      shadows: e.semanticShadows,
      motion: e.semanticMotion,
      spacing: e.semanticSpacing,
      textShadows: e.semanticTextShadows
    })
  ) : "", i = e.fontFamilies ? j(
    V(e.fontFamilies)
  ) : "", l = {};
  e.baseSpacing && (l[H("base")] = e.baseSpacing), e.baseFontSize && (l[J()] = e.baseFontSize), e.baseMotionDuration && (l[Q("base")] = e.baseMotionDuration);
  const y = j(l), F = fe(e.googleFonts);
  let T = "", v = [];
  const A = /* @__PURE__ */ new Map(), R = /* @__PURE__ */ new Map(), P = /* @__PURE__ */ new Map(), W = "/@beatui/google-fonts", E = [];
  let G = null, C = null, _ = !1;
  const I = (h) => {
    const f = [
      y,
      g,
      i
    ];
    return T && (h === "dev" ? f.push(
      he(T, A)
    ) : f.push(T)), f.filter((o) => o && o.length > 0).join(`
`);
  };
  return {
    name: "beatui-tailwind",
    enforce: "pre",
    async configResolved(h) {
      if (s = h.root, _ = h.command === "build", n = h.base && h.base !== "/" ? h.base.endsWith("/") ? h.base : `${h.base}/` : "/", t) {
        const o = await me(
          this,
          L
        );
        C = ue(o) ?? de(s);
      }
      const f = (o) => {
        this && typeof this.warn == "function" ? this.warn(o) : h.logger.warn(o);
      };
      if (F.length > 0) {
        const o = Array.from(
          // eslint-disable-next-line tempots/require-async-signal-disposal -- This is an array, not a Signal
          new Set(F.map(M))
        ), c = await ee({
          projectRoot: s,
          requests: F,
          logger: (m) => f(`[BeatUI] ${m}`)
        });
        if (T = c?.cssText ?? "", v = c?.assets ?? [], A.clear(), R.clear(), P.clear(), E.length = 0, v.length > 0)
          for (const m of v) {
            const p = `${W}/${m.fileName}`;
            A.set(m.placeholder, p), P.set(p, m.localPath);
          }
        else
          E.push(...o);
      } else
        E.length = 0;
      t && !C && f(
        "[BeatUI] Unable to resolve @tempots/beatui/tailwind.css. CSS will not be auto-injected."
      );
    },
    configureServer(h) {
      !t || C == null || (h.middlewares.use((f, o, c) => {
        const m = f.method ?? "GET";
        if (!["GET", "HEAD"].includes(m)) {
          c();
          return;
        }
        const p = (f.url ?? "").split("?")[0];
        if (!new Set(
          [
            `/${b}`,
            n === "/" ? null : `${n}${b}`
          ].filter(($) => !!$)
        ).has(p)) {
          c();
          return;
        }
        o.setHeader("Content-Type", "text/css");
        try {
          let $ = S.readFileSync(C, "utf8");
          const N = I("dev");
          N && ($ += `
${N}`), o.end($);
        } catch ($) {
          h.config.logger.error(
            `[BeatUI] Failed to stream ${L}: ${String($)}`
          ), o.statusCode = 500, o.end();
        }
      }), P.size > 0 && h.middlewares.use((f, o, c) => {
        const m = f.method ?? "GET";
        if (!["GET", "HEAD"].includes(m)) {
          c();
          return;
        }
        const p = (f.url ?? "").split("?")[0], U = p ? P.get(p) : void 0;
        if (!U) {
          c();
          return;
        }
        o.setHeader("Content-Type", "font/woff2"), S.createReadStream(U).on("error", () => {
          o.statusCode = 500, o.end();
        }).pipe(o);
      }));
    },
    buildStart() {
      if (!_ || !t || C == null) return;
      R.clear(), G = null;
      const h = C;
      let f = S.readFileSync(h, "utf8");
      const o = I("raw");
      if (o && (f += `
${o}`), G = this.emitFile({
        type: "asset",
        fileName: b,
        source: f
      }), v.length > 0)
        for (const c of v)
          try {
            const m = S.readFileSync(c.localPath), p = this.emitFile({
              type: "asset",
              name: `assets/${c.fileName}`,
              source: m
            });
            R.set(c.placeholder, p);
          } catch (m) {
            this.warn(
              `[BeatUI] Failed to include Google Font asset ${c.fileName}: ${String(
                m
              )}`
            );
          }
    },
    generateBundle(h, f) {
      if (!_ || !G)
        return;
      const o = this.getFileName(G), c = f[o];
      if (!c || c.type !== "asset" || typeof c.source != "string")
        return;
      let m = c.source;
      for (const [p, U] of R) {
        const $ = this.getFileName(U);
        m = m.split(p).join($);
      }
      c.source = m;
    },
    transformIndexHtml(h) {
      const f = [];
      if (t && C) {
        const c = n === "/" ? `/${b}` : `${n}${b}`;
        f.push({
          tag: "link",
          attrs: {
            rel: "stylesheet",
            href: c
          },
          injectTo: "head-prepend"
        });
      }
      E.length > 0 && f.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"
        },
        ...E.map((c) => ({
          tag: "link",
          attrs: {
            rel: "stylesheet",
            href: c,
            "data-beatui-google-font": ""
          },
          injectTo: "head"
        }))
      );
      const o = `
        (() => {
          const apply = () => {
            const root = document.documentElement
            const target = document.body
            if (!target) return
            const dirValue = root.getAttribute('${r.replace(/'/g, "\\'")}')
            const isRtl = dirValue === '${a.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: ['${r.replace(/'/g, "\\'")}'],
          })
        })();
      `;
      return f.push({
        tag: "script",
        attrs: { type: "module" },
        children: o,
        injectTo: "body"
      }), { html: h, tags: f };
    }
  };
}
export {
  Se as beatuiTailwindPlugin,
  Se as default
};
