"use client";

import { useEffect, useState } from "react";

type Site = {
  title: string;
  description: string;
  keywords: string;
  ogTitle: string;
  ogDescription: string;
  siteName: string;
  headerCode: string;
  bodyCode: string;
  footerCode: string;
};

export default function AdminSeoPage() {
  const [seo, setSeo] = useState<Site | null>(null);
  const [msg, setMsg] = useState("");

  useEffect(() => {
    fetch("/api/admin/seo")
      .then((r) => r.json())
      .then((j) => setSeo(j.seo));
  }, []);

  async function save(e: React.FormEvent) {
    e.preventDefault();
    if (!seo) return;
    const res = await fetch("/api/admin/seo", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(seo),
    });
    const json = await res.json();
    if (!res.ok) {
      setMsg(json.error || "Save failed");
      return;
    }
    setSeo(json.seo);
    setMsg("Saved. Reload the public site to see header, body, and footer code.");
  }

  if (!seo) return <p className="px-4 py-16 text-sm text-forest/60">Loading website settings…</p>;

  const fields: { key: keyof Site; label: string; area?: boolean }[] = [
    { key: "siteName", label: "Site name" },
    { key: "title", label: "Default title" },
    { key: "description", label: "Meta description", area: true },
    { key: "keywords", label: "Keywords (comma separated)", area: true },
    { key: "ogTitle", label: "Open Graph title" },
    { key: "ogDescription", label: "Open Graph description", area: true },
  ];

  const codeFields: { key: keyof Site; label: string; hint: string }[] = [
    {
      key: "headerCode",
      label: "Header code",
      hint: "Goes in <head>. Meta tags, CSS, Google Tag Manager head snippet, pixels.",
    },
    {
      key: "bodyCode",
      label: "Body code",
      hint: "Goes at the top of <body>, above the site header. Banners, announcement HTML, widgets.",
    },
    {
      key: "footerCode",
      label: "Footer code",
      hint: "Goes just before </body>. Analytics, chat widgets, extra scripts or HTML.",
    },
  ];

  return (
    <div className="mx-auto max-w-2xl px-4 py-10">
      <h1 className="font-display text-4xl text-forest">Website settings</h1>
      <p className="mt-2 text-sm text-forest/70">
        Update public titles here, or paste HTML and scripts into header, body, and footer when you
        need to change what the live site loads.
      </p>
      <form onSubmit={save} className="mt-8 space-y-8">
        <div className="space-y-4 rounded-3xl bg-cream p-6">
          <h2 className="font-display text-2xl text-forest">SEO</h2>
          {fields.map((f) => (
            <label key={f.key} className="block text-sm">
              {f.label}
              {f.area ? (
                <textarea
                  value={seo[f.key]}
                  onChange={(e) => setSeo({ ...seo, [f.key]: e.target.value })}
                  rows={3}
                  className="mt-1 w-full rounded-xl border border-forest/10 bg-white px-3 py-2 font-sans"
                />
              ) : (
                <input
                  value={seo[f.key]}
                  onChange={(e) => setSeo({ ...seo, [f.key]: e.target.value })}
                  className="mt-1 w-full rounded-xl border border-forest/10 bg-white px-3 py-2"
                />
              )}
            </label>
          ))}
        </div>

        <div className="space-y-4 rounded-3xl bg-cream p-6">
          <h2 className="font-display text-2xl text-forest">Header, body &amp; footer code</h2>
          <p className="text-sm text-forest/70">
            Paste HTML, CSS, or JavaScript. Scripts will run on the public site. Use this for pixels,
            banners, or swapping in extra content without a deploy.
          </p>
          {codeFields.map((f) => (
            <label key={f.key} className="block text-sm">
              {f.label}
              <span className="mt-0.5 block text-xs text-forest/50">{f.hint}</span>
              <textarea
                value={seo[f.key]}
                onChange={(e) => setSeo({ ...seo, [f.key]: e.target.value })}
                rows={8}
                spellCheck={false}
                className="mt-2 w-full rounded-xl border border-forest/10 bg-white px-3 py-2 font-mono text-xs leading-relaxed"
                placeholder="<!-- paste code here -->"
              />
            </label>
          ))}
        </div>

        <button className="rounded-full bg-forest px-5 py-2.5 text-sm font-semibold text-gold-2">
          Save website settings
        </button>
        {msg ? <p className="text-sm text-forest">{msg}</p> : null}
      </form>
    </div>
  );
}
