/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/
use std::borrow::Cow;

#[cfg(not(feature = "reload"))]
pub fn js_bundle() -> Cow<'static, str> {
    include_str!(concat!(env!("OUT_DIR"), "/bundle.js")).into()
}
#[cfg(not(feature = "reload"))]
pub fn js_bundle_map() -> Cow<'static, str> {
    include_str!(concat!(env!("OUT_DIR"), "/bundle.js.map")).into()
}

#[cfg(feature = "reload")]
pub fn js_bundle() -> Cow<'static, str> {
    use std::process::{Command, Stdio};

    let proc = Command::new("esbuild")
        .arg("ui/client-scripts/src/main.ts")
        .arg("--bundle")
        .arg("--target=esnext")
        .arg("--sourcemap")
        .arg("--format=esm")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();

    let output = proc.wait_with_output().unwrap();

    Cow::Owned(if output.status.success() {
        String::from_utf8(output.stdout).unwrap()
    } else {
        format!(
            "console.error({:?})",
            String::from_utf8(output.stderr).unwrap()
        )
    })
}

#[cfg(feature = "reload")]
pub fn js_bundle_map() -> Cow<'static, str> {
    Cow::Borrowed("")
}
