/*
 * VOISACE Blog / News & Insights page
 * - Public: lists published posts with category filter
 * - Admin panel (owner-only): create / edit / delete posts
 * - Full i18n via useLanguage()
 */
import { useState, useEffect, useCallback } from "react";
import { Link } from "wouter";
import Navigation from "@/components/Navigation";
import Footer from "@/components/Footer";
import { useLanguage } from "@/contexts/LanguageContext";
import { useMetaTags } from "@/hooks/useMetaTags";
import { useBreadcrumb } from "@/hooks/useBreadcrumb";
import { useJsonLd } from "@/hooks/useJsonLd";
import { BlogPost, BLOG_CATEGORIES } from "@shared/blog";
import { trackBlogArticleClick } from "@/lib/analytics";

// ─── Admin secret (stored in sessionStorage for the session) ────────────────
const ADMIN_KEY = "voisace_blog_admin";

function getAdminSecret(): string {
  return sessionStorage.getItem(ADMIN_KEY) || "";
}

// ─── API helpers ─────────────────────────────────────────────────────────────
async function apiFetch(path: string, opts?: RequestInit) {
  const res = await fetch(path, opts);
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: res.statusText }));
    throw new Error(err.error || "Request failed");
  }
  return res.json();
}

// ─── Category badge colours ──────────────────────────────────────────────────
const CATEGORY_COLORS: Record<string, string> = {
  Technical: "bg-blue-500/15 text-blue-300 border-blue-500/20",
  "Product Update": "bg-[#2EEEA0]/15 text-[#2EEEA0] border-[#2EEEA0]/20",
  "Industry Insights": "bg-purple-500/15 text-purple-300 border-purple-500/20",
  "Case Study": "bg-amber-500/15 text-amber-300 border-amber-500/20",
  "Company News": "bg-pink-500/15 text-pink-300 border-pink-500/20",
};

function CategoryBadge({ category }: { category: string }) {
  const cls = CATEGORY_COLORS[category] || "bg-gray-500/15 text-gray-300 border-gray-500/20";
  return (
    <span className={`inline-block text-[10px] font-bold uppercase tracking-widest px-2.5 py-1 rounded border ${cls}`}>
      {category}
    </span>
  );
}

// ─── Post card ───────────────────────────────────────────────────────────────
function readingTime(text: string): number {
  const words = text.trim().split(/\s+/).length;
  return Math.max(1, Math.round(words / 200));
}

function PostCard({ post, t, onEdit, onDelete, isAdmin }: {
  post: BlogPost;
  t: ReturnType<typeof useLanguage>["t"];
  onEdit?: (p: BlogPost) => void;
  onDelete?: (id: string) => void;
  isAdmin: boolean;
}) {
  const date = new Date(post.publishedAt).toLocaleDateString(undefined, {
    year: "numeric", month: "long", day: "numeric",
  });
  const mins = readingTime((post.content || "") + " " + (post.excerpt || ""));

  return (
    <article className="group relative bg-[#0D1220] border border-white/8 rounded-2xl overflow-hidden hover:border-[#2EEEA0]/30 flex flex-col" style={{ transition: 'transform 220ms cubic-bezier(0.23,1,0.32,1), box-shadow 220ms cubic-bezier(0.23,1,0.32,1), border-color 220ms cubic-bezier(0.23,1,0.32,1)' }} onMouseEnter={e => { (e.currentTarget as HTMLElement).style.transform = 'translateY(-4px)'; (e.currentTarget as HTMLElement).style.boxShadow = '0 12px 32px rgba(46,238,160,0.12)'; }} onMouseLeave={e => { (e.currentTarget as HTMLElement).style.transform = ''; (e.currentTarget as HTMLElement).style.boxShadow = ''; }}>
      {/* Cover image or gradient placeholder */}
      {post.coverUrl ? (
        <img src={post.coverUrl} alt={post.title} className="w-full h-48 object-cover" />
      ) : (
        <div className="w-full h-48 bg-gradient-to-br from-[#0A0E1A] via-[#0D1220] to-[#1a2035] flex items-center justify-center">
          <div className="w-16 h-16 rounded-full bg-[#2EEEA0]/10 border border-[#2EEEA0]/20 flex items-center justify-center">
            <svg className="w-7 h-7 text-[#2EEEA0]/60" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 12h6m-6-4h2" />
            </svg>
          </div>
        </div>
      )}

      <div className="p-6 flex flex-col flex-1">
        <div className="flex items-center justify-between mb-3">
          <CategoryBadge category={post.category} />
          {!post.published && (
            <span className="text-[10px] font-bold uppercase tracking-widest px-2 py-0.5 rounded bg-yellow-500/15 text-yellow-400 border border-yellow-500/20">{t.blog.blogDraft}</span>
          )}
        </div>

        <h3 className="text-white font-bold text-lg leading-snug mb-2 group-hover:text-[#2EEEA0] transition-colors duration-200" style={{ fontFamily: "'Space Grotesk', sans-serif" }}>
          {post.title}
        </h3>

        <p className="text-gray-400 text-sm leading-relaxed flex-1 mb-3 line-clamp-3">
          {post.excerpt}
        </p>

        <div className="flex items-center justify-between mt-auto pt-4 border-t border-white/6">
          <div className="text-xs text-gray-500 flex items-center gap-2">
            <span>{t.blog.publishedOn} </span>
            <span className="text-gray-400">{date}</span>
            <span className="text-white/20">·</span>
            <span className="text-gray-500 flex items-center gap-1">
              <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              {mins} {t.blog.minRead}
            </span>
          </div>
          <div className="flex items-center gap-2">
            {isAdmin && onEdit && onDelete && (
              <>
                <button
                  onClick={(e) => { e.preventDefault(); onEdit(post); }}
                  className="text-xs text-gray-400 hover:text-[#2EEEA0] transition-colors px-2 py-1 rounded border border-white/10 hover:border-[#2EEEA0]/30"
                >
                  {t.blog.adminEditPost}
                </button>
                <button
                  onClick={(e) => { e.preventDefault(); onDelete(post.id); }}
                  className="text-xs text-red-400 hover:text-red-300 transition-colors px-2 py-1 rounded border border-red-500/20 hover:border-red-400/40"
                >
                  {t.blog.adminDelete}
                </button>
              </>
            )}
            <Link href={`/blog/${post.slug}`} className="text-xs font-semibold text-[#2EEEA0] hover:text-white transition-colors flex items-center gap-1" onClick={() => trackBlogArticleClick(post.slug)}>
              {t.blog.readMore}
              <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
            </Link>
          </div>
        </div>

        {/* Tags at bottom */}
        {post.tags && post.tags.length > 0 && (
          <div className="flex flex-wrap gap-1.5 mt-4 pt-4 border-t border-white/6">
            {post.tags.slice(0, 3).map((tag) => (
              <Link
                key={tag}
                href={`/blog?tag=${encodeURIComponent(tag)}`}
                onClick={(e) => e.stopPropagation()}
                className="text-[10px] font-medium px-2 py-0.5 rounded-full bg-white/5 text-gray-400 border border-white/8 hover:bg-blue-500/15 hover:text-blue-300 hover:border-blue-500/30 transition-all duration-150"
              >
                #{tag}
              </Link>
            ))}
          </div>
        )}
      </div>
    </article>
  );
}

// ─── Admin post editor modal ─────────────────────────────────────────────────
const EMPTY_POST: Partial<BlogPost> = {
  title: "", slug: "", excerpt: "", content: "", coverUrl: "",
  category: "Technical", author: "VOISACE Engineering",
  publishedAt: new Date().toISOString().slice(0, 10),
  published: true,
};

function AdminEditor({
  post, onClose, onSaved, t,
}: {
  post: Partial<BlogPost> | null;
  onClose: () => void;
  onSaved: () => void;
  t: ReturnType<typeof useLanguage>["t"];
}) {
  const [form, setForm] = useState<Partial<BlogPost>>(post || EMPTY_POST);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  const isEdit = !!form.id;

  const handleSave = async (published: boolean) => {
    setSaving(true);
    setError("");
    try {
      const payload = { ...form, published };
      const secret = getAdminSecret();
      if (isEdit) {
        await apiFetch(`/api/blog/${form.id}`, {
          method: "PUT",
          headers: { "Content-Type": "application/json", "x-admin-secret": secret },
          body: JSON.stringify(payload),
        });
      } else {
        await apiFetch("/api/blog", {
          method: "POST",
          headers: { "Content-Type": "application/json", "x-admin-secret": secret },
          body: JSON.stringify(payload),
        });
      }
      onSaved();
      onClose();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setSaving(false);
    }
  };

  const set = (key: keyof BlogPost, val: string | boolean) =>
    setForm((f: Partial<BlogPost>) => ({ ...f, [key]: val }));

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm" onClick={onClose}>
      <div className="bg-[#0D1220] border border-white/12 rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto shadow-2xl" onClick={(e) => e.stopPropagation()}>
        <div className="p-6 border-b border-white/8 flex items-center justify-between">
          <h2 className="text-white font-bold text-xl" style={{ fontFamily: "'Space Grotesk', sans-serif" }}>
            {isEdit ? t.blog.adminEditPost : t.blog.adminNewPost}
          </h2>
          <button onClick={onClose} className="text-gray-400 hover:text-white transition-colors text-2xl leading-none">&times;</button>
        </div>

        <div className="p-6 space-y-4">
          {error && (
            <div className="bg-red-500/10 border border-red-500/20 rounded-lg px-4 py-3 text-red-400 text-sm">{error}</div>
          )}

          <div>
            <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">{t.blog.adminTitle}</label>
            <input
              value={form.title || ""}
              onChange={(e) => set("title", e.target.value)}
              className="w-full bg-[#0A0E1A] border border-white/10 rounded-lg px-4 py-2.5 text-white text-sm focus:outline-none focus:border-[#2EEEA0]/50"
            />
          </div>

          <div>
            <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">{t.blog.adminSlug}</label>
            <input
              value={form.slug || ""}
              onChange={(e) => set("slug", e.target.value)}
              className="w-full bg-[#0A0E1A] border border-white/10 rounded-lg px-4 py-2.5 text-white text-sm focus:outline-none focus:border-[#2EEEA0]/50 font-mono"
              placeholder="my-post-slug"
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">{t.blog.adminCategory}</label>
              <select
                value={form.category || "Technical"}
                onChange={(e) => set("category", e.target.value)}
                className="w-full bg-[#0A0E1A] border border-white/10 rounded-lg px-4 py-2.5 text-white text-sm focus:outline-none focus:border-[#2EEEA0]/50"
              >
                {BLOG_CATEGORIES.map((c) => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">{t.blog.blogAuthorLabel}</label>
              <input
                value={form.author || ""}
                onChange={(e) => set("author", e.target.value)}
                className="w-full bg-[#0A0E1A] border border-white/10 rounded-lg px-4 py-2.5 text-white text-sm focus:outline-none focus:border-[#2EEEA0]/50"
              />
            </div>
          </div>

          <div>
            <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">{t.blog.adminExcerpt}</label>
            <textarea
              value={form.excerpt || ""}
              onChange={(e) => set("excerpt", e.target.value)}
              rows={2}
              className="w-full bg-[#0A0E1A] border border-white/10 rounded-lg px-4 py-2.5 text-white text-sm focus:outline-none focus:border-[#2EEEA0]/50 resize-none"
            />
          </div>

          <div>
            <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">{t.blog.adminCoverUrl}</label>
            <input
              value={form.coverUrl || ""}
              onChange={(e) => set("coverUrl", e.target.value)}
              className="w-full bg-[#0A0E1A] border border-white/10 rounded-lg px-4 py-2.5 text-white text-sm focus:outline-none focus:border-[#2EEEA0]/50"
              placeholder="https://..."
            />
          </div>

          <div>
            <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">{t.blog.adminContent}</label>
            <textarea
              value={form.content || ""}
              onChange={(e) => set("content", e.target.value)}
              rows={12}
              className="w-full bg-[#0A0E1A] border border-white/10 rounded-lg px-4 py-2.5 text-white text-sm focus:outline-none focus:border-[#2EEEA0]/50 resize-y font-mono"
              placeholder="# Heading&#10;&#10;Your content in Markdown..."
            />
          </div>
        </div>

        <div className="p-6 border-t border-white/8 flex items-center justify-end gap-3">
          <button onClick={onClose} className="px-4 py-2 text-sm text-gray-400 hover:text-white border border-white/10 rounded-lg transition-colors">
            {t.blog.blogCancel}
          </button>
          <button
            onClick={() => handleSave(false)}
            disabled={saving}
            className="px-4 py-2 text-sm text-gray-300 border border-white/15 rounded-lg hover:border-white/30 transition-colors disabled:opacity-50"
          >
            {saving ? t.blog.adminSaving : t.blog.adminSaveDraft}
          </button>
          <button
            onClick={() => handleSave(true)}
            disabled={saving}
            className="px-5 py-2 text-sm font-bold btn-teal rounded-lg disabled:opacity-50 transition-opacity"
          >
            {saving ? t.blog.adminSaving : t.blog.adminPublish}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Admin login modal ────────────────────────────────────────────────────────
function AdminLogin({ onClose, onLogin }: { onClose: () => void; onLogin: () => void }) {
  const [secret, setSecret] = useState("");
  const [error, setError] = useState("");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!secret.trim()) { setError("Please enter the admin secret."); return; }
    // Validate by fetching admin listing with the secret header
    try {
      const res = await fetch("/api/blog?admin=1", {
        headers: { "x-admin-secret": secret },
      });
      if (!res.ok) throw new Error("Forbidden");
      sessionStorage.setItem(ADMIN_KEY, secret);
      onLogin();
      onClose();
    } catch {
      setError("Invalid secret. Please try again.");
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm" onClick={onClose}>
      <form
        onSubmit={handleSubmit}
        className="bg-[#0D1220] border border-white/12 rounded-2xl w-full max-w-sm p-6 shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        <h2 className="text-white font-bold text-xl mb-4" style={{ fontFamily: "'Space Grotesk', sans-serif" }}>Admin Access</h2>
        {error && <div className="text-red-400 text-sm mb-3">{error}</div>}
        <input
          type="password"
          value={secret}
          onChange={(e) => setSecret(e.target.value)}
          placeholder="Admin secret"
          className="w-full bg-[#0A0E1A] border border-white/10 rounded-lg px-4 py-2.5 text-white text-sm mb-4 focus:outline-none focus:border-[#2EEEA0]/50"
          autoFocus
        />
        <div className="flex gap-3">
          <button type="button" onClick={onClose} className="flex-1 px-4 py-2 text-sm text-gray-400 border border-white/10 rounded-lg">Cancel</button>
          <button type="submit" className="flex-1 px-4 py-2 text-sm font-bold btn-teal rounded-lg">Login</button>
        </div>
      </form>
    </div>
  );
}

// ─── Main Blog page ───────────────────────────────────────────────────────────
export default function Blog() {
  const { t } = useLanguage();
  useMetaTags({
    title: "Acoustic AI Blog — Voice Technology Insights",
    description: "Technical articles, case studies, and industry insights on embedded acoustic AI, voice enhancement, AEC, beamforming, and edge audio processing.",
    image: "https://d2xsxph8kpxj0f.cloudfront.net/310519663679102940/5SUvwiDeUfPstxb2NvLAKJ/og-blog-listing-dQsLNSTiuXfEoNgrdQxeFx.webp",
  });

  useBreadcrumb([
    { name: "VOISACE", url: "/" },
    { name: t.blog.pageTitle, url: "/blog" },
  ]);

  const [posts, setPosts] = useState<BlogPost[]>([]);

  // Blog + ItemList JSON-LD — updates whenever published posts change
  useJsonLd(
    {
      "@context": "https://schema.org",
      "@type": "Blog",
      "name": "VOISACE Blog & Insights",
      "url": "https://www.voisace.com/blog",
      "description": "Technical articles, case studies and industry insights on embedded acoustic AI, voice enhancement and edge audio processing.",
      "publisher": {
        "@type": "Organization",
        "name": "VOISACE",
        "url": "https://www.voisace.com"
      },
      "blogPost": posts
        .filter((p) => p.published)
        .slice(0, 20)
        .map((p) => ({
          "@type": "BlogPosting",
          "headline": p.title,
          "description": p.excerpt,
          "url": `https://www.voisace.com/blog/${p.slug}`,
          "datePublished": new Date(p.publishedAt).toISOString(),
          "author": {
            "@type": "Person",
            "name": p.author || "VOISACE"
          },
          "image": p.coverUrl || undefined,
          "articleSection": p.category
        }))
    },
    [posts]
  );
  const [loading, setLoading] = useState(true);
  const [activeCategory, setActiveCategory] = useState<string>("All");
  const [activeTag, setActiveTag] = useState<string | null>(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("tag") || null;
  });
  const [searchQuery, setSearchQuery] = useState("");
  const [isAdmin, setIsAdmin] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  const [editingPost, setEditingPost] = useState<Partial<BlogPost> | null>(null);
  const [showEditor, setShowEditor] = useState(false);

  const fetchPosts = useCallback(async () => {
    setLoading(true);
    try {
      const secret = getAdminSecret();
      const admin = isAdmin && secret ? "?admin=1" : "";
      const headers: Record<string, string> = {};
      if (isAdmin && secret) headers["x-admin-secret"] = secret;
      const data = await apiFetch(`/api/blog${admin}`, { headers });
      setPosts(data);
    } catch {
      setPosts([]);
    } finally {
      setLoading(false);
    }
  }, [isAdmin]);

  useEffect(() => { fetchPosts(); }, [fetchPosts]);

  const handleDelete = async (id: string) => {
    if (!confirm(t.blog.adminConfirmDelete)) return;
    try {
      await apiFetch(`/api/blog/${id}`, {
        method: "DELETE",
        headers: { "x-admin-secret": getAdminSecret() },
      });
      fetchPosts();
    } catch (e: any) {
      alert(e.message);
    }
  };

  const categories = ["All", ...Array.from(new Set(posts.map((p) => p.category)))];
  const allTags = Array.from(new Set(posts.flatMap((p) => p.tags || []))).sort();
  const filtered = posts.filter((p) => {
    const matchesCategory = activeCategory === "All" || p.category === activeCategory;
    const matchesTag = !activeTag || (p.tags || []).includes(activeTag);
    const q = searchQuery.trim().toLowerCase();
    const matchesSearch = !q ||
      p.title.toLowerCase().includes(q) ||
      p.excerpt.toLowerCase().includes(q) ||
      p.category.toLowerCase().includes(q) ||
      (p.author || "").toLowerCase().includes(q) ||
      (p.tags || []).some((tag) => tag.toLowerCase().includes(q));
    return matchesCategory && matchesTag && matchesSearch;
  });

  return (
    <div className="min-h-screen bg-[#060A14] text-white">
      <Navigation />

      {/* Hero */}
      <section className="pt-40 pb-16 px-4 relative overflow-hidden">
        <div className="absolute inset-0 pointer-events-none">
          <div className="absolute top-0 left-1/4 w-96 h-96 bg-[#2EEEA0]/4 rounded-full blur-3xl" />
          <div className="absolute bottom-0 right-1/4 w-64 h-64 bg-blue-500/4 rounded-full blur-3xl" />
        </div>
        <div className="max-w-7xl mx-auto relative">
          <div className="flex items-center justify-between mb-6">
            <p className="text-[#2EEEA0] text-xs font-bold uppercase tracking-[0.25em]" style={{ fontFamily: "'Space Mono', monospace" }}>
              {t.blog.pageTagline}
            </p>
            {/* Admin toggle */}
            <div className="flex items-center gap-2">
              {isAdmin ? (
                <>
                  <button
                    onClick={() => { setEditingPost({ ...EMPTY_POST }); setShowEditor(true); }}
                    className="px-4 py-2 text-xs font-bold btn-teal rounded-lg flex items-center gap-1.5"
                  >
                    <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                    </svg>
                    {t.blog.adminNewPost}
                  </button>
                  <button
                    onClick={() => { setIsAdmin(false); sessionStorage.removeItem(ADMIN_KEY); }}
                    className="px-3 py-2 text-xs text-gray-400 border border-white/10 rounded-lg hover:text-white transition-colors"
                  >
                    Exit Admin
                  </button>
                </>
              ) : (
                <button
                  onClick={() => setShowLogin(true)}
                  className="text-xs text-gray-600 hover:text-gray-400 transition-colors"
                  title="Admin login"
                >
                  ···
                </button>
              )}
            </div>
          </div>

          <h1 className="text-5xl sm:text-6xl font-black text-white mb-4" style={{ fontFamily: "'Space Grotesk', sans-serif" }}>
            {t.blog.pageTitle}
          </h1>
          <p className="text-gray-400 text-lg max-w-2xl mb-8">
            {t.blog.pageSubtitle}
          </p>
          {/* Search bar + RSS link */}
          <div className="flex items-center gap-3 max-w-lg">
          <div className="relative flex-1">
            <svg className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 pointer-events-none" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0" />
            </svg>
            <input
              type="search"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder={t.blog.searchPlaceholder || "Search articles…"}
              className="w-full bg-[#0D1220] border border-white/10 rounded-xl pl-11 pr-4 py-3 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-[#2EEEA0]/50 transition-colors"
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery("")}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white transition-colors"
                aria-label={t.blog.blogClearSearch}
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            )}
          </div>
          {/* RSS Feed link */}
          <a
            href="/feed.xml"
            target="_blank"
            rel="noopener noreferrer"
            title="Subscribe via RSS"
            className="flex-shrink-0 flex items-center justify-center w-10 h-10 rounded-xl border border-white/10 text-gray-500 hover:text-orange-400 hover:border-orange-400/40 hover:bg-orange-400/5 transition-all duration-200"
            aria-label="RSS Feed"
          >
            <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
              <path d="M6.18 15.64a2.18 2.18 0 0 1 2.18 2.18C8.36 19.01 7.38 20 6.18 20C4.98 20 4 19.01 4 17.82a2.18 2.18 0 0 1 2.18-2.18M4 4.44A15.56 15.56 0 0 1 19.56 20h-2.83A12.73 12.73 0 0 0 4 7.27V4.44m0 5.66a9.9 9.9 0 0 1 9.9 9.9h-2.83A7.07 7.07 0 0 0 4 12.93V10.1z" />
            </svg>
          </a>
          </div>
        </div>
      </section>

      {/* Posts grid */}
      <section className="pb-24 px-4">
        <div className="max-w-7xl mx-auto">
          {loading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {[1, 2, 3].map((i) => (
                <div key={i} className="bg-[#0D1220] border border-white/8 rounded-2xl h-80 animate-pulse" />
              ))}
            </div>
          ) : filtered.length === 0 ? (
            <div className="text-center py-24">
              <div className="w-16 h-16 rounded-full bg-[#2EEEA0]/10 border border-[#2EEEA0]/20 flex items-center justify-center mx-auto mb-4">
                <svg className="w-7 h-7 text-[#2EEEA0]/50" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 12h6m-6-4h2" />
                </svg>
              </div>
              <h3 className="text-white font-bold text-xl mb-2" style={{ fontFamily: "'Space Grotesk', sans-serif" }}>{t.blog.noPostsTitle}</h3>
              <p className="text-gray-500">{t.blog.noPostsText}</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filtered.map((post) => (
                <PostCard
                  key={post.id}
                  post={post}
                  t={t}
                  isAdmin={isAdmin}
                  onEdit={(p) => { setEditingPost(p); setShowEditor(true); }}
                  onDelete={handleDelete}
                />
              ))}
            </div>
          )}
        </div>
      </section>

      {/* Category filter + Tag filter */}
      <section className="pb-8 px-4 border-t border-white/6 pt-8">
        <div className="max-w-7xl mx-auto space-y-3">
          {/* Category chips */}
          <div className="flex flex-wrap gap-2">
            {categories.map((cat) => (
              <button
                key={cat}
                onClick={() => setActiveCategory(cat)}
                className={`px-4 py-1.5 text-xs font-semibold rounded-full border transition-all duration-200 ${
                  activeCategory === cat
                    ? "bg-[#2EEEA0] text-[#060A14] border-[#2EEEA0]"
                    : "text-gray-400 border-white/10 hover:border-white/25 hover:text-white"
                }`}
              >
                {cat}
              </button>
            ))}
          </div>
          {/* Tag chips */}
          {allTags.length > 0 && (
            <div className="flex flex-wrap gap-2 items-center">
              <span className="text-[10px] font-bold uppercase tracking-widest text-gray-600 mr-1">{t.blog.blogTagsLabel}</span>
              {allTags.map((tag) => (
                <button
                  key={tag}
                  onClick={() => setActiveTag(activeTag === tag ? null : tag)}
                  className={`px-3 py-1 text-[11px] font-medium rounded-full border transition-all duration-200 ${
                    activeTag === tag
                      ? "bg-blue-500/20 text-blue-300 border-blue-500/40"
                      : "text-gray-500 border-white/8 hover:border-white/20 hover:text-gray-300"
                  }`}
                >
                  #{tag}
                </button>
              ))}
              {activeTag && (
                <button
                  onClick={() => setActiveTag(null)}
                  className="text-[11px] text-gray-500 hover:text-white transition-colors ml-1 flex items-center gap-1"
                >
                  <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                  {t.blog.blogClearTag}
                </button>
              )}
            </div>
          )}
        </div>
      </section>

      {/* CTA */}
      <section className="py-20 px-4 bg-gradient-to-b from-[#060A14] to-[#0A0E1A] border-t border-white/6">
        <div className="max-w-3xl mx-auto text-center">
          <h2 className="text-3xl font-black text-white mb-3" style={{ fontFamily: "'Space Grotesk', sans-serif" }}>{t.blog.ctaTitle}</h2>
          <p className="text-gray-400 mb-8">{t.blog.ctaSubtitle}</p>
          <Link href="/contact" className="inline-block px-8 py-3.5 font-bold btn-teal rounded-xl text-sm">
            {t.blog.ctaBtn}
          </Link>
        </div>
      </section>

      <Footer />

      {/* Modals */}
      {showLogin && (
        <AdminLogin
          onClose={() => setShowLogin(false)}
          onLogin={() => setIsAdmin(true)}
        />
      )}
      {showEditor && (
        <AdminEditor
          post={editingPost}
          onClose={() => { setShowEditor(false); setEditingPost(null); }}
          onSaved={fetchPosts}
          t={t}
        />
      )}
    </div>
  );
}
