<template>
  <div class="name-generator-card">
    <div class="card-header">
      <h3>Generator {{ cardId }}</h3>
      <button class="reset-btn" @click="resetGenerator" title="Reset Generator">
        <svg
          class="icon icon--sm"
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"
            stroke="currentColor"
            stroke-width="2"
            fill="none"
          />
          <path
            d="M21 3v5h-5"
            stroke="currentColor"
            stroke-width="2"
            fill="none"
          />
          <path
            d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"
            stroke="currentColor"
            stroke-width="2"
            fill="none"
          />
          <path
            d="M3 21v-5h5"
            stroke="currentColor"
            stroke-width="2"
            fill="none"
          />
        </svg>
      </button>
    </div>

    <div class="controls">
      <div class="name-type-switch">
        <span class="switch-label">Type:</span>
        <div class="switch-container">
          <button
            type="button"
            class="switch-button"
            :class="{ active: !modern }"
            @click="modern = false"
          >
            Fantasy
          </button>
          <button
            type="button"
            class="switch-button button-switch"
            :class="{ active: modern }"
            @click="modern = true"
          >
            Modern
          </button>
        </div>
      </div>

      <label v-if="!modern">
        Race:
        <select v-model="race">
          <option v-for="r in races" :key="r.value" :value="r.value">
            {{ r.label }}
          </option>
        </select>
      </label>

      <label v-if="modern">
        Language:
        <select v-model="language">
          <option value="english">English</option>
          <option value="portuguese">Portuguese (EU)</option>
        </select>
      </label>

      <label>
        Gender:
        <select v-model="gender">
          <option value="male">Male</option>
          <option value="female">Female</option>
          <option v-if="modern" value="unisex">Unisex</option>
        </select>
      </label>
    </div>

    <button class="button-generate" @click="generate" :disabled="isLoading">
      {{ isLoading ? "Generating..." : "Generate" }}
    </button>

    <ul class="results" v-if="fullNames.length > 0">
      <li
        v-for="name in fullNames"
        :key="name"
        @click="copyToClipboard(name)"
        class="name-item"
        :title="'Click to copy: ' + name"
      >
        {{ name }}
        <svg
          class="copy-icon icon icon--sm"
          width="14"
          height="14"
          viewBox="0 0 24 24"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <rect
            x="9"
            y="9"
            width="13"
            height="13"
            rx="2"
            ry="2"
            stroke="currentColor"
            stroke-width="2"
            fill="none"
          />
          <path
            d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"
            stroke="currentColor"
            stroke-width="2"
            fill="none"
          />
        </svg>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref } from "vue";

const props = defineProps({
  cardId: {
    type: Number,
    required: true,
  },
});

const emit = defineEmits(["show-toast"]);

const modern = ref(false);
const isLoading = ref(false);

const races = [
  { label: "Aasimar", value: "aasimar" },
  { label: "Arakocra", value: "arakocra" },
  { label: "Bugbear", value: "bugbear" },
  { label: "Centaur", value: "centaur" },
  { label: "Changeling", value: "changeling" },
  { label: "Deep Gnome", value: "deep-gnome" },
  { label: "Deva", value: "deva" },
  { label: "Dragonborn", value: "dragonborn" },
  { label: "Drow", value: "drow" },
  { label: "Duergar", value: "duergar" },
  { label: "Dwarf", value: "dwarf" },
  { label: "Eladrin", value: "eladrin" },
  { label: "Elf", value: "elf" },
  { label: "Fairy", value: "fairy" },
  { label: "Firbolg", value: "firbolg" },
  { label: "Genasi", value: "genasi" },
  { label: "Githyanki", value: "githyanki" },
  { label: "Githzerai", value: "githzerai" },
  { label: "Gnome", value: "gnome" },
  { label: "Goblin", value: "goblin" },
  { label: "Goliath", value: "goliath" },
  { label: "Grung", value: "grung" },
  { label: "Half-Elf", value: "half-elf" },
  { label: "Half-Orc", value: "half-orc" },
  { label: "Halfling", value: "halfling" },
  { label: "Harengon", value: "harengon" },
  { label: "Hobgoblin", value: "hobgoblin" },
  { label: "Human", value: "human" },
  { label: "Kalashtar", value: "kalashtar" },
  { label: "Kenku", value: "kenku" },
  { label: "Kobold", value: "kobold" },
  { label: "Leonin", value: "leonin" },
  { label: "Lizardfolk", value: "lizardfolk" },
  { label: "Locathah", value: "locathah" },
  { label: "Loxodon", value: "loxodon" },
  { label: "Minotaur", value: "minotaur" },
  { label: "Orc", value: "orc" },
  { label: "Satyr", value: "satyr" },
  { label: "Shadar-Kai", value: "shadar-kai" },
  { label: "Shardmind", value: "shardmind" },
  { label: "Shifter", value: "shifter" },
  { label: "Simic Hybrid", value: "simic-hybrid" },
  { label: "Tabaxi", value: "tabaxi" },
  { label: "Tiefling", value: "tiefling" },
  { label: "Tortle", value: "tortle" },
  { label: "Triton", value: "triton" },
  { label: "Vedalken", value: "vedalken" },
  { label: "Verdan", value: "verdan" },
  { label: "Warforged", value: "warforged" },
  { label: "Wilden", value: "wilden" },
  { label: "Yuan-Ti", value: "yuan-ti" },
];

const race = ref(races[0].value);
const language = ref("english");
const gender = ref("male");
const fullNames = ref([]);

function resetGenerator() {
  modern.value = false;
  race.value = races[0].value;
  language.value = "english";
  gender.value = "male";
  fullNames.value = [];
}

async function generate() {
  fullNames.value = [];
  isLoading.value = true;

  try {
    if (modern.value) {
      // Use API for modern names
      const url = `https://namegen.fernandovideira.com/v1/modern/${language.value}?gender=${gender.value}`;
      const response = await fetch(url, {
        method: "GET",
        headers: {
          Referer: window.location.href,
          Origin: window.location.origin,
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();

      if (data.names) {
        fullNames.value = data.names;
      } else {
        console.error(
          "Failed to fetch modern names:",
          data.message || "Unknown error",
        );
        emit("show-toast", {
          message: `Error: ${
            data.message || "Failed to generate modern names"
          }`,
          type: "error",
        });
      }
    } else {
      // Use API for fantasy names
      const url = `https://namegen.fernandovideira.com/v1/fantasy/${race.value}-names?gender=${gender.value}`;
      const response = await fetch(url, {
        method: "GET",
        headers: {
          Referer: window.location.href,
          Origin: window.location.origin,
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();

      if (data.names) {
        fullNames.value = data.names;
      } else {
        console.error(
          "Failed to fetch fantasy names:",
          data.message || "Unknown error",
        );
        emit("show-toast", {
          message: `Error: ${
            data.message || "Failed to generate fantasy names"
          }`,
          type: "error",
        });
      }
    }
  } catch (error) {
    console.error("Error fetching names:", error);
    emit("show-toast", {
      message: `Connection error: ${error.message}`,
      type: "error",
    });
  } finally {
    isLoading.value = false;
  }
}

async function copyToClipboard(name) {
  try {
    await navigator.clipboard.writeText(name);
    emit("show-toast", {
      message: `"${name}" copied to clipboard!`,
      type: "success",
    });
  } catch (err) {
    console.error("Failed to copy to clipboard:", err);
    // Fallback for older browsers
    const textArea = document.createElement("textarea");
    textArea.value = name;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand("copy");
    document.body.removeChild(textArea);
    emit("show-toast", {
      message: `"${name}" copied to clipboard!`,
      type: "success",
    });
  }
}
</script>

<style scoped>
.name-generator-card {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  padding: var(--spacing-md);
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
  min-height: 320px;
  position: relative;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-sm);
}

.card-header h3 {
  margin: 0;
  font-size: 1.1rem;
  color: var(--color-text);
}

.reset-btn {
  background: transparent;
  border: 1px solid var(--color-card-border);
  border-radius: var(--radius-md);
  padding: var(--spacing-xs);
  color: var(--color-text-muted);
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.reset-btn:hover {
  background: var(--color-surface-hover);
  color: var(--color-text);
  border-color: var(--color-primary);
}

.controls {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.name-type-switch {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.switch-label {
  font-size: 0.9rem;
  color: var(--color-text-muted);
  font-weight: 500;
}

.switch-container {
  display: flex;
  border: 1px solid var(--color-card-border);
  border-radius: var(--radius-md);
  overflow: hidden;
  background: var(--color-background);
}

.switch-button {
  flex: 1;
  padding: var(--spacing-xs) var(--spacing-sm);
  background: var(--color-background);
  border: none;
  color: var(--color-text-muted);
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 0.9rem;
  font-weight: 500;
}

.switch-button:hover {
  background: var(--color-surface-hover);
  color: var(--color-text);
}

.switch-button.active {
  background: var(--color-primary);
  color: white;
  font-weight: 600;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
}

.switch-button + .switch-button {
  border-left: 1px solid var(--color-card-border);
}

label {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
  font-size: 0.9rem;
  color: var(--color-text-muted);
  font-weight: 500;
}

select {
  padding: var(--spacing-xs) var(--spacing-sm);
  border: 1px solid var(--color-card-border);
  border-radius: var(--radius-md);
  background: var(--color-background);
  color: var(--color-text);
  font-size: 0.9rem;
}

select:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px var(--color-primary-alpha);
}

.button-generate {
  padding: var(--spacing-sm) var(--spacing-md);
  background: var(--color-primary);
  color: white;
  border: none;
  border-radius: var(--border-radius);
  cursor: pointer;
  font-weight: 600;
  transition: all 0.16s ease;
  margin-top: var(--spacing-sm);
  box-shadow: var(--shadow-sm);
}

.button-generate:hover:not(:disabled) {
  background: var(--color-accent-hover);
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

.button-generate:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.results {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
  flex: 1;
  overflow-y: auto;
  max-height: 200px;
}

.name-item {
  padding: var(--spacing-xs) var(--spacing-sm);
  background: var(--surface-secondary);
  border: 1px solid var(--border);
  border-radius: var(--border-radius);
  cursor: pointer;
  transition: all 0.14s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.95rem;
}

.name-item:hover {
  background: var(--surface-hover);
  border-color: var(--border-hover);
  transform: translateX(2px);
}

.copy-icon {
  opacity: 0;
  transition: opacity 0.2s ease;
  color: var(--text-secondary);
}

.name-item:hover .copy-icon {
  opacity: 1;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}
</style>
