"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { isPaid } from "../lib/payment";

const CHAT_URL = "https://chatwoot.hackrobot.cn/livechat?user_id=hackrobot";

export function ChatFloatButton() {
  const [paid, setPaid] = useState(false);

  useEffect(() => {
    setPaid(isPaid());
    const onPayUpdate = () => setPaid(isPaid());
    window.addEventListener("pay:updated", onPayUpdate);
    return () => window.removeEventListener("pay:updated", onPayUpdate);
  }, []);

  const baseClass =
    "animate__animated animate__bounceIn fixed bottom-6 right-6 z-40 flex h-12 w-12 items-center justify-center rounded-full shadow-lg transition-all hover:scale-110";
  const paidClass = "bg-[var(--accent)] text-[var(--accent-foreground)] shadow-[var(--accent)]/30 hover:shadow-xl hover:shadow-[var(--accent)]/40";
  const lockedClass = "bg-[var(--accent)] text-[var(--accent-foreground)] shadow-[var(--accent)]/30 hover:shadow-xl hover:shadow-[var(--accent)]/40";

  if (paid) {
    return (
      <a
        href={CHAT_URL}
        target="_blank"
        rel="noopener noreferrer"
        className={`${baseClass} ${paidClass}`}
        style={{ animationDelay: "0.5s", animationFillMode: "both" }}
        aria-label="即时问答"
      >
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
        </svg>
      </a>
    );
  }

  return (
    <Link
      href="/"
      className={`${baseClass} ${lockedClass}`}
      style={{ animationDelay: "0.5s", animationFillMode: "both" }}
      aria-label="即时问答（开通VIP解锁）"
      title="开通VIP解锁即时问答"
    >
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
        <path d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
      </svg>
    </Link>
  );
}
