<script setup lang="ts">
import { computed, ref } from "vue";

const props = defineProps<{ body: string }>();

const STORAGE_KEY = "word_count_mode";
const mode = ref<"words" | "time">(
  (localStorage.getItem(STORAGE_KEY) as "words" | "time") ?? "words"
);

function toggle() {
  mode.value = mode.value === "words" ? "time" : "words";
  localStorage.setItem(STORAGE_KEY, mode.value);
}

const plainText = computed(() =>
  props.body
    .replace(/```[\s\S]*?```/g, " ")
    .replace(/`[^`]*`/g, " ")
    .replace(/!?\[.*?\]\(.*?\)/g, " ")
    .replace(/\[\[([^\]]*)\]\]/g, "$1")
    .replace(/[#*_~>|\\]/g, " ")
    .trim()
);

const wordCount = computed(() => {
  if (!plainText.value) return 0;
  return plainText.value.split(/\s+/).filter(Boolean).length;
});

const charCount = computed(() => props.body.length);

const readingTime = computed(() => Math.max(1, Math.ceil(wordCount.value / 200)));

const label = computed(() => {
  if (!props.body.trim()) return "";
  if (mode.value === "time") return `~${readingTime.value} min read`;
  return `${wordCount.value.toLocaleString()} words · ${charCount.value.toLocaleString()} chars`;
});
</script>

<template>
  <button v-if="label" class="word-count" @click="toggle" :title="mode === 'words' ? 'Switch to reading time' : 'Switch to word count'">
    {{ label }}
  </button>
</template>

<style scoped>
.word-count {
  background: none;
  border: none;
  font-size: 0.72rem;
  color: var(--color-text-muted);
  cursor: pointer;
  padding: 0;
  white-space: nowrap;
  flex-shrink: 0;
}
.word-count:hover { color: var(--color-text); }
</style>
