"use client";

import { useState } from "react";
import { BlogSmiley } from "./BlogSmiley";

type State = "idle" | "error" | "loading" | "done";

export function BlogNewsletter() {
  const [email, setEmail] = useState("");
  const [company, setCompany] = useState(""); // honeypot — bots fill it, humans don't
  const [state, setState] = useState<State>("idle");
  const [toast, setToast] = useState(false);

  const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

  const showToast = () => {
    setToast(true);
    setTimeout(() => setToast(false), 4000);
  };

  const handleSubmit = async (e: { preventDefault(): void }) => {
    e.preventDefault();
    if (!isValid) {
      setState("error");
      return;
    }

    setState("loading");
    try {
      const res = await fetch("/api/newsletter", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, company }),
      });
      if (!res.ok) throw new Error();
      setState("done");
      showToast();
    } catch {
      setState("error");
    }
  };

  return (
    <>
      {/* Success toast */}
      {toast && (
        <div
          style={{
            position: "fixed",
            bottom: 88,
            left: "50%",
            transform: "translateX(-50%)",
            zIndex: 9999,
            background: "#16161a",
            color: "#f4efe1",
            padding: "14px 22px",
            borderRadius: 999,
            display: "flex",
            alignItems: "center",
            gap: 10,
            fontSize: 15,
            fontWeight: 600,
            boxShadow: "0 8px 32px rgba(0,0,0,0.32)",
            whiteSpace: "nowrap",
            animation: "b-fadeUp 0.35s cubic-bezier(0.16,1,0.3,1) both",
          }}
        >
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <circle cx="12" cy="12" r="10" fill="#2d5bff" />
            <path
              d="m8 12 3 3 5-5"
              stroke="#fff"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          You&apos;re subscribed! Check your inbox.
        </div>
      )}

      <section className="b-nl">
        <div className="b-wrap">
          <div className="b-nl-inner">
            {/* Left: copy */}
            <div>
              <span
                className="b-kicker"
                style={{ color: "var(--b-on-dark-soft)" }}
              >
                <span className="b-dot" /> The DesignShare dispatch
              </span>
              <h2 className="b-nl-heading">
                Design notes,{" "}
                <span className="b-serif" style={{ fontWeight: 500 }}>
                  weekly.
                </span>
              </h2>
              <p className="b-nl-sub">
                Teardowns, conversion experiments, and what we learn shipping
                315+ products. No fluff, one email a week.
              </p>
            </div>

            {/* Right: form */}
            <div>
              {state === "done" ? (
                <div className="b-nl-success">
                  <BlogSmiley size={42} />
                  <div>
                    <div className="b-nl-success-title">
                      You&rsquo;re on the list.
                    </div>
                    <div className="b-nl-success-sub">
                      First dispatch lands this Thursday.
                    </div>
                  </div>
                </div>
              ) : (
                <form onSubmit={handleSubmit}>
                  {/* Honeypot: hidden from users, catches bots */}
                  <input
                    type="text"
                    name="company"
                    value={company}
                    onChange={(e) => setCompany(e.target.value)}
                    tabIndex={-1}
                    autoComplete="off"
                    aria-hidden="true"
                    style={{
                      position: "absolute",
                      left: "-9999px",
                      width: 1,
                      height: 1,
                      opacity: 0,
                    }}
                  />
                  <div
                    className={`b-nl-form${state === "error" ? " error" : ""}`}
                  >
                    <input
                      type="email"
                      value={email}
                      placeholder="you@company.com"
                      disabled={state === "loading"}
                      onChange={(e) => {
                        setEmail(e.target.value);
                        if (state === "error") setState("idle");
                      }}
                    />
                    <button
                      type="submit"
                      className="b-btn"
                      disabled={state === "loading"}
                      style={{
                        flexShrink: 0,
                        opacity: state === "loading" ? 0.7 : 1,
                      }}
                    >
                      {state === "loading" ? (
                        <>
                          <svg
                            width="16"
                            height="16"
                            viewBox="0 0 24 24"
                            fill="none"
                            style={{ animation: "spin 0.8s linear infinite" }}
                          >
                            <circle
                              cx="12"
                              cy="12"
                              r="10"
                              stroke="rgba(255,255,255,0.3)"
                              strokeWidth="2.5"
                            />
                            <path
                              d="M12 2a10 10 0 0 1 10 10"
                              stroke="#fff"
                              strokeWidth="2.5"
                              strokeLinecap="round"
                            />
                          </svg>
                          Sending…
                        </>
                      ) : (
                        <>
                          Subscribe <span className="b-arrow">→</span>
                        </>
                      )}
                    </button>
                  </div>
                  <div className="b-nl-hint">
                    {state === "error" ? (
                      <span className="b-nl-hint-err">
                        Please enter a valid email address.
                      </span>
                    ) : (
                      <span className="b-nl-hint-ok">
                        Join 4,200+ founders &amp; designers. Unsubscribe
                        anytime.
                      </span>
                    )}
                  </div>
                </form>
              )}
            </div>
          </div>
        </div>
      </section>

      <style>{`
        @keyframes spin { to { transform: rotate(360deg); } }
      `}</style>
    </>
  );
}
