"use client";

import { useEffect, useState } from "react";

// R15 C.12: thin client wrapper for blog-post interactions. Markdown is
// server-rendered (see blog-post-markdown.tsx) — this only hosts the TOC
// scroll-spy reading from the DOM, the copy-link button, and the
// view-count POST.

interface TocItem {
  id: string;
  text: string;
  level: number;
}

export function BlogPostContent({ slug, postUrl }: { slug: string; postUrl: string }) {
  const [toc, setToc] = useState<TocItem[]>([]);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    fetch(`/api/blog-posts/${slug}/views`, { method: "POST" }).catch(() => {});
  }, [slug]);

  useEffect(() => {
    const timer = setTimeout(() => {
      const article = document.querySelector("[data-blog-content]");
      if (!article) return;
      const headings = article.querySelectorAll("h2, h3");
      const items: TocItem[] = [];
      headings.forEach((heading) => {
        const id =
          heading.id ||
          heading.textContent?.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "") ||
          "";
        if (!heading.id) heading.id = id;
        items.push({
          id,
          text: heading.textContent || "",
          level: heading.tagName === "H2" ? 2 : 3,
        });
      });
      setToc(items);
    }, 100);
    return () => clearTimeout(timer);
  }, []);

  const handleCopyLink = () => {
    navigator.clipboard.writeText(postUrl).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  return (
    <>
      {toc.length > 2 && (
        <nav className="lg:hidden bg-surface rounded-lg p-4 mb-8">
          <h3 className="text-sm font-semibold mb-3 text-text-muted uppercase tracking-wide">
            Table of Contents
          </h3>
          <ul className="space-y-1">
            {toc.map((item) => (
              <li key={item.id} style={{ paddingLeft: item.level === 3 ? "1rem" : 0 }}>
                <a
                  href={`#${item.id}`}
                  className="text-sm text-text-muted hover:text-primary transition-colors block py-0.5"
                >
                  {item.text}
                </a>
              </li>
            ))}
          </ul>
        </nav>
      )}

      <div className="lg:hidden mb-6">
        <button
          onClick={handleCopyLink}
          className="text-sm text-text-muted hover:text-primary transition-colors flex items-center gap-2"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"
            />
          </svg>
          {copied ? "Copied!" : "Copy link"}
        </button>
      </div>

      <div className="hidden lg:block fixed bottom-8 right-8">
        <button
          onClick={handleCopyLink}
          className="bg-surface hover:bg-surface-light text-text-muted hover:text-primary px-4 py-2 rounded-lg text-sm transition-colors shadow-lg flex items-center gap-2"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"
            />
          </svg>
          {copied ? "Copied!" : "Copy link"}
        </button>
      </div>
    </>
  );
}
