"use client";

import { useEffect, useState } from "react";
import ShareButtons from "@/components/blog/ShareButtons";

type BlogSidebarProps = {
  post: {
    title: string;
    excerpt?: string;
    slug?: string;
  };
};
export default function BlogSidebar({ post }: BlogSidebarProps) {
  const [email, setEmail] = useState("");
  const [status, setStatus] =
    useState<"idle" | "loading" | "success" | "error">("idle");

  // ✅ timestamp in SECONDS, set on mount
  const [timestamp, setTimestamp] = useState("");

  useEffect(() => {
    setTimestamp(Math.floor(Date.now() / 1000).toString());
  }, []);

  async function handleSubscribe(e: React.FormEvent) {
    e.preventDefault();
    setStatus("loading");

    try {
      const res = await fetch(
        "https://www.togwe.com/backend/wp-json/mc4wp/v1/form",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: new URLSearchParams({
            EMAIL: email,
            _mc4wp_form_id: "8527",
            _mc4wp_timestamp: timestamp,
            _mc4wp_honeypot: "", // ✅ correct name
          }),
        }
      );

      if (!res.ok) throw new Error("Spam blocked");

      setStatus("success");
      setEmail("");
    } catch {
      setStatus("error");
    }
  }

  return (
    <aside className="space-y-[30px]">
      {/* SHARE */}
      <ShareButtons
        title={post.title}
        summary={(post.excerpt || "").replace(/(<([^>]+)>)/gi, "")}
        siteOrigin={process.env.NEXT_PUBLIC_SITE_URL}
      />

      {/* SUBSCRIBE */}
      <div className="p-[30px] rounded-xl bg-white border border-[#202020]/15">
        <h4 className="text-lg text-[#202020] font-medium mb-4">Join 1,000,000+ subscribers receiving expert tips on earning more, investing smarter and living better, all in our free newsletter.</h4>
        <form onSubmit={handleSubscribe}>
          <input
            type="email"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="Enter your email"
            className="w-full h-[56px] border px-4 py-2 rounded mb-3 bg-[#F3F3F3] border-[#ffffff]/15 focus:outline-none focus:ring-0 focus:ring-[#F3F3F3] text-[#202020] text-[16px]"
          />
          {/* ✅ Correct honeypot */}
          <input
            type="text"
            name="_mc4wp_honeypot"
            value=""
            readOnly
            className="hidden"
          />
          <button 
            disabled={status === "loading"}
            className="bg-[#202020] text-white py-2 px-4 rounded cursor-pointer h-[48px] text-lg font-medium hover:bg-black transition">
              {status === "loading" ? "Subscribing..." : "Subscribe"}
          </button>
          {status === "success" && (
            <p className="text-green-600 mt-3">
              ✅ Thanks for subscribing!
            </p>
          )}

          {status === "error" && (
            <p className="text-red-600 mt-3">
              ❌ Please wait 5 seconds and try again
            </p>
          )}
        </form>
      </div>
    </aside>
  );
}
