<script setup>
import ActionButton from "@/components/ActionButton.vue";
import OverlayLoader from "@/components/OverlayLoader.vue";
import { useLanguageTemplateStore } from "@/stores/languageTemplateStore";
import { languages } from "@/utils/languageCode";
import { storeToRefs } from "pinia";
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { toast } from "vue3-toastify";

const route = useRoute();
const router = useRouter();
const templateStore = useLanguageTemplateStore();

const {
  readiness,
  loading,
  checking,
  saving,
} = storeToRefs(templateStore);

const {
  fetchTemplateById,
  fetchOccupiedLanguageCodes,
  addTemplate,
  updateStatus,
  checkPageTranslation,
  refreshReadiness,
} = templateStore;

/** Must be reactive: same component is used for /add and /:id/edit */
const templateId = computed(() => {
  const raw = route.params.id;
  return raw != null && String(raw).trim() !== "" ? String(raw) : "";
});
const isEdit = computed(() => Boolean(templateId.value));

const formData = ref({
  language_name: "",
  language_code: "",
  status: "Draft",
  updated_at: null,
  created_at: null,
});

const activeCategory = ref("pages");

/** Lowercased codes that already have a template (add flow only). */
const occupiedLanguageCodes = ref([]);
const occupiedLanguagesLoading = ref(false);

const categories = [
  { id: "pages", name: "Pages", icon: "bx-copy-alt", color: "#6366F1" },
  { id: "programs", name: "Programs", icon: "bx-layout", color: "#F59E0B" },
  { id: "activities", name: "Activities", icon: "bx-wrench", color: "#10B981" },
  { id: "forms", name: "Forms", icon: "bx-send", color: "#8B5CF6" },
  {
    id: "testimonials",
    name: "Testimonials",
    icon: "bx-smile",
    color: "#EC4899",
  },
];

async function loadTemplateRouteState() {
  if (isEdit.value) {
    const data = await fetchTemplateById(templateId.value);
    if (data?.template) {
      formData.value = {
        language_name: data.template.language_name,
        language_code: data.template.language_code,
        status: data.template.status,
        updated_at: data.template.updated_at ?? null,
        created_at: data.template.created_at ?? null,
      };
      await refreshReadiness(formData.value.language_code);
    } else {
      router.push("/pages/language-templates");
    }
    return;
  }

  formData.value = {
    language_name: "",
    language_code: "",
    status: "Draft",
    updated_at: null,
    created_at: null,
  };
  occupiedLanguagesLoading.value = true;
  try {
    occupiedLanguageCodes.value = await fetchOccupiedLanguageCodes();
    const taken = new Set(occupiedLanguageCodes.value);
    const current = String(formData.value.language_code || "")
      .toLowerCase()
      .trim();
    if (current && taken.has(current)) {
      formData.value.language_code = "";
      formData.value.language_name = "";
    }
  } finally {
    occupiedLanguagesLoading.value = false;
  }
}

onMounted(() => {
  loadTemplateRouteState();
});

watch(templateId, () => {
  loadTemplateRouteState();
});

// Watch for language selection to fetch readiness (pages list) for new templates
watch(
  () => formData.value.language_code,
  async (newCode) => {
    if (newCode && !isEdit.value) {
      await refreshReadiness(newCode);
    }
  },
);

/** Languages available in the add dropdown (excludes codes that already have a template). */
const languageOptionsForAdd = computed(() => {
  if (isEdit.value) {
    return languages;
  }
  const taken = new Set(occupiedLanguageCodes.value);
  return languages.filter(
    (l) => !taken.has(String(l.code).toLowerCase().trim()),
  );
});

const selectedLanguage = computed({
  get: () =>
    languageOptionsForAdd.value.find(
      (l) => l.code === formData.value.language_code,
    ),
  set: (val) => {
    if (val) {
      formData.value.language_name = val.name;
      formData.value.language_code = val.code;
    }
  },
});

const lastUpdatedLabel = computed(() => {
  if (!isEdit.value) {
    return "—";
  }
  const lastUpdatedAt =
    formData.value.updated_at || formData.value.created_at;
  if (!lastUpdatedAt) return "N/A";

  const parsedDate = new Date(lastUpdatedAt);
  if (Number.isNaN(parsedDate.getTime())) return "N/A";

  return new Intl.DateTimeFormat(undefined, {
    year: "numeric",
    month: "short",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  }).format(parsedDate);
});

function mergeTimestampsFromApiTemplate(t) {
  if (!t) return;
  if (t.updated_at != null) {
    formData.value.updated_at = t.updated_at;
  }
  if (t.created_at != null) {
    formData.value.created_at = t.created_at;
  }
}

async function handleRefreshReadiness() {
  if (!formData.value.language_code) return;
  await refreshReadiness(formData.value.language_code);
}

const checklistItems = computed(() => {
  if (!readiness.value) return [];

  return categories.flatMap((cat) => {
    const items = readiness.value?.[cat.id]?.items || [];
    return items.map((item) => ({
      id: `${cat.id}-${item.id}`,
      category: cat.name,
      categoryId: cat.id,
      title: item.title || item.name || "Untitled Item",
      subtitle: item.slug || item.page_type || "",
      ready: !!item.ready,
      missingReason: item.missing_reason || null,
      item,
    }));
  });
});

const checklistDoneCount = computed(
  () => checklistItems.value.filter((i) => i.ready).length,
);
const checklistTotalCount = computed(() => checklistItems.value.length);
const isChecklistComplete = computed(
  () =>
    checklistTotalCount.value > 0 &&
    checklistDoneCount.value === checklistTotalCount.value,
);
const showReadinessSections = computed(
  () =>
    !!readiness.value &&
    (isEdit.value || !!formData.value.language_code),
);

async function handleSave() {
  if (!formData.value.language_code) {
    toast.error("Please select a language");
    return;
  }

  if (isEdit.value) {
    return;
  }

  try {
    const { updated_at: _u, created_at: _c, ...templatePayload } =
      formData.value;
    const res = await addTemplate(templatePayload);

    if (res.status) {
      const createdId = res?.data?.id || res?.data?.template?.id;
      if (createdId) {
        router.push(`/pages/language-templates/${createdId}/edit`);
      } else {
        toast.error(
          "Template created, but could not open edit page automatically.",
        );
      }
    }
  } catch (err) {
    console.error(err);
  }
}

async function handlePublish() {
  const res = await updateStatus(templateId.value, "Published");
  if (res.status) {
    formData.value.status = "Published";
    const tpl = res?.data?.template ?? res?.data;
    if (tpl) {
      mergeTimestampsFromApiTemplate(tpl);
    }
  }
}

async function handleSetDraft() {
  const res = await updateStatus(templateId.value, "Draft");
  if (res.status) {
    formData.value.status = "Draft";
    const tpl = res?.data?.template ?? res?.data;
    if (tpl) {
      mergeTimestampsFromApiTemplate(tpl);
    }
  }
}

// Local state for checked pages when adding new template
const localCheckedPages = ref(new Set());

async function checkPage(pageId) {
  if (!formData.value.language_code) return;

  const res = await checkPageTranslation({
    page_id: pageId,
    language_code: formData.value.language_code,
  });

  if (res.status) {
    // If it's a new template, keep track locally of which ones we've "checked"
    if (!isEdit.value) {
      localCheckedPages.value.add(pageId);
    }
    // Refresh readiness to update the specific item status in store
    await refreshReadiness(formData.value.language_code);
  }
}

function handleCancel() {
  router.push("/pages/language-templates");
}

const getStatusColor = (status) => {
  switch (status) {
    case "Published":
      return "success";
    case "Needs Update":
      return "warning";
    case "Draft":
      return "secondary";
    default:
      return "primary";
  }
};

const getTranslateRoute = (categoryId, itemId) => {
  switch (categoryId) {
    case "pages":
      return `/pages/edit/${itemId}`;
    case "programs":
      return `/programs/${itemId}/edit`;
    case "activities":
      return `/activity/${itemId}/edit`;
    case "forms":
      return `/forms/edit/${itemId}`;
    case "testimonials":
      return `/testimonials`;
    default:
      return null;
  }
};

const getPreviewUrl = (item) => {
  const basePreviewUrl = import.meta.env.VITE_PREVIEW_URL || "";
  if (!basePreviewUrl) return null;

  const params = new URLSearchParams();
  if (item.page_type) params.set("type", item.page_type);
  if (item.slug) params.set("slug", item.slug);
  if (formData.value.language_code)
    params.set("lang", formData.value.language_code);

  const query = params.toString();
  return query ? `${basePreviewUrl}?${query}` : basePreviewUrl;
};
</script>

<template>
  <OverlayLoader :loading="loading" />

  <div class="add-edit-template-layout">
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">
          {{
            isEdit
              ? `${formData.language_name} — Website language template`
              : "New website language template"
          }}
        </h1>
        <p class="page-subtitle">
          Manage global translation sets and website publication readiness
        </p>
      </div>
      <div class="header-right">
        <VBtn
          variant="tonal"
          color="primary"
          prepend-icon="bx-arrow-back"
          class="header-back-btn"
          @click="handleCancel"
        >
          Back to templates
        </VBtn>
      </div>
    </div>

    <div class="content-grid">
      <div class="main-content">
        <!-- Language Config (Only visible when creating or in compact mode) -->
        <div class="form-section-card mb-6" v-if="!isEdit">
          <div class="section-header">
            <div class="section-icon-wrapper">
              <VIcon color="white">bx-globe</VIcon>
            </div>
            <div class="section-text">
              <h3 class="section-title">Language Configuration</h3>
              <p class="section-subtitle">
                Select the target language for this template
              </p>
            </div>
          </div>
          <div class="section-body">
            <VSelect
              v-model="selectedLanguage"
              :items="languageOptionsForAdd"
              item-title="name"
              label="Select Language"
              placeholder="Choose a language..."
              variant="outlined"
              density="comfortable"
              hide-details
              return-object
              clearable
              :loading="occupiedLanguagesLoading"
              :no-data-text="
                languageOptionsForAdd.length === 0
                  ? 'All languages already have a template'
                  : 'No matching language'
              "
            />
          </div>
        </div>

        <div
          id="required-checklist"
          v-if="showReadinessSections"
          class="checklist-summary-card mb-6"
        >
          <div class="checklist-summary-header">
            <div class="checklist-summary-header-text">
              <h3 class="checklist-title">Required Translation Checklist</h3>
              <p class="checklist-subtitle">
                Complete all required sections before publishing this language
                template.
              </p>
            </div>
            <div class="checklist-summary-header-aside">
              <VBtn
                v-if="formData.language_code"
                size="small"
                variant="tonal"
                prepend-icon="bx-refresh"
                :loading="checking"
                class="flex-shrink-0"
                @click="handleRefreshReadiness"
              >
                Refresh
              </VBtn>
              <VChip
                :color="isChecklistComplete ? 'success' : 'warning'"
                variant="flat"
                class="flex-shrink-0"
              >
                {{ checklistDoneCount }} / {{ checklistTotalCount }} Complete
              </VChip>
            </div>
          </div>

          <div class="checklist-grid">
            <div
              v-for="entry in checklistItems"
              :key="entry.id"
              class="checklist-item"
              :class="{ done: entry.ready }"
            >
              <div class="checklist-left">
                <VIcon :color="entry.ready ? 'success' : 'warning'" size="18">
                  {{ entry.ready ? "bx-check-circle" : "bx-radio-circle" }}
                </VIcon>
                <div class="checklist-text">
                  <div class="checklist-item-title">{{ entry.title }}</div>
                  <div class="checklist-item-meta">
                    {{ entry.category }}
                    <span v-if="entry.subtitle">• {{ entry.subtitle }}</span>
                  </div>
                  <div
                    v-if="!entry.ready && entry.missingReason"
                    class="checklist-missing"
                  >
                    {{ entry.missingReason }}
                  </div>
                </div>
              </div>
              <div class="checklist-actions">
                <VBtn
                  v-if="
                    !entry.ready &&
                    getTranslateRoute(entry.categoryId, entry.item.id)
                  "
                  size="x-small"
                  color="primary"
                  variant="flat"
                  :to="getTranslateRoute(entry.categoryId, entry.item.id)"
                >
                  Translate
                </VBtn>
                <VBtn
                  v-else-if="
                    entry.ready &&
                    entry.categoryId === 'pages' &&
                    getPreviewUrl(entry.item)
                  "
                  size="x-small"
                  color="secondary"
                  variant="tonal"
                  :href="getPreviewUrl(entry.item)"
                  target="_blank"
                >
                  Preview
                </VBtn>
              </div>
            </div>
          </div>
        </div>

        <!-- Category Tabs -->
        <div v-if="showReadinessSections" class="translation-explorer">
          <div class="explorer-sidebar">
            <div
              v-for="cat in categories"
              :key="cat.id"
              class="category-tab"
              :class="{
                active: activeCategory === cat.id,
                'is-missing': readiness[cat.id]?.missing_count > 0,
              }"
              @click="activeCategory = cat.id"
            >
              <div
                class="tab-icon"
                :style="{ backgroundColor: cat.color + '20', color: cat.color }"
              >
                <VIcon>{{ cat.icon }}</VIcon>
              </div>
              <div class="tab-info">
                <span class="tab-name">{{ cat.name }}</span>
                <span class="tab-stats"
                  >{{ readiness[cat.id]?.ready_count }} /
                  {{ readiness[cat.id]?.total }} Ready</span
                >
              </div>
              <VIcon
                v-if="readiness[cat.id]?.overall_ready"
                color="success"
                class="tab-status-icon"
                >bx-check-circle</VIcon
              >
              <VIcon v-else color="warning" class="tab-status-icon"
                >bx-time-five</VIcon
              >
            </div>
          </div>

          <div class="explorer-content">
            <div class="content-header">
              <h3 class="active-cat-title">
                {{ categories.find((c) => c.id === activeCategory)?.name }}
                Translation Details
              </h3>
              <VChip
                size="x-small"
                :color="
                  readiness[activeCategory]?.overall_ready
                    ? 'success'
                    : 'warning'
                "
                variant="tonal"
              >
                {{
                  readiness[activeCategory]?.overall_ready
                    ? "CATEGORY COMPLETE"
                    : "PENDING UPDATES"
                }}
              </VChip>
            </div>

            <div class="items-list">
              <div
                v-if="readiness[activeCategory]?.items?.length === 0"
                class="empty-state py-8 text-center text-slate-400"
              >
                <VIcon size="48" class="mb-2 opacity-20">bx-folder-open</VIcon>
                <p>No items found or all items are currently ready.</p>
              </div>

              <div
                v-for="item in readiness[activeCategory]?.items"
                :key="item.id"
                class="readiness-item"
                :class="{ 'is-ready': item.ready, 'is-missing': !item.ready }"
              >
                <div class="item-primary">
                  <span class="item-title">{{
                    item.title || item.name || "Untitled Item"
                  }}</span>
                  <span class="item-meta">{{
                    item.slug || item.page_type || "No slug"
                  }}</span>
                  <div
                    v-if="item.missing_reason"
                    class="item-reason mt-1 flex items-center gap-1"
                  >
                    <VIcon size="14" color="warning">bx-info-circle</VIcon>
                    <span>{{ item.missing_reason }}</span>
                  </div>
                </div>

                <div class="item-actions">
                  <VChip
                    v-if="item.status || item.translation_status"
                    size="x-small"
                    :color="
                      ['publish', 'published', 'public'].includes(
                        (item.status || item.translation_status || '').toLowerCase(),
                      )
                        ? 'success'
                        : 'info'
                    "
                    class="mr-2"
                  >
                    {{ (item.status || item.translation_status || "").toUpperCase() }}
                  </VChip>

                  <VBtn
                    v-if="activeCategory === 'pages'"
                    size="small"
                    variant="text"
                    icon="bx-sync"
                    color="primary"
                    :loading="checking"
                    @click="checkPage(item.id)"
                  />

                  <VBtn
                    v-if="
                      !item.ready && getTranslateRoute(activeCategory, item.id)
                    "
                    size="small"
                    color="primary"
                    variant="flat"
                    :to="getTranslateRoute(activeCategory, item.id)"
                    class="ml-2"
                  >
                    Translate
                  </VBtn>

                  <VBtn
                    v-if="item.ready && getPreviewUrl(item)"
                    size="small"
                    color="secondary"
                    variant="tonal"
                    :href="getPreviewUrl(item)"
                    target="_blank"
                    class="ml-2"
                  >
                    Preview
                  </VBtn>

                  <div class="status-marker ml-2">
                    <VIcon v-if="item.ready" color="success"
                      >bx-check-circle</VIcon
                    >
                    <VIcon v-else color="warning" class="pulse-animation"
                      >bx-error-circle</VIcon
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Sticky Sidebar -->
      <div class="side-content">
        <div class="sticky-wrapper">
          <div class="sidebar-card">
            <div class="sidebar-meta-rows">
              <div class="sidebar-meta-row">
                <span class="sidebar-meta-label">Template status</span>
                <template v-if="isEdit">
                  <VChip
                    :color="getStatusColor(formData.status)"
                    variant="flat"
                    size="small"
                    class="sidebar-status-chip"
                  >
                    {{ formData.status.toUpperCase() }}
                  </VChip>
                </template>
                <span v-else class="sidebar-meta-value text-medium-emphasis">
                  Draft after create
                </span>
              </div>
              <div class="sidebar-meta-row">
                <span class="sidebar-meta-label">Last updated</span>
                <span class="sidebar-meta-value">{{ lastUpdatedLabel }}</span>
              </div>
            </div>

            <div class="divider my-4" />

            <div class="actions-stack">
              <div v-if="!isEdit">
                <ActionButton
                  label="Create Template"
                  icon="bx-plus"
                  severity="primary"
                  class="w-full mb-3 h-12"
                  :loading="saving"
                  @click="handleSave"
                />
              </div>

              <div v-else>
                <p class="sidebar-hint mb-3">
                  <template v-if="formData.status === 'Published'">
                    This language is live for franchise websites. Save as draft
                    to unpublish.
                  </template>
                  <template v-else>
                    Publish when the checklist is complete. Save as draft to
                    keep this language unpublished.
                  </template>
                </p>
                <ActionButton
                  label="Publish Language"
                  icon="bx-rocket"
                  severity="primary"
                  class="w-full mb-3 h-12"
                  :loading="saving"
                  :disabled="
                    formData.status === 'Published' || !isChecklistComplete
                  "
                  @click="handlePublish"
                />
                <p
                  v-if="
                    formData.status !== 'Published' && !isChecklistComplete
                  "
                  class="text-xs text-amber-600 mb-3"
                >
                  Complete all checklist items to enable publishing.
                </p>
                <ActionButton
                  label="Save as draft"
                  icon="bx-save"
                  severity="secondary"
                  class="w-full h-12"
                  :loading="saving"
                  :disabled="formData.status === 'Draft'"
                  @click="handleSetDraft"
                />
              </div>
            </div>
          </div>

          <div
            v-if="isEdit"
            class="sidebar-card mt-6 bg-slate-50 border-dashed border-slate-300"
          >
            <h4 class="text-sm font-bold text-slate-700 mb-2 uppercase">
              Publishing Rules
            </h4>
            <ul class="text-xs text-slate-500 space-y-2">
              <li class="flex gap-2">
                <VIcon size="14" color="primary">bx-check-double</VIcon>
                All "Global" marked pages must have a Published translation.
              </li>
              <li class="flex gap-2">
                <VIcon size="14" color="primary">bx-check-double</VIcon>
                Programs and Activities require basic translation details.
              </li>
              <li class="flex gap-2">
                <VIcon size="14" color="primary">bx-check-double</VIcon>
                Missing items will trigger a "Needs Update" status.
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.add-edit-template-layout {
  padding: 32px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 32px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-back-btn {
  font-weight: 600;
}

.sidebar-meta-rows {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.sidebar-meta-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.sidebar-meta-label {
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 0.06em;
  text-transform: uppercase;
  color: #64748b;
  flex-shrink: 0;
}

.sidebar-meta-value {
  font-size: 13px;
  font-weight: 600;
  color: #0f172a;
  text-align: right;
}

.sidebar-status-chip {
  font-weight: 700 !important;
}

.page-title {
  font-size: 32px;
  font-weight: 800;
  color: #0f172a;
  margin: 0 0 4px 0;
  letter-spacing: -1px;
}

.status-pill-big {
  font-weight: 900 !important;
  letter-spacing: 1px;
  padding: 0 24px !important;
}

.content-grid {
  display: grid;
  grid-template-columns: 1fr 360px;
  gap: 32px;
}

.checklist-summary-card {
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 16px;
  padding: 20px;
}

.checklist-summary-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 16px;
}

.checklist-summary-header-text {
  min-width: 0;
  flex: 1;
}

.checklist-summary-header-aside {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-shrink: 0;
}

.checklist-title {
  font-size: 18px;
  font-weight: 700;
  color: #0f172a;
  margin: 0;
}

.checklist-subtitle {
  margin: 4px 0 0;
  color: #64748b;
  font-size: 13px;
}

.checklist-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 10px;
  max-height: 360px;
  overflow: auto;
  padding-right: 4px;
}

.checklist-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 10px 12px;
  background: #f8fafc;
}

.checklist-item.done {
  border-color: #bbf7d0;
  background: #f0fdf4;
}

.checklist-left {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  min-width: 0;
}

.checklist-text {
  min-width: 0;
}

.checklist-item-title {
  font-weight: 600;
  color: #0f172a;
  font-size: 13px;
}

.checklist-item-meta {
  color: #64748b;
  font-size: 12px;
}

.checklist-missing {
  color: #b45309;
  font-size: 12px;
}

/* Translation Explorer */
.translation-explorer {
  display: grid;
  grid-template-columns: 280px 1fr;
  background: white;
  border-radius: 20px;
  overflow: hidden;
  border: 1px solid #e2e8f0;
  min-height: 600px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
}

.explorer-sidebar {
  background: #f8fafc;
  padding: 24px 16px;
  border-right: 1px solid #e2e8f0;
}

.category-tab {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 12px;
  cursor: pointer;
  margin-bottom: 8px;
  transition: all 0.2s ease;
  position: relative;
}

.category-tab:hover {
  background: #f1f5f9;
}

.category-tab.active {
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #e2e8f0;
}

.category-tab.is-missing::before {
  content: "";
  position: absolute;
  left: 4px;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 24px;
  background: #f59e0b;
  border-radius: 4px;
}

.tab-icon {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.tab-info {
  display: flex;
  flex-direction: column;
}

.tab-name {
  font-size: 14px;
  font-weight: 700;
  color: #1e293b;
}

.tab-stats {
  font-size: 11px;
  color: #64748b;
  font-weight: 500;
}

.tab-status-icon {
  margin-left: auto;
  font-size: 18px;
}

.explorer-content {
  padding: 32px;
  display: flex;
  flex-direction: column;
}

.content-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f1f5f9;
}

.active-cat-title {
  font-size: 18px;
  font-weight: 800;
  color: #0f172a;
}

/* Items List */
.readiness-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-radius: 12px;
  margin-bottom: 12px;
  border: 1px solid #f1f5f9;
  transition: all 0.2s ease;
}

.readiness-item:hover {
  background: #f8fafc;
  transform: translateX(4px);
}

.item-primary {
  display: flex;
  flex-direction: column;
}

.item-title {
  font-size: 15px;
  font-weight: 700;
  color: #1e293b;
}

.item-meta {
  font-size: 12px;
  color: #94a3b8;
  font-family: monospace;
}

.item-reason {
  font-size: 11px;
  font-weight: 600;
  color: #d97706;
}

.item-actions {
  display: flex;
  align-items: center;
}

.status-marker {
  font-size: 20px;
}

/* Sidebar */
.sticky-wrapper {
  position: sticky;
  top: 105px;
}

.sidebar-card {
  background: white;
  border-radius: 20px;
  padding: 24px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
}

.sidebar-title {
  font-size: 16px;
  font-weight: 800;
  color: #0f172a;
  margin: 0 0 20px 0;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.sidebar-hint {
  font-size: 13px;
  color: #64748b;
  line-height: 1.5;
}

.divider {
  height: 1px;
  background: #e2e8f0;
}

.pulse-animation {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}

@media (max-width: 1024px) {
  .content-grid {
    grid-template-columns: 1fr;
  }
  .translation-explorer {
    grid-template-columns: 1fr;
  }
  .explorer-sidebar {
    display: flex;
    overflow-x: auto;
    padding: 12px;
    border-right: none;
    border-bottom: 1px solid #e2e8f0;
  }
  .category-tab {
    flex-shrink: 0;
    min-width: 160px;
    margin-right: 12px;
    margin-bottom: 0;
  }
}
</style>

<style scoped>
.add-edit-template-layout {
  padding: 32px;
  max-width: 1300px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

.header-back-btn {
  font-weight: 600;
}

.sidebar-meta-rows {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.sidebar-meta-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.sidebar-meta-label {
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 0.06em;
  text-transform: uppercase;
  color: #64748b;
  flex-shrink: 0;
}

.sidebar-meta-value {
  font-size: 13px;
  font-weight: 600;
  color: #0f172a;
  text-align: right;
}

.sidebar-status-chip {
  font-weight: 700 !important;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #1e293b;
  margin: 0 0 4px 0;
  letter-spacing: -0.5px;
}

.page-subtitle {
  font-size: 15px;
  color: #64748b;
  margin: 0;
}

.content-grid {
  display: grid;
  grid-template-columns: 1fr 340px;
  gap: 32px;
  position: relative;
  z-index: 10;
}

.main-content {
  display: flex;
  flex-direction: column;
}

/* Form Section Card */
.form-section-card {
  background: white;
  border-radius: 16px;
  border: 1px solid #e2e8f0;
  overflow: hidden;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
}

.section-header {
  padding: 20px 24px;
  background: #f8fafc;
  display: flex;
  align-items: center;
  gap: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.section-icon-wrapper {
  width: 44px;
  height: 44px;
  border-radius: 12px;
  background: linear-gradient(135deg, #003b6f, #0056a3);
  display: flex;
  align-items: center;
  justify-content: center;
}

.pages-icon {
  background: linear-gradient(135deg, #6366f1, #4f46e5);
}

.section-title {
  font-size: 18px;
  font-weight: 700;
  color: #1e293b;
  margin: 0;
}

.section-subtitle {
  font-size: 13px;
  color: #64748b;
  margin: 0;
}

.section-body {
  padding: 24px;
}

/* Language Display */
.language-display {
  background: #f1f5f9;
  padding: 16px;
  border-radius: 12px;
}

.display-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.display-item .label {
  font-size: 14px;
  font-weight: 600;
  color: #64748b;
}

.display-item .value {
  font-size: 16px;
  font-weight: 700;
  color: #0f172a;
}

/* Pages Grid */
.pages-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

.page-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.page-card:hover {
  border-color: #cbd5e1;
  transform: translateY(-2px);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.05);
}

.page-card.is-selected {
  border-color: #003b6f;
  background: #f0f7ff;
}

.page-card-icon {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-card-info {
  flex: 1;
}

.page-name {
  font-size: 15px;
  font-weight: 700;
  color: #1e293b;
  margin: 0 0 2px 0;
}

.page-desc {
  font-size: 12px;
  color: #64748b;
  margin: 0;
}

/* Sidebar */
.side-content {
  height: 100%;
}

.sticky-wrapper {
  position: sticky;
  top: 105px;
  z-index: 10;
}

.sidebar-card {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
}

.sidebar-title {
  font-size: 16px;
  font-weight: 700;
  color: #1e293b;
  margin: 0 0 16px 0;
}

.status-indicator {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.status-chip {
  font-weight: 800 !important;
  letter-spacing: 0.5px;
}

.status-date {
  font-size: 12px;
  color: #94a3b8;
}

.sidebar-text {
  font-size: 13px;
  line-height: 1.6;
  color: #64748b;
  margin-bottom: 24px;
}

.actions-stack {
  display: flex;
  flex-direction: column;
}

.w-full {
  width: 100%;
}

.divider {
  height: 1px;
  background: #e2e8f0;
}

.cancel-btn :deep(.p-button-label) {
  font-weight: 500;
}

/* Responsive */
@media (max-width: 1024px) {
  .content-grid {
    grid-template-columns: 1fr;
  }

  .sticky-wrapper {
    position: static;
  }

  .side-content {
    order: -1;
  }
}
</style>
