<script setup>
import BaseButton from "../../components/base/BaseButton.vue";
import { useBaseToast } from "../../composables/useBaseToast.js";
import { ref } from "vue";
import {
  appBranding,
  defaultBrandingUrls,
  deleteBrandingSlot,
  mergeAppSettingsPayload,
  postBrandingUpload,
} from "../../composables/useAppSettings";
import { apiErrorDetail } from "../../services/api";

const toast = useBaseToast();

const uploading = ref(null);

const slots = [
  {
    key: "sidebar",
    title: "Sidebar logo",
    hint: "White / high-contrast lockup for colored sidebar backgrounds.",
  },
  {
    key: "header",
    title: "Header logo",
    hint: "Full-color lockup for light toolbars and login screens.",
  },
  {
    key: "compact",
    title: "Compact mark",
    hint: "Icon-style mark when the sidebar is collapsed.",
  },
  {
    key: "favicon",
    title: "Favicon",
    hint: "Browser tab icon (PNG, ICO, or SVG recommended).",
  },
  {
    key: "loginHero",
    title: "Login hero image",
    hint:
      "Large illustration on the login screen’s right panel (matches the Sakai / Top-Level-Punt-style layout).",
    largePreview: true,
  },
];

async function onPickFile(slot, event) {
  const input = event.target;
  const file = input.files?.[0];
  input.value = "";
  if (!file) {
    return;
  }

  uploading.value = slot;
  try {
    const fd = new FormData();
    fd.append("slot", slot);
    fd.append("file", file);
    const { data } = await postBrandingUpload(fd);
    mergeAppSettingsPayload(data);
    toast.add({
      severity: "success",
      summary: "Uploaded",
      detail: `${slot} branding updated.`,
      life: 3000,
    });
  } catch (error) {
    toast.add({
      severity: "error",
      summary: "Upload failed",
      detail: apiErrorDetail(error),
      life: 6500,
    });
  } finally {
    uploading.value = null;
  }
}

function triggerPick(slot) {
  document.getElementById(`brand-upload-${slot}`)?.click();
}

async function clearSlot(slot) {
  uploading.value = slot;
  try {
    await deleteBrandingSlot(slot);
    toast.add({
      severity: "success",
      summary: "Reset",
      detail: `${slot} restored to Core default.`,
      life: 3000,
    });
  } catch (error) {
    toast.add({
      severity: "error",
      summary: "Could not reset",
      detail: apiErrorDetail(error),
      life: 6500,
    });
  } finally {
    uploading.value = null;
  }
}

function previewUrl(slot) {
  return appBranding[slot] ?? defaultBrandingUrls[slot];
}
</script>

<template>
  <div class="flex flex-col gap-6">
    <div>
      <h2 class="title-h6 text-surface-900 dark:text-surface-0 mb-1">
        Branding
      </h2>
      <p class="body-small text-surface-600 dark:text-surface-400">
        Defaults ship Build2Connect assets from Core. Upload overrides here for
        the whole application (stored per instance).
      </p>
    </div>

    <div class="flex flex-col gap-8">
      <section
        v-for="item in slots"
        :key="item.key"
        class="border border-surface-200 dark:border-surface-700 rounded-lg p-4 flex flex-col gap-3 sm:flex-row sm:items-start"
      >
        <div
          class="flex-shrink-0 flex items-center justify-center bg-surface-100 dark:bg-surface-900 rounded-md p-4"
          :class="
            item.largePreview
              ? 'min-h-[12rem] min-w-[14rem]'
              : 'min-h-[5rem] min-w-[8rem]'
          "
        >
          <img
            :src="previewUrl(item.key)"
            :alt="item.title"
            :class="
              item.largePreview
                ? 'max-h-48 max-w-[16rem] w-full object-contain'
                : 'max-h-14 max-w-[7rem] object-contain'
            "
          />
        </div>
        <div class="flex-1 min-w-0 flex flex-col gap-2">
          <div>
            <span class="font-semibold text-surface-900 dark:text-surface-0">{{
              item.title
            }}</span>
            <p class="body-small text-surface-600 dark:text-surface-400 mb-0 mt-1">
              {{ item.hint }}
            </p>
          </div>
          <div class="flex flex-wrap gap-2 items-center">
            <input
              type="file"
              :accept="
                item.key === 'favicon'
                  ? '.png,.ico,.svg,.webp,.gif,.jpg,.jpeg'
                  : '.png,.jpg,.jpeg,.webp,.svg,.gif'
              "
              class="hidden"
              :id="`brand-upload-${item.key}`"
              @change="onPickFile(item.key, $event)"
            />
            <BaseButton
              type="button"
              variant="secondary"
              :loading="uploading === item.key"
              label="Upload"
              icon="upload"
              size="small"
              @click="triggerPick(item.key)"
            />
            <BaseButton
              variant="secondary"
              label="Reset to Core default"
              icon="replay"
              size="small"
              text
              :loading="uploading === item.key"
              @click="clearSlot(item.key)"
            />
          </div>
        </div>
      </section>
    </div>
  </div>
</template>
