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

interface Props {
  title: string;
  text?: string;
  url: string;
  variant?: "icon" | "button" | "inline";
}

const props = withDefaults(defineProps<Props>(), {
  text: "",
  variant: "icon",
});

const copied = ref(false);
const showFallback = ref(false);

// Check if Web Share API is available
const canShare = computed(() => {
  return (
    typeof navigator !== "undefined" &&
    typeof navigator.share === "function" &&
    navigator.canShare?.({ url: props.url, title: props.title })
  );
});

async function handleShare() {
  if (canShare.value) {
    try {
      await navigator.share({
        title: props.title,
        text: props.text,
        url: props.url,
      });
    } catch (err: any) {
      // User cancelled or error - show fallback
      if (err.name !== "AbortError") {
        showFallback.value = true;
      }
    }
  } else {
    showFallback.value = true;
  }
}

async function copyLink() {
  try {
    await navigator.clipboard.writeText(props.url);
    copied.value = true;
    setTimeout(() => {
      copied.value = false;
    }, 2000);
  } catch (err) {
    // Fallback for older browsers
    const input = document.createElement("input");
    input.value = props.url;
    document.body.appendChild(input);
    input.select();
    document.execCommand("copy");
    document.body.removeChild(input);
    copied.value = true;
    setTimeout(() => {
      copied.value = false;
    }, 2000);
  }
}

function closeFallback() {
  showFallback.value = false;
}
</script>

<template>
  <div class="relative">
    <!-- Inline variant: Copy Link + Share buttons side by side -->
    <div v-if="variant === 'inline'" class="flex items-center gap-2">
      <!-- Copy Link Button (always visible) -->
      <button
        @click="copyLink"
        class="h-10 px-3 rounded-warm bg-warm-bg-surface border border-warm-border-subtle hover:border-warm-accent hover:bg-warm-accent/10 flex items-center gap-2 transition-all text-sm"
        :class="{ 'border-green-500 bg-green-500/10': copied }"
        aria-label="Copy link"
        title="Copy link"
      >
        <i
          :class="
            copied
              ? 'ph ph-check text-green-400'
              : 'ph ph-link text-warm-text-secondary'
          "
        ></i>
        <span
          class="text-warm-text-secondary whitespace-nowrap"
          :class="{ 'text-green-400': copied }"
        >
          {{ copied ? "Copied!" : "Copy link" }}
        </span>
      </button>

      <!-- Share Button (shows native share or dropdown) -->
      <button
        @click="handleShare"
        class="w-10 h-10 rounded-warm bg-warm-bg-surface border border-warm-border-subtle hover:border-warm-accent hover:bg-warm-accent/10 flex items-center justify-center transition-all"
        aria-label="Share"
        title="Share"
      >
        <i
          class="ph ph-share-network text-warm-text-secondary hover:text-warm-accent"
        ></i>
      </button>
    </div>

    <!-- Icon variant -->
    <button
      v-else-if="variant === 'icon'"
      @click="handleShare"
      class="w-10 h-10 rounded-warm bg-warm-bg-surface border border-warm-border-subtle hover:border-warm-accent hover:bg-warm-accent/10 flex items-center justify-center transition-all"
      aria-label="Share"
      title="Share"
    >
      <i
        class="ph ph-share-network text-warm-text-secondary hover:text-warm-accent"
      ></i>
    </button>

    <!-- Button variant -->
    <button
      v-else
      @click="handleShare"
      class="btn-ghost inline-flex items-center gap-2"
      aria-label="Share"
    >
      <i class="ph ph-share-network"></i>
      Share
    </button>

    <!-- Fallback Dropdown -->
    <div
      v-if="showFallback"
      class="absolute right-0 top-full mt-2 w-64 bg-warm-bg-surface border border-warm-border-subtle rounded-warm shadow-lg z-50 p-3"
    >
      <div class="flex items-center justify-between mb-2">
        <span class="text-sm text-warm-text-secondary">Share link</span>
        <button
          @click="closeFallback"
          class="text-warm-text-muted hover:text-warm-text-primary"
          aria-label="Close"
        >
          <i class="ph ph-x text-sm"></i>
        </button>
      </div>

      <div class="flex gap-2">
        <input
          type="text"
          :value="url"
          readonly
          class="flex-1 bg-warm-bg-deep border border-warm-border-subtle rounded px-2 py-1.5 text-xs text-warm-text-primary font-mono truncate"
        />
        <button
          @click="copyLink"
          class="btn-primary px-3 py-1.5 text-xs shrink-0"
          :class="{ 'bg-green-600 hover:bg-green-600': copied }"
        >
          <i :class="copied ? 'ph ph-check' : 'ph ph-copy'"></i>
        </button>
      </div>

      <!-- Social links -->
      <div class="flex gap-2 mt-3 pt-3 border-t border-warm-border-subtle">
        <a
          :href="`https://twitter.com/intent/tweet?text=${encodeURIComponent(title)}&url=${encodeURIComponent(url)}`"
          target="_blank"
          rel="noopener noreferrer"
          class="flex-1 py-1.5 rounded bg-warm-bg-elevated hover:bg-warm-accent/10 text-center text-xs text-warm-text-secondary hover:text-warm-accent transition-colors"
          aria-label="Share on X/Twitter"
        >
          <i class="ph ph-x-logo"></i>
        </a>
        <a
          :href="`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`"
          target="_blank"
          rel="noopener noreferrer"
          class="flex-1 py-1.5 rounded bg-warm-bg-elevated hover:bg-warm-accent/10 text-center text-xs text-warm-text-secondary hover:text-warm-accent transition-colors"
          aria-label="Share on LinkedIn"
        >
          <i class="ph ph-linkedin-logo"></i>
        </a>
        <a
          :href="`mailto:?subject=${encodeURIComponent(title)}&body=${encodeURIComponent(text + '\n\n' + url)}`"
          class="flex-1 py-1.5 rounded bg-warm-bg-elevated hover:bg-warm-accent/10 text-center text-xs text-warm-text-secondary hover:text-warm-accent transition-colors"
          aria-label="Share via Email"
        >
          <i class="ph ph-envelope"></i>
        </a>
      </div>
    </div>

    <!-- Backdrop for closing fallback -->
    <div
      v-if="showFallback"
      class="fixed inset-0 z-40"
      @click="closeFallback"
    ></div>
  </div>
</template>
