<template>
  <div class="home-page">
    <HomeHeroStatus
      :content="content"
      :status-items="statusItems"
      :lab-status="labStatus"
      :loading="loading"
      :error="error"
      :last-checked-label="lastCheckedLabel"
      :mailto-href="mailtoHref"
    />

    <HomeProfessionalSections :content="content" />

    <PlatformSection
      :lab-data="labData"
      :lab-status="labStatus"
      :service-data="serviceData"
      :network-data="networkData"
      :metrics-data="metricsData"
      :loading="loading"
      :error="error"
    />

    <HomeMemberAccess
      :content="content"
      :member-panel-copy="memberPanelCopy"
      :member-action="memberAction"
      :member-state="memberState"
    />

    <HomeContactFooter
      :content="content"
      :mailto-href="mailtoHref"
      :current-year="currentYear"
    />
  </div>
</template>

<script setup>
import { computed } from "vue";
import { useRoute } from "vue-router";
import HomeContactFooter from "../components/HomeContactFooter.vue";
import HomeHeroStatus from "../components/HomeHeroStatus.vue";
import HomeMemberAccess from "../components/HomeMemberAccess.vue";
import HomeProfessionalSections from "../components/HomeProfessionalSections.vue";
import PlatformSection from "../components/PlatformSection.vue";
import { auth } from "../auth";
import { contactMailto, homepageContentForMode, homepageModeFromRoute } from "../data/homepageContent";
import { useMemberAccessState } from "../member/useMemberAccessState";

const props = defineProps({
  labData: Object,
  labStatus: Object,
  serviceData: Object,
  networkData: Object,
  metricsData: Object,
  loading: Boolean,
  error: String,
});

const route = useRoute();
const homepageMode = computed(() => homepageModeFromRoute(route));
const content = computed(() => homepageContentForMode(homepageMode.value));
const { memberState, memberAction } = useMemberAccessState();
const currentYear = new Date().getFullYear();
const mailtoHref = computed(() => contactMailto(content.value));

const statusItems = computed(() => [
  {
    label: "Atlas cluster",
    labelHref: "#platform",
    value: statusLabelFrom(contentStatus.value.atlas),
    state: contentStatus.value.atlas,
  },
  {
    label: "Outpost hosts",
    value: dedicatedHostsLabel.value,
    state: dedicatedHostsState.value,
    children: dedicatedHostItems.value,
  },
  {
    label: "Most requested service",
    value: activeServiceLabel.value,
    href: activeServiceHref.value,
    state: activeServiceState.value,
  },
]);

const contentStatus = computed(() => ({
  atlas: statusState(props.labStatus?.atlas),
}));

const activeService = computed(() => props.labStatus?.active_service || null);
const activeServiceLabel = computed(() => {
  if (activeService.value?.known && activeService.value?.label) return activeService.value.label;
  return "Waiting for activity data";
});
const activeServiceHref = computed(() => activeService.value?.url || "");
const activeServiceState = computed(() => (activeService.value?.known ? "ok" : "unknown"));

const dedicatedHosts = computed(() => props.labStatus?.dedicated_hosts || null);
const dedicatedHostsState = computed(() => {
  if (!dedicatedHosts.value?.known) return "unknown";
  const total = dedicatedHostTotal(dedicatedHosts.value);
  const upCount = Number.isFinite(dedicatedHosts.value.up_count) ? dedicatedHosts.value.up_count : 0;
  if (upCount <= 0) return "bad";
  if (upCount < total) return "warn";
  return "ok";
});
const dedicatedHostsLabel = computed(() => {
  const hosts = dedicatedHosts.value;
  if (!hosts?.known) return "Waiting for public checks";
  const total = dedicatedHostTotal(hosts);
  const upCount = Number.isFinite(hosts.up_count) ? hosts.up_count : 0;
  return `${upCount} of ${total} online`;
});
const dedicatedHostItems = computed(() => {
  const hosts = dedicatedHosts.value?.hosts;
  if (!Array.isArray(hosts) || !hosts.length) return [];
  return hosts.map((host) => ({
    label: dedicatedHostLabel(host.label),
    value: host.known ? (host.up ? "Online" : "Offline") : "Unknown",
    state: statusState(host),
  }));
});

const lastCheckedLabel = computed(() => {
  const checkedAt = props.labStatus?.checked_at;
  if (!checkedAt) return "Waiting for public status";
  return new Date(checkedAt * 1000).toLocaleString(undefined, {
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "2-digit",
  });
});

const memberPanelCopy = computed(() => {
  if (auth.enabled && auth.authenticated) return content.value.memberAccessCopy.authenticated;
  if (memberAction.value?.kind === "restricted") return content.value.memberAccessCopy.restricted;
  return "";
});

function statusState(status) {
  if (!status || status.known === false) return "unknown";
  return status.up ? "ok" : "bad";
}

function statusLabelFrom(state) {
  if (state === "ok") return "Responding";
  if (state === "bad") return "Needs attention";
  return "Unknown";
}

function dedicatedHostTotal(hosts) {
  if (Number.isFinite(hosts?.total)) return hosts.total;
  return Array.isArray(hosts?.hosts) && hosts.hosts.length ? hosts.hosts.length : 2;
}

function dedicatedHostLabel(label = "") {
  const normalized = label.toLowerCase();
  if (normalized.includes("database") || normalized.includes("db")) return "Database machine";
  if (normalized.includes("jump") || normalized.includes("theia")) return "Jumphost";
  return label || "Host";
}
</script>

<style scoped>
:global(html) {
  scroll-behavior: auto;
  scroll-padding-top: 76px;
}

.home-page {
  max-width: 1240px;
  margin: 0 auto;
  padding: 40px 22px 72px;
}

@media (max-width: 760px) {
  .home-page {
    padding: 28px 16px 56px;
  }
}
</style>
