<script setup lang="ts">
import { computed } from "vue";
import { useGmStore } from "../../ui/stores/gmStore";

const gmStore = useGmStore();

const factionLabelById = computed(() =>
  new Map(gmStore.factions.map((faction) => [faction.id, faction.label])),
);

function factionLabel(factionId?: string | null) {
  if (!factionId) return "—";
  return factionLabelById.value.get(factionId) ?? factionId;
}

function titleCase(value?: string | null) {
  if (!value) return "—";
  return value
    .replace(/[-_]+/g, " ")
    .replace(/\s+/g, " ")
    .trim()
    .replace(/\b\w/g, (char) => char.toUpperCase());
}

function percent(value?: number | null) {
  if (value == null || Number.isNaN(value)) return "—";
  return `${Math.round(value * 100)}%`;
}

const relations = computed(() =>
  [...(gmStore.geopolitics?.diplomacy.relations ?? [])]
    .sort((left, right) => right.tensionScore - left.tensionScore || left.id.localeCompare(right.id))
    .slice(0, 12),
);

const incidents = computed(() =>
  [...(gmStore.geopolitics?.diplomacy.incidents ?? [])]
    .sort((left, right) => right.lastObservedAtUtc.localeCompare(left.lastObservedAtUtc))
    .slice(0, 8),
);

const contestedSystems = computed(() =>
  [...(gmStore.geopolitics?.territory.controlStates ?? [])]
    .filter((state) => state.isContested)
    .sort((left, right) => right.strategicValue - left.strategicValue || left.systemId.localeCompare(right.systemId))
    .slice(0, 12),
);

const frontLines = computed(() =>
  [...(gmStore.geopolitics?.territory.frontLines ?? [])]
    .sort((left, right) => right.pressureScore - left.pressureScore || left.id.localeCompare(right.id))
    .slice(0, 10),
);

const regions = computed(() =>
  [...(gmStore.geopolitics?.economyRegions.regions ?? [])]
    .sort((left, right) => left.label.localeCompare(right.label))
    .slice(0, 16),
);

const bottlenecks = computed(() =>
  [...(gmStore.geopolitics?.economyRegions.bottlenecks ?? [])]
    .sort((left, right) => right.severity - left.severity || left.id.localeCompare(right.id))
    .slice(0, 12),
);

const corridors = computed(() =>
  [...(gmStore.geopolitics?.economyRegions.corridors ?? [])]
    .sort((left, right) => right.riskScore - left.riskScore || left.id.localeCompare(right.id))
    .slice(0, 12),
);
</script>

<template>
  <div class="space-y-5 p-4 text-xs text-white/90">
    <div v-if="!gmStore.geopolitics" class="rounded border border-white/10 bg-white/5 p-4 text-white/60">
      No geopolitical state loaded.
    </div>

    <template v-else>
      <section class="grid gap-3 md:grid-cols-4">
        <div class="rounded border border-white/10 bg-white/5 p-3">
          <div class="text-[11px] uppercase tracking-[0.2em] text-white/50">Diplomacy</div>
          <div class="mt-2 text-lg font-semibold">{{ gmStore.geopolitics.diplomacy.relations.length }}</div>
          <div class="text-white/60">relations</div>
        </div>
        <div class="rounded border border-white/10 bg-white/5 p-3">
          <div class="text-[11px] uppercase tracking-[0.2em] text-white/50">Wars</div>
          <div class="mt-2 text-lg font-semibold">{{ gmStore.geopolitics.diplomacy.wars.length }}</div>
          <div class="text-white/60">active conflicts</div>
        </div>
        <div class="rounded border border-white/10 bg-white/5 p-3">
          <div class="text-[11px] uppercase tracking-[0.2em] text-white/50">Contested</div>
          <div class="mt-2 text-lg font-semibold">{{ contestedSystems.length }}</div>
          <div class="text-white/60">systems</div>
        </div>
        <div class="rounded border border-white/10 bg-white/5 p-3">
          <div class="text-[11px] uppercase tracking-[0.2em] text-white/50">Regions</div>
          <div class="mt-2 text-lg font-semibold">{{ gmStore.geopolitics.economyRegions.regions.length }}</div>
          <div class="text-white/60">economic regions</div>
        </div>
      </section>

      <section class="grid gap-5 xl:grid-cols-2">
        <div class="rounded border border-white/10 bg-white/5 p-4">
          <h3 class="text-sm font-semibold">Relations</h3>
          <div class="mt-3 space-y-2">
            <div v-for="relation in relations" :key="relation.id" class="rounded border border-white/10 bg-black/20 p-2">
              <div class="font-medium">{{ factionLabel(relation.factionAId) }} vs {{ factionLabel(relation.factionBId) }}</div>
              <div class="mt-1 text-white/70">
                {{ titleCase(relation.posture) }} · tension {{ percent(relation.tensionScore) }} · grievance {{ percent(relation.grievanceScore) }}
              </div>
              <div class="text-white/55">
                Trade {{ relation.tradeAccessPolicy }} · Military {{ relation.militaryAccessPolicy }} · treaties {{ relation.activeTreatyIds.length }} · incidents {{ relation.activeIncidentIds.length }}<span v-if="relation.warStateId"> · war {{ relation.warStateId }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="rounded border border-white/10 bg-white/5 p-4">
          <h3 class="text-sm font-semibold">Incidents</h3>
          <div class="mt-3 space-y-2">
            <div v-for="incident in incidents" :key="incident.id" class="rounded border border-white/10 bg-black/20 p-2">
              <div class="font-medium">{{ titleCase(incident.kind) }} · {{ incident.systemId ?? "no-system" }}</div>
              <div class="mt-1 text-white/70">{{ incident.summary }}</div>
              <div class="text-white/55">
                Severity {{ incident.severity.toFixed(2) }} · Escalation {{ incident.escalationScore.toFixed(2) }} · {{ factionLabel(incident.sourceFactionId) }} → {{ factionLabel(incident.targetFactionId) }}
              </div>
            </div>
          </div>
        </div>
      </section>

      <section class="grid gap-5 xl:grid-cols-2">
        <div class="rounded border border-white/10 bg-white/5 p-4">
          <h3 class="text-sm font-semibold">Territory</h3>
          <div class="mt-3 space-y-2">
            <div v-for="state in contestedSystems" :key="state.systemId" class="rounded border border-white/10 bg-black/20 p-2">
              <div class="font-medium">{{ state.systemId }} · {{ titleCase(state.controlKind) }}</div>
              <div class="mt-1 text-white/70">
                Control {{ state.controlScore.toFixed(1) }} · strategic {{ state.strategicValue.toFixed(1) }}
              </div>
              <div class="text-white/55">
                Controller {{ factionLabel(state.controllerFactionId) }} · Claimant {{ factionLabel(state.primaryClaimantFactionId) }}
              </div>
            </div>
          </div>
        </div>

        <div class="rounded border border-white/10 bg-white/5 p-4">
          <h3 class="text-sm font-semibold">Front Lines</h3>
          <div class="mt-3 space-y-2">
            <div v-for="front in frontLines" :key="front.id" class="rounded border border-white/10 bg-black/20 p-2">
              <div class="font-medium">{{ front.id }}</div>
              <div class="mt-1 text-white/70">
                {{ titleCase(front.kind) }} · pressure {{ percent(front.pressureScore) }} · supply {{ percent(front.supplyRisk) }}
              </div>
              <div class="text-white/55">
                {{ front.factionIds.map((id) => factionLabel(id)).join(" vs ") }}<span v-if="front.anchorSystemId"> · anchor {{ front.anchorSystemId }}</span><br>
                {{ front.systemIds.join(", ") }}
              </div>
            </div>
          </div>
        </div>
      </section>

      <section class="grid gap-5 xl:grid-cols-2">
        <div class="rounded border border-white/10 bg-white/5 p-4">
          <h3 class="text-sm font-semibold">Economic Regions</h3>
          <div class="mt-3 space-y-2">
            <div v-for="region in regions" :key="region.id" class="rounded border border-white/10 bg-black/20 p-2">
              <div class="font-medium">{{ region.label }}</div>
              <div class="mt-1 text-white/70">
                {{ titleCase(region.kind) }} · core {{ region.coreSystemId }} · systems {{ region.systemIds.length }}
              </div>
              <div class="text-white/55">
                Faction {{ factionLabel(region.factionId) }} · fronts {{ region.frontLineIds.length }} · corridors {{ region.corridorIds.length }}
              </div>
            </div>
          </div>
        </div>

        <div class="rounded border border-white/10 bg-white/5 p-4">
          <h3 class="text-sm font-semibold">Bottlenecks And Corridors</h3>
          <div class="mt-3 space-y-2">
            <div v-for="bottleneck in bottlenecks" :key="bottleneck.id" class="rounded border border-white/10 bg-black/20 p-2">
              <div class="font-medium">{{ bottleneck.itemId }} · {{ bottleneck.regionId }}</div>
              <div class="mt-1 text-white/70">
                {{ titleCase(bottleneck.cause) }} · severity {{ bottleneck.severity.toFixed(2) }}
              </div>
            </div>
            <div v-for="corridor in corridors" :key="corridor.id" class="rounded border border-white/10 bg-black/20 p-2">
              <div class="font-medium">{{ corridor.id }}</div>
              <div class="mt-1 text-white/70">
                {{ titleCase(corridor.kind) }} · {{ titleCase(corridor.accessState) }} · risk {{ percent(corridor.riskScore) }}
              </div>
              <div class="text-white/55">
                Path {{ corridor.systemPathIds.join(" → ") }}
              </div>
            </div>
          </div>
        </div>
      </section>
    </template>
  </div>
</template>
