"use client";

import { useState } from "react";

export default function ContentEditor({ page, data }: any) {
  const [content, setContent] = useState(data?.content || {});

  const updateField = (lang: string, field: string, value: string) => {
    setContent({
      ...content,
      [lang]: {
        ...content?.[lang],
        [field]: value,
      },
    });
  };

  const save = async () => {
    await fetch(`/api/content/${page}`, {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(content),
    });

    alert("Saved !");
  };

  return (
    <div className="space-y-6 max-w-2xl">
      {["fr", "en"].map((lang) => (
        <div key={lang} className="border p-4 rounded">
          <h2 className="font-bold mb-2">{lang.toUpperCase()}</h2>

          <input
            className="border p-2 w-full mb-2"
            placeholder="title"
            value={content?.[lang]?.title || ""}
            onChange={(e) =>
              updateField(lang, "title", e.target.value)
            }
          />

          <textarea
            className="border p-2 w-full"
            placeholder="content"
            value={content?.[lang]?.content || ""}
            onChange={(e) =>
              updateField(lang, "content", e.target.value)
            }
          />
        </div>
      ))}

      <button
        onClick={save}
        className="bg-black text-white px-4 py-2"
      >
        Save
      </button>
    </div>
  );
}