<script setup>
import { ref, onMounted } from "vue";
import { request } from "../api";
import { t, tSplit } from "../i18n";

// Superadmin-only: where the Web App lives (the address /api/status probes) and
// which browser origins CORS admits. Like the PocketBase card, the change is
// applied at runtime AND persisted to the server's .env, so it survives a
// restart. Origins are edited as a comma-separated list.
const cfg = ref(null);
const form = ref({ url: "", origins: "" });
const probe = ref(null);
const error = ref("");
const notice = ref("");
const busy = ref(false);

// The panel sends the origin list as an array; the field edits it as CSV.
const splitOrigins = (s) => s.split(",").map((o) => o.trim()).filter(Boolean);

function apply(view) {
  cfg.value = view;
  form.value = { url: view.url, origins: (view.allowOrigins || []).join(", ") };
  probe.value = view.probe;
}

async function load() {
  try {
    apply(await request("/api/admin/webapp-config"));
  } catch (e) {
    error.value = e.message;
  }
}
onMounted(load);

async function test() {
  error.value = "";
  notice.value = "";
  busy.value = true;
  try {
    probe.value = await request("/api/admin/webapp-config/test", {
      method: "POST",
      body: { url: form.value.url },
    });
    notice.value =
      probe.value.status === "ok"
        ? t("webapp.testOk")
        : t("webapp.testFailed");
  } catch (e) {
    error.value = e.message;
  } finally {
    busy.value = false;
  }
}

async function save() {
  error.value = "";
  notice.value = "";
  busy.value = true;
  try {
    const out = await request("/api/admin/webapp-config", {
      method: "PUT",
      body: { url: form.value.url, allowOrigins: splitOrigins(form.value.origins) },
    });
    apply(out.config);
    notice.value = out.warning || t("webapp.savedNotice");
  } catch (e) {
    error.value = e.message;
  } finally {
    busy.value = false;
  }
}
</script>

<template>
  <div class="dh-card overflow-hidden">
    <div class="flex items-center justify-between border-b border-subtle px-5 py-4">
      <div>
        <div class="text-base font-bold tracking-[-0.02em] text-strong">{{ t("webapp.title") }}</div>
        <p class="mt-0.5 text-xs text-muted">{{ t("webapp.subtitle") }}</p>
      </div>
      <span
        v-if="probe"
        class="dh-pill"
        :class="probe.status === 'ok' ? 'bg-success-soft text-success' : 'bg-danger-soft text-danger'"
      >
        <span class="h-1.5 w-1.5 rounded-full bg-current"></span>
        {{ probe.status === "ok" ? t("webapp.reachable") : t("webapp.unreachable") }}
      </span>
    </div>

    <div class="flex flex-col gap-4 px-5 py-4">
      <div>
        <label class="dh-label" for="web-url">{{ t("webapp.baseUrl") }}</label>
        <input id="web-url" v-model="form.url" class="dh-input" placeholder="http://localhost:8090" />
      </div>

      <div>
        <label class="dh-label" for="web-origins">{{ t("webapp.allowedOrigins") }}</label>
        <input
          id="web-origins"
          v-model="form.origins"
          class="dh-input"
          placeholder="http://localhost:8090, https://app.example.com"
        />
        <p class="mt-1 text-xs text-muted">
          {{ tSplit("webapp.originsHint", "star").before
          }}<span class="data">*</span>{{ tSplit("webapp.originsHint", "star").after }}
        </p>
      </div>

      <p v-if="probe?.error" class="data text-xs text-muted">{{ probe.error }}</p>
      <p v-if="notice" class="rounded-control bg-info-soft px-3 py-2 text-xs text-info">{{ notice }}</p>
      <p v-if="error" class="rounded-control bg-danger-soft px-3 py-2 text-xs text-danger">{{ error }}</p>

      <div class="flex items-center gap-2">
        <button class="dh-btn" :disabled="busy" @click="save">{{ t("webapp.saveApply") }}</button>
        <button class="dh-btn-ghost" :disabled="busy" @click="test">{{ t("webapp.testConnection") }}</button>
        <span class="flex-1"></span>
        <span class="eyebrow">{{ t("webapp.persistedEnv") }}</span>
      </div>
    </div>
  </div>
</template>
