<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { getProjectApplicableRules } from "@/api/rulebooks";
import type { ApplicableRules } from "@/api/rulebooks";

const props = defineProps<{ projectId: number }>();
const data = ref<ApplicableRules | null>(null);

function grouped(rules: ApplicableRules["rules"]) {
  const g: Record<string, Record<string, ApplicableRules["rules"]>> = {};
  for (const r of rules) {
    (g[r.rulebook_title] ??= {});
    (g[r.rulebook_title][r.topic_title] ??= []).push(r);
  }
  return g;
}

async function load() {
  data.value = await getProjectApplicableRules(props.projectId);
}

onMounted(load);
watch(() => props.projectId, load);
</script>

<template>
  <section class="plan-rules" v-if="data && data.rules.length">
    <h3>Applicable rules</h3>
    <div v-for="(topics, rb) in grouped(data.rules)" :key="rb" class="rb">
      <h4>{{ rb }}</h4>
      <div v-for="(rules, topic) in topics" :key="topic">
        <h5>{{ topic }}</h5>
        <ul>
          <li v-for="r in rules" :key="r.id">
            <strong>{{ r.title }}</strong> — {{ r.statement }}
          </li>
        </ul>
      </div>
    </div>
    <p v-if="data.truncated" class="truncated">
      Truncated at 50 rules — more apply.
    </p>
  </section>
</template>

<style scoped>
.plan-rules {
  margin-top: 1.5rem;
  border-top: 1px solid var(--fs-border-color);
  padding-top: 1rem;
}
.plan-rules h3 {
  font-size: 0.9em; opacity: 0.7;
  text-transform: uppercase; letter-spacing: 0.05em;
}
/* `.rb` is deliberately bare — it exists to namespace the two heading rules
   below, and its children carry their own spacing (the h4 keeps the UA
   margin-top that separates one rulebook group from the next). Nothing here
   assumes a flex or grid parent, which is the tell that distinguishes this
   from a base rule someone deleted (#2444). Stated so the next reader doesn't
   re-open the question. */
.rb h4 { font-family: Fraunces, serif; font-style: italic; margin-bottom: 0.25rem; }
.rb h5 {
  font-size: 0.8em; opacity: 0.7;
  text-transform: uppercase; margin-top: 0.5rem;
}
.plan-rules ul {
  list-style: none; padding-left: 0.75rem; margin: 0.25rem 0;
  border-left: 2px solid var(--fs-accent);
}
.plan-rules li { margin: 0.35rem 0; font-size: 0.92em; }
.truncated { opacity: 0.7; font-style: italic; font-size: 0.85em; }
</style>
