<script setup lang="ts">
/**
 * The inception form (milestone 297): "what does this project inherit?"
 *
 * Two homes, one component. mode="create" rides the New-project modal's
 * second step and only emits the choices (the project does not exist yet);
 * mode="decide" sits on ProjectView for an undecided project, loads that
 * project's current defaults, and records the decision itself.
 */
import { computed, onMounted, ref, watch } from "vue";
import { apiErrorMessage } from "@/api/client";
import { fetchDesignSystems } from "@/api/designSystems";
import {
  decideInception, emptyChoices, fetchInceptionDefaults,
  type InceptionChoices, type InceptionDecision, type InceptionDefaults,
} from "@/api/inception";
import { listRulebooks } from "@/api/rulebooks";

const props = withDefaults(defineProps<{
  mode: "create" | "decide";
  projectId?: number;
  choices?: InceptionChoices;
}>(), { projectId: 0, choices: undefined });

const emit = defineEmits<{
  "update:choices": [value: InceptionChoices];
  decided: [decision: InceptionDecision];
}>();

const local = ref<InceptionChoices>(props.choices ? { ...props.choices } : emptyChoices());
const alwaysOn = ref<{ id: number; title: string }[]>([]);
const others = ref<{ id: number; title: string }[]>([]);
const designSystems = ref<{ id: number; title: string }[]>([]);
const systemsCount = ref(0);
const loading = ref(true);
const saving = ref(false);
const error = ref("");

function emitChoices() {
  emit("update:choices", { ...local.value });
}
watch(local, emitChoices, { deep: true });

async function load() {
  loading.value = true;
  error.value = "";
  try {
    if (props.mode === "decide" && props.projectId) {
      const d: InceptionDefaults = await fetchInceptionDefaults(props.projectId);
      alwaysOn.value = d.always_on_rulebooks;
      others.value = d.other_rulebooks;
      designSystems.value = d.design_systems;
      systemsCount.value = d.systems;
      // Start from what stands today so "record" without changes is a true inherit-all.
      local.value = {
        exclude_always_on_rulebooks: d.excluded_always_on.map((r) => r.id),
        subscribe_rulebooks: d.subscribed_rulebooks.map((r) => r.id),
        design_system_id: d.design_system_id,
        seed_systems: false,
      };
    } else {
      const [rulebooks, ds] = await Promise.all([listRulebooks(), fetchDesignSystems()]);
      alwaysOn.value = rulebooks.filter((r) => r.always_on).map((r) => ({ id: r.id, title: r.title }));
      others.value = rulebooks.filter((r) => !r.always_on).map((r) => ({ id: r.id, title: r.title }));
      designSystems.value = ds.design_systems.map((d) => ({ id: d.id, title: d.title }));
    }
  } catch (e: unknown) {
    error.value = apiErrorMessage(e, "Could not load what this project could inherit");
  } finally {
    loading.value = false;
  }
}

function inherits(id: number): boolean {
  return !local.value.exclude_always_on_rulebooks.includes(id);
}
function toggleInherit(id: number) {
  const list = local.value.exclude_always_on_rulebooks;
  local.value.exclude_always_on_rulebooks = list.includes(id) ? list.filter((x) => x !== id) : [...list, id];
}
function subscribed(id: number): boolean {
  return local.value.subscribe_rulebooks.includes(id);
}
function toggleSubscribe(id: number) {
  const list = local.value.subscribe_rulebooks;
  local.value.subscribe_rulebooks = list.includes(id) ? list.filter((x) => x !== id) : [...list, id];
}

const nothingToDecide = computed(
  () => !alwaysOn.value.length && !others.value.length && !designSystems.value.length,
);

async function record() {
  if (!props.projectId) return;
  saving.value = true;
  error.value = "";
  try {
    const decision = await decideInception(props.projectId, local.value);
    emit("decided", decision);
  } catch (e: unknown) {
    error.value = apiErrorMessage(e, "Could not record the decision");
  } finally {
    saving.value = false;
  }
}

onMounted(load);
</script>

<template>
  <section class="inception" aria-labelledby="inception-title">
    <h3 id="inception-title" class="inception-title">What does this project inherit?</h3>
    <p class="inception-lede">
      A project's inheritance is a decision, not a default. Until it is recorded,
      every always-on rulebook binds, nothing is subscribed, and there is no design
      system or Systems.
    </p>
    <p v-if="loading" class="inception-muted">Loading…</p>
    <p v-else-if="error" class="error-msg">{{ error }}</p>
    <template v-else>
      <div v-if="alwaysOn.length" class="inception-group">
        <h4>Always-on rulebooks</h4>
        <p class="inception-muted">Checked = inherits. Uncheck to exclude a rulebook for this project only.</p>
        <label v-for="rb in alwaysOn" :key="rb.id" class="inception-choice">
          <input type="checkbox" :checked="inherits(rb.id)" @change="toggleInherit(rb.id)" />
          <span>{{ rb.title }}</span>
        </label>
      </div>
      <div v-if="others.length" class="inception-group">
        <h4>Subscribe to rulebooks</h4>
        <label v-for="rb in others" :key="rb.id" class="inception-choice">
          <input type="checkbox" :checked="subscribed(rb.id)" @change="toggleSubscribe(rb.id)" />
          <span>{{ rb.title }}</span>
        </label>
      </div>
      <div class="inception-group">
        <h4>Design system</h4>
        <select v-model="local.design_system_id" class="inception-select" aria-label="Design system">
          <option :value="null">None</option>
          <option v-for="ds in designSystems" :key="ds.id" :value="ds.id">{{ ds.title }}</option>
        </select>
      </div>
      <div class="inception-group">
        <label class="inception-choice">
          <input type="checkbox" v-model="local.seed_systems" :disabled="systemsCount > 0" />
          <span>
            Seed the standard starter Systems (CI &amp; Release, Auth &amp; Access, Data Model &amp; Storage, …)
            <em v-if="systemsCount > 0" class="inception-muted"> — this project already has {{ systemsCount }}</em>
          </span>
        </label>
      </div>
      <p v-if="nothingToDecide" class="inception-muted">
        Nothing to inherit yet on this install — recording still settles the question.
      </p>
      <div v-if="mode === 'decide'" class="inception-actions">
        <button class="btn-primary" :disabled="saving" @click="record">
          {{ saving ? "Recording…" : "Record decision" }}
        </button>
      </div>
    </template>
  </section>
</template>

<style scoped>
.inception {
  background: var(--fs-surface-raised);
  border: 1px solid var(--fs-border-color);
  border-radius: var(--fs-radius-lg);
  padding: 1.25rem 1.5rem;
  margin-bottom: 1.5rem;
}
.inception-title { margin: 0 0 0.35rem; font-size: 1.05rem; }
.inception-lede { margin: 0 0 1rem; color: var(--fs-text-secondary); font-size: 0.9rem; }
.inception-muted { color: var(--fs-text-tertiary); font-size: 0.85rem; margin: 0 0 0.35rem; }
.inception-group { margin-bottom: 1rem; }
.inception-group h4 { margin: 0 0 0.35rem; font-size: 0.9rem; font-weight: 500; }
.inception-choice { display: flex; align-items: flex-start; gap: 0.5rem; font-size: 0.9rem; margin: 0.25rem 0; }
.inception-choice input { margin-top: 0.2rem; accent-color: var(--fs-accent); }
.inception-select {
  padding: 0.45rem 0.7rem;
  border: 1px solid var(--fs-border-color);
  border-radius: var(--fs-radius-sm);
  background: var(--fs-surface-page);
  color: var(--fs-text-primary);
  font-size: 0.9rem;
}
.inception-actions { display: flex; justify-content: flex-end; margin-top: 0.5rem; }
.error-msg { color: var(--fs-error); font-size: 0.9rem; }
</style>
