<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { useToast } from "primevue/usetoast";
import { useConfirm } from "primevue/useconfirm";
import { contentApi } from "../../api/content";
import { tenantApi } from "../../api/tenant";

const route = useRoute();
const toast = useToast();
const confirm = useConfirm();

const fontSize = ref(18);
const isPlaying = ref(false);
const content = ref({});
const comments = ref([]);

const isLiked = ref(false);
const isFavorited = ref(false);
const likeLoading = ref(false);
const favLoading = ref(false);
const newComment = ref("");
const commentLoading = ref(false);

const listComments = async () => {
  try {
    const cmts = await contentApi.listComments(route.params.id);
    comments.value = cmts.items || [];
  } catch (e) {
    console.error("Failed to load comments", e);
  }
};

onMounted(async () => {
  try {
    const res = await contentApi.get(route.params.id);
    content.value = res;
    isLiked.value = res.is_liked;
    isFavorited.value = res.is_favorited;
    listComments(); // Fetch comments
  } catch (e) {
    console.error(e);
  }
});

const submitComment = async () => {
  if (!newComment.value || commentLoading.value) return;
  commentLoading.value = true;
  try {
    await contentApi.createComment(content.value.id, {
      content: newComment.value,
    });
    toast.add({ severity: "success", summary: "评论成功", life: 2000 });
    newComment.value = "";
    listComments(); // Refresh comments
  } catch (e) {
    toast.add({
      severity: "error",
      summary: "评论失败",
      detail: e.message,
      life: 3000,
    });
  } finally {
    commentLoading.value = false;
  }
};

const toggleLike = async () => {
  if (likeLoading.value) return;
  likeLoading.value = true;
  try {
    if (isLiked.value) {
      await contentApi.removeLike(content.value.id);
      isLiked.value = false;
      content.value.likes--;
    } else {
      await contentApi.addLike(content.value.id);
      isLiked.value = true;
      content.value.likes++;
      toast.add({ severity: "success", summary: "点赞成功", life: 1000 });
    }
  } catch (e) {
    toast.add({
      severity: "error",
      summary: "操作失败",
      detail: e.message,
      life: 3000,
    });
  } finally {
    likeLoading.value = false;
  }
};

const toggleFavorite = async () => {
  if (favLoading.value) return;
  favLoading.value = true;
  try {
    if (isFavorited.value) {
      await contentApi.removeFavorite(content.value.id);
      isFavorited.value = false;
      toast.add({ severity: "info", summary: "取消收藏", life: 1000 });
    } else {
      await contentApi.addFavorite(content.value.id);
      isFavorited.value = true;
      toast.add({ severity: "success", summary: "收藏成功", life: 1000 });
    }
  } catch (e) {
    toast.add({
      severity: "error",
      summary: "操作失败",
      detail: e.message,
      life: 3000,
    });
  } finally {
    favLoading.value = false;
  }
};

const handlePurchase = () => {
  confirm.require({
    message: `确认支付 ¥${content.value.price} 购买此内容？`,
    header: "购买确认",
    icon: "pi pi-shopping-cart",
    accept: () => {
      // Mock purchase flow
      toast.add({
        severity: "success",
        summary: "购买成功",
        detail: "已解锁完整内容",
        life: 2000,
      });
      content.value.is_purchased = true;
    },
  });
};

const authorIsFollowing = ref(false);
const authorFollowLoading = ref(false);

const toggleAuthorFollow = async () => {
  if (authorFollowLoading.value) return;
  authorFollowLoading.value = true;
  try {
    if (authorIsFollowing.value) {
      await tenantApi.unfollow(content.value.author_id);
      authorIsFollowing.value = false;
    } else {
      await tenantApi.follow(content.value.author_id);
      authorIsFollowing.value = true;
    }
  } catch (e) {
    toast.add({ severity: "error", summary: "操作失败", life: 2000 });
  } finally {
    authorFollowLoading.value = false;
  }
};

const likeComment = async (comment) => {
  if (comment.loading) return;
  comment.loading = true;
  try {
    await contentApi.likeComment(comment.id);
    // Note: The backend doesn't support unliking comments via the same endpoint.
    // This is an optimistic update.
    if (comment.is_liked) {
      // This part might not work if backend doesn't support unliking
      // comment.likes--;
      // comment.is_liked = false;
    } else {
      comment.likes++;
      comment.is_liked = true;
    }
  } catch (e) {
    toast.add({
      severity: "error",
      summary: "点赞失败",
      detail: e.message,
      life: 3000,
    });
  } finally {
    comment.loading = false;
  }
};
</script>

<template>
  <div
    class="grid grid-cols-1 lg:grid-cols-12 gap-8 mx-auto max-w-screen-xl px-4 sm:px-6 lg:px-8 py-8 items-start"
  >
    <!-- Main Content (Left 9) -->
    <div class="lg:col-span-9 space-y-6">
      <!-- Article Body -->
      <div
        class="bg-white rounded-xl shadow-sm border border-slate-100 p-8 md:p-12 relative overflow-hidden"
      >
        <!-- Header -->
        <div class="mb-8 border-b border-slate-100 pb-8">
          <div class="flex items-start justify-between gap-4 mb-4">
            <h1
              class="text-3xl md:text-4xl font-bold text-slate-900 leading-tight"
            >
              <span class="text-primary-600 mr-2 text-2xl align-middle"
                >[{{ content.genre || "未分类" }}]</span
              >
              {{ content.title }}
            </h1>
          </div>

          <!-- Opera Meta -->
          <div class="flex flex-wrap gap-3 mb-6" v-if="content.meta">
            <span
              v-if="content.meta.role"
              class="px-3 py-1 bg-slate-100 text-slate-600 rounded-full text-sm font-bold"
              >行当: {{ content.meta.role }}</span
            >
            <span
              v-if="content.meta.key"
              class="px-3 py-1 bg-slate-100 text-slate-600 rounded-full text-sm font-bold"
              >定调: {{ content.meta.key }}</span
            >
            <span
              v-if="content.meta.beat"
              class="px-3 py-1 bg-slate-100 text-slate-600 rounded-full text-sm font-bold"
              >板式: {{ content.meta.beat }}</span
            >
          </div>

          <!-- Author & Tools -->
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-3">
              <img
                :src="
                  content.author_avatar ||
                  `https://api.dicebear.com/7.x/avataaars/svg?seed=${content.author_id}`
                "
                class="w-10 h-10 rounded-full border border-slate-200"
              />
              <div>
                <div class="font-bold text-slate-900 text-sm">
                  {{ content.author_name }}
                  <i class="pi pi-check-circle text-blue-500 text-xs"></i>
                </div>
                <div class="text-xs text-slate-400">
                  发布于 {{ content.create_time }}
                </div>
              </div>
            </div>
            <div class="flex items-center gap-2">
              <button
                @click="fontSize++"
                class="w-9 h-9 flex items-center justify-center rounded hover:bg-slate-100 text-slate-600"
                title="放大字体"
              >
                <i class="pi pi-plus" style="font-size: 0.8rem"></i>A
              </button>
              <button
                @click="fontSize--"
                class="w-9 h-9 flex items-center justify-center rounded hover:bg-slate-100 text-slate-600"
                title="缩小字体"
              >
                <i class="pi pi-minus" style="font-size: 0.8rem"></i>A
              </button>
              <div class="w-px h-4 bg-slate-200 mx-1"></div>
              <button
                class="w-9 h-9 flex items-center justify-center rounded hover:bg-slate-100 text-slate-600"
                @click="
                  toast.add({ severity: 'info', summary: '分享功能开发中' })
                "
              >
                <i class="pi pi-share-alt"></i>
              </button>
              <button
                class="w-9 h-9 flex items-center justify-center rounded hover:bg-slate-100 transition-colors"
                :class="
                  isFavorited
                    ? 'text-primary-600 bg-primary-50'
                    : 'text-slate-600'
                "
                @click="toggleFavorite"
                :disabled="favLoading"
              >
                <i
                  class="pi"
                  :class="[
                    favLoading
                      ? 'pi-spinner pi-spin'
                      : isFavorited
                        ? 'pi-bookmark-fill'
                        : 'pi-bookmark',
                  ]"
                ></i>
              </button>
              <button
                class="w-auto h-9 px-3 flex items-center justify-center rounded hover:bg-slate-100 transition-colors gap-1"
                :class="isLiked ? 'text-red-500 bg-red-50' : 'text-slate-600'"
                @click="toggleLike"
                :disabled="likeLoading"
              >
                <i
                  class="pi"
                  :class="[
                    likeLoading
                      ? 'pi-spinner pi-spin'
                      : isLiked
                        ? 'pi-thumbs-up-fill'
                        : 'pi-thumbs-up',
                  ]"
                ></i>
                <span class="text-xs font-bold">{{ content.likes }}</span>
              </button>
            </div>
          </div>
        </div>

        <!-- Content Render -->
        <div
          class="prose prose-slate max-w-none text-slate-800"
          :style="{ fontSize: fontSize + 'px' }"
        >
          <!-- Video Player -->
          <div
            class="not-prose mb-8 rounded-xl overflow-hidden bg-black relative group aspect-video"
            v-if="content.type === 'video'"
          >
            <video
              v-if="isPlaying"
              :src="content.media_urls?.[0]?.url"
              controls
              autoplay
              class="w-full h-full object-contain bg-black"
            ></video>

            <div
              class="absolute inset-0 flex items-center justify-center text-white z-10"
              v-if="!isPlaying"
            >
              <img
                v-if="content.cover"
                :src="content.cover"
                class="absolute inset-0 w-full h-full object-cover opacity-50"
              />
              <button
                @click="isPlaying = true"
                class="w-16 h-16 bg-white/20 hover:bg-white/30 backdrop-blur rounded-full flex items-center justify-center transition-all relative z-20"
              >
                <i class="pi pi-play text-3xl ml-1"></i>
              </button>
            </div>

            <!-- Paywall Overlay -->
            <div
              v-if="!content.is_purchased && content.price > 0 && !isPlaying"
              class="absolute inset-0 bg-black/80 backdrop-blur-sm flex flex-col items-center justify-center text-center p-8 z-30"
            >
              <h3 class="text-white text-xl font-bold mb-2">试看已结束</h3>
              <p class="text-slate-300 text-sm mb-6">
                购买后可观看完整内容 (包含高清视频 + 完整剧本)
              </p>
              <button
                @click="handlePurchase"
                class="px-8 py-3 bg-primary-600 text-white rounded-full font-bold hover:bg-primary-700 shadow-lg shadow-primary-900/50 transition-transform hover:scale-105 active:scale-95"
              >
                ¥ {{ content.price }} 立即解锁
              </button>
            </div>
          </div>

          <div v-html="content.body"></div>

          <!-- Paywall Mask for Text -->
          <div
            class="relative mt-8 pt-20 pb-8 text-center"
            v-if="!content.is_purchased && content.price > 0"
          >
            <div
              class="absolute inset-0 bg-gradient-to-b from-transparent via-white/90 to-white z-10"
            ></div>
            <div class="relative z-20">
              <button
                @click="handlePurchase"
                class="px-10 py-3.5 bg-primary-600 text-white rounded-full font-bold text-lg hover:bg-primary-700 shadow-xl shadow-primary-100 transition-transform hover:scale-105 active:scale-95 flex items-center gap-2 mx-auto"
              >
                <i class="pi pi-lock"></i> 购买解锁全文 ¥ {{ content.price }}
              </button>
              <p class="text-xs text-slate-400 mt-3">支持微信 / 支付宝</p>
            </div>
          </div>
        </div>
      </div>

      <!-- Comments Section -->
      <div class="bg-white rounded-xl shadow-sm border border-slate-100 p-8">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-xl font-bold text-slate-900">
            全部评论 ({{ comments.length }})
          </h2>
        </div>

        <!-- Comment Input -->
        <div class="flex items-start gap-4 mb-8">
          <img
            src="https://api.dicebear.com/7.x/initials/svg?seed=User"
            class="w-10 h-10 rounded-full bg-slate-100"
          />
          <div class="flex-1">
            <textarea
              v-model="newComment"
              placeholder="发表你的看法..."
              rows="3"
              class="w-full border border-slate-200 rounded-lg p-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary-100 transition-all"
            ></textarea>
            <div class="flex justify-end mt-2">
              <button
                @click="submitComment"
                :disabled="!newComment || commentLoading"
                class="px-6 py-2 bg-primary-600 text-white rounded-lg font-bold text-sm hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <i
                  v-if="commentLoading"
                  class="pi pi-spin pi-spinner mr-1"
                  style="font-size: 0.8rem"
                ></i>
                发布评论
              </button>
            </div>
          </div>
        </div>

        <div class="space-y-6">
          <div v-for="comment in comments" :key="comment.id" class="flex gap-4">
            <img
              :src="comment.user_avatar"
              class="w-10 h-10 rounded-full bg-slate-100"
            />
            <div>
              <div class="flex items-center gap-2 mb-1">
                <span class="font-bold text-slate-900 text-sm">{{
                  comment.user_nickname
                }}</span>
                <span class="text-xs text-slate-400">{{
                  comment.create_time
                }}</span>
              </div>
              <p class="text-slate-700 text-sm leading-relaxed mb-2">
                {{ comment.content }}
              </p>
              <div class="flex items-center gap-4 text-xs text-slate-400">
                <button
                  @click="likeComment(comment)"
                  :disabled="comment.loading"
                  class="flex items-center gap-1 hover:text-red-500 transition-colors"
                  :class="{ 'text-red-500': comment.is_liked }"
                >
                  <i
                    class="pi"
                    :class="[
                      comment.loading
                        ? 'pi-spinner pi-spin'
                        : comment.is_liked
                          ? 'pi-thumbs-up-fill'
                          : 'pi-thumbs-up',
                    ]"
                  ></i>
                  <span>{{ comment.likes || 0 }}</span>
                </button>
                <button class="hover:text-slate-700">回复</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Sidebar (Right 3) - Sticky -->
    <div class="lg:col-span-3 space-y-6 sticky top-24 h-fit">
      <!-- Author Card -->
      <div
        class="bg-white rounded-xl shadow-sm border border-slate-100 p-6 text-center"
      >
        <div
          class="w-20 h-20 rounded-full border-4 border-slate-50 mx-auto -mt-10 mb-4 bg-white shadow-sm overflow-hidden"
        >
          <img
            :src="
              content.author_avatar ||
              `https://api.dicebear.com/7.x/avataaars/svg?seed=${content.author_id}`
            "
            class="w-full h-full object-cover"
          />
        </div>
        <h3 class="font-bold text-slate-900 text-lg">
          {{ content.author_name }}
        </h3>
        <div class="grid grid-cols-2 gap-3 mt-4">
          <button
            @click="toggleAuthorFollow"
            :disabled="authorFollowLoading"
            class="py-2 rounded-lg font-bold transition-colors flex items-center justify-center gap-1"
            :class="[
              authorIsFollowing
                ? 'bg-slate-100 text-slate-600 hover:bg-slate-200'
                : 'bg-primary-600 text-white hover:bg-primary-700 shadow-sm shadow-primary-200',
            ]"
          >
            <i
              class="pi"
              :class="[
                authorFollowLoading
                  ? 'pi-spin pi-spinner'
                  : authorIsFollowing
                    ? 'pi-check'
                    : 'pi-plus',
              ]"
            ></i>
            {{ authorIsFollowing ? "已关注" : "关注" }}
          </button>
          <button
            class="py-2 border border-slate-200 text-slate-700 rounded-lg font-bold hover:bg-slate-50"
            @click="toast.add({ severity: 'info', summary: '开发中' })"
          >
            私信
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
