<!-- components/SectionLayouts/WhatChildrenGainLayout.vue -->
<template>
  <div class="what-children-gain-layout">
    <!-- Main Heading -->
    <div v-if="section.fields.mainHeading" class="heading-field">
      <SectionField
        :field="section.fields.mainHeading"
        field-key="mainHeading"
        :section-key="sectionKey"
        :section-model="sectionModel"
        :model-value="sectionModel"
        :user-role="userRole"
        :disabled="disabled"
        :is-super-admin="isSuperAdmin"
        :is-hero-field="true"
        @update-field="emitUpdate"
      />
    </div>

    <!-- Programs Repeater (program dropdown + tag + description + robot image) -->
    <div v-if="section.fields.programs" class="programs-container">
      <div class="repeater-items">
        <DraggableList
          :model-value="sectionModel.programs || []"
          :disabled="disabled"
          row-class="mb-4"
          @update:model-value="onReorder"
        >
          <template #item="{ element: item, index }">
            <div class="repeater-item-row">
              <div class="fields-wrapper">
            <!-- Program selector: maps slide to a program (logo + age auto) -->
            <div class="field-group">
              <label class="field-label">Program</label>
              <VSelect
                :model-value="resolveProgramId(item)"
                :items="programOptions"
                item-title="title"
                item-value="id"
                placeholder="Select a program"
                :loading="programsLoading"
                :disabled="disabled"
                clearable
                hide-details
                density="compact"
                variant="outlined"
                @update:model-value="onProgramSelect(index, $event)"
              />
            </div>

            <!-- Program card (left 50%) + Robot image (right 50%) in one row -->
            <div class="card-image-row">
              <!-- Auto-filled program preview (logo + age) -->
              <div class="col-half">
                <label class="field-label">Selected Program</label>
                <div class="program-preview">
                  <div class="program-logo-box">
                    <img
                      v-if="item.programLogo"
                      :src="item.programLogo"
                      :alt="item.program_name || 'Program logo'"
                      class="program-logo-img"
                    />
                    <span v-else class="no-logo">No logo</span>
                  </div>
                  <div class="program-meta">
                    <span class="program-name">{{ item.program_name || "No program" }}</span>
                    <span class="program-age">Age: {{ item.programAge || "—" }}</span>
                  </div>
                </div>
              </div>

              <!-- Robot image (per slide / shown as thumbnail too) -->
              <div class="col-half">
                <label class="field-label">Robot Image</label>
                <div class="robot-image-row">
                  <div class="robot-image-box">
                    <img
                      v-if="item.programImage"
                      :src="item.programImage"
                      alt="Robot"
                      class="robot-image-img"
                    />
                    <span v-else class="no-image">No image</span>
                  </div>
                  <div class="robot-image-actions">
                    <VBtn
                      variant="tonal"
                      color="primary"
                      size="small"
                      prepend-icon="bx-image-add"
                      :disabled="disabled"
                      @click="openRobotImagePicker(index)"
                    >
                      {{ item.programImage ? "Change Image" : "Select Image" }}
                    </VBtn>
                    <VBtn
                      v-if="item.programImage"
                      variant="text"
                      color="error"
                      size="small"
                      icon="bx-x"
                      :disabled="disabled"
                      @click="updateFieldInRepeater(index, 'programImage', '')"
                    />
                  </div>
                </div>
              </div>
            </div>

            <!-- Tag (robot name shown on the pill) -->
            <div class="field-group">
              <label class="field-label">Tag</label>
              <VTextField
                :model-value="item.programTitle || ''"
                placeholder="e.g., Fan Moving Robot"
                :disabled="disabled"
                hide-details
                density="compact"
                variant="outlined"
                @update:model-value="updateFieldInRepeater(index, 'programTitle', $event)"
              />
            </div>

            <!-- Description -->
            <div class="field-group">
              <label class="field-label">Description</label>
              <VTextarea
                :model-value="item.programHeading || ''"
                placeholder="e.g., Program for developing confidence in problem-solving"
                :disabled="disabled"
                hide-details
                density="compact"
                rows="3"
                variant="outlined"
                @update:model-value="updateFieldInRepeater(index, 'programHeading', $event)"
              />
            </div>
          </div>

              <button
                v-if="!disabled"
                class="btn-remove"
                @click="removeItem(index)"
                title="Remove"
              >
                <VIcon size="20">bx-trash</VIcon>
              </button>
            </div>
          </template>
        </DraggableList>

        <!-- Add new item -->
        <div v-if="!disabled && canAddMore" class="add-item-row">
          <VBtn color="primary" prepend-icon="bx-plus" @click="addItem">
            Add Program Slide
          </VBtn>
        </div>
      </div>

      <p class="info-text">
        {{ (sectionModel.programs || []).length }} /
        {{ maxItems }} items
      </p>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import { VBtn, VIcon, VSelect, VTextField, VTextarea } from "vuetify/components";
import { useProgramStore } from "@/stores/programStore";
import SectionField from "../SectionField.vue";
import DraggableList from "@/components/DraggableList.vue";

const props = defineProps({
  section: Object,
  sectionKey: String,
  sectionModel: Object,
  userRole: String,
  disabled: Boolean,
  isSuperAdmin: Boolean,
});

const emit = defineEmits(["update-field", "open-media-picker"]);

const emitUpdate = (sectionKey, fieldKey, value) => {
  emit("update-field", sectionKey, fieldKey, value);
};

const maxItems = computed(() => props.section.fields.programs?.maxItems || 10);
const currentCount = computed(() => (props.sectionModel.programs || []).length);
const canAddMore = computed(() => currentCount.value < maxItems.value);

/* ---- Programs (for the dropdown) ---- */
const programStore = useProgramStore();
const programsLoading = ref(false);
const programOptions = computed(() =>
  (programStore.programs || [])
    .filter((p) => p && p.id && p.title)
    .map((p) => ({
      id: p.id,
      // parent_program_id is the immutable global id for a franchisee override;
      // a global program has none. Used to resolve the stored mapping across tenants.
      parent_program_id: p.parent_program_id || null,
      is_global: !!p.is_global,
      title: p.title,
      slug: p.slug || "",
      program_icon: p.program_icon || "",
      age_range: p.age_range || "",
    })),
);

// The stable, cross-tenant identity of a program. A franchisee override and the
// global program it derives from both normalise to the same global id, so a slide
// saved by the super admin resolves to whichever copy this tenant actually has.
const globalIdOf = (p) => (p && (p.parent_program_id || p.id)) || null;

// Map a stored mapping (which holds the GLOBAL id) to THIS tenant's matching
// program id, so the VSelect shows the program name instead of a raw UUID.
const resolveProgramId = (item) => {
  if (!item?.program_id) return null;
  // Primary: match by the normalised global id. Covers every super-admin-saved
  // mapping (overridden by this tenant or not).
  const byChain = programOptions.value.find(
    (p) => globalIdOf(p) === item.program_id,
  );
  if (byChain) return byChain.id;
  // Fallback: a legacy mapping saved by a franchisee stored this tenant's own
  // row id directly — match it so old data keeps resolving.
  const byId = programOptions.value.find((p) => p.id === item.program_id);
  return byId ? byId.id : null;
};

onMounted(async () => {
  if ((programStore.programs || []).length === 0) {
    programsLoading.value = true;
    try {
      await programStore.fetchProgramsLazy({ page: 1, rows: 200 });
    } catch (e) {
      // store surfaces its own toast
    } finally {
      programsLoading.value = false;
    }
  }
});

/* ---- Repeater helpers ---- */
const updateFieldInRepeater = (index, fieldKey, value) => {
  const programs = [...(props.sectionModel.programs || [])];
  if (!programs[index]) programs[index] = {};
  programs[index] = { ...programs[index], [fieldKey]: value };
  emit("update-field", props.sectionKey, "programs", programs);
};

const setItemFields = (index, fields) => {
  const programs = [...(props.sectionModel.programs || [])];
  if (!programs[index]) programs[index] = {};
  programs[index] = { ...programs[index], ...fields };
  emit("update-field", props.sectionKey, "programs", programs);
};

// Store the GLOBAL id + resolved logo/age/slug so the public site can render
// directly. We persist the global id (not this tenant's row id) so the mapping
// stays valid for every franchisee.
const onProgramSelect = (index, programId) => {
  if (!programId) {
    setItemFields(index, {
      program_id: "",
      program_name: "",
      programSlug: "",
      programLogo: "",
      programAge: "",
    });
    return;
  }
  const program = programOptions.value.find((p) => p.id === programId);
  setItemFields(index, {
    // Normalise to the global id so an override and its global parent map alike.
    program_id: globalIdOf(program) || programId,
    program_name: program?.title || "",
    programSlug: program?.slug || "",
    programLogo: program?.program_icon || "",
    programAge: program?.age_range || "",
  });
};

const openRobotImagePicker = (index) => {
  emit("open-media-picker", {
    sectionKey: props.sectionKey,
    fieldKey: `programs.${index}.programImage`,
    // What Children Gain robots (seeded in media as `what_children_gain`).
    mediaCategory: "what_children_gain",
    multiple: false,
  });
};

const addItem = () => {
  if (!canAddMore.value) return;
  const programs = [...(props.sectionModel.programs || [])];
  programs.push({
    program_id: "",
    program_name: "",
    programSlug: "",
    programLogo: "",
    programAge: "",
    programImage: "",
    programTitle: "",
    programHeading: "",
  });
  emit("update-field", props.sectionKey, "programs", programs);
};

const removeItem = (index) => {
  const programs = (props.sectionModel.programs || []).filter(
    (_, i) => i !== index,
  );
  emit("update-field", props.sectionKey, "programs", programs);
};

// Persist a drag-reordered program-slide list.
const onReorder = (newArray) => {
  emit("update-field", props.sectionKey, "programs", newArray);
};
</script>

<style scoped>
.what-children-gain-layout {
  background: #ffffff;
  padding: 4px;
}

.heading-field {
  margin-bottom: 16px;
  width: 100%;
}

.programs-container {
  margin-top: 12px;
  padding: 0;
  background: transparent;
  border-radius: 8px;
}

.repeater-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.repeater-item-row {
  display: flex;
  gap: 16px;
  align-items: flex-start;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 16px;
}

.fields-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.field-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.field-label {
  font-size: 12px;
  font-weight: 600;
  color: #374151;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

/* Program card (left) + Robot image (right) in one row */
.card-image-row {
  display: flex;
  gap: 16px;
  align-items: stretch;
}

.col-half {
  flex: 1 1 50%;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

@media (max-width: 600px) {
  .card-image-row {
    flex-direction: column;
  }
}

.program-preview {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  background: #f8fafc;
  border: 1px dashed #cbd5e1;
  border-radius: 8px;
  flex: 1;
}

.program-logo-box {
  width: 90px;
  height: 60px;
  border-radius: 8px;
  background: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  flex-shrink: 0;
}

.program-logo-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.program-meta {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.program-name {
  font-size: 13px;
  font-weight: 600;
  color: #1f2937;
}

.program-age {
  font-size: 12px;
  color: #6b7280;
}

.no-logo,
.no-image {
  font-size: 11px;
  color: #9ca3af;
}

.robot-image-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.robot-image-box {
  width: 90px;
  height: 70px;
  border-radius: 8px;
  background: #f3f4f6;
  border: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  flex-shrink: 0;
}

.robot-image-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.robot-image-actions {
  display: flex;
  align-items: center;
  gap: 6px;
}

.btn-remove {
  padding: 4px 8px;
  border: none;
  background: transparent;
  color: #dc2626;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  margin-top: 4px;
}

.btn-remove:hover {
  color: #991b1b;
  background: rgba(239, 68, 68, 0.1);
  border-radius: 4px;
}

.add-item-row {
  display: flex;
  padding: 12px 0;
}

.info-text {
  font-size: 12px;
  color: #9ca3af;
  margin: 8px 0 0;
  text-align: center;
}

@media (max-width: 768px) {
  .what-children-gain-layout {
    padding: 4px;
  }

  .heading-field {
    margin-bottom: 16px;
  }

  .programs-container {
    padding: 12px;
  }
}
</style>
