import React, { useEffect, useState } from "react";
import { api } from "./api.js";
import { Spinner } from "./ui.jsx";

export default function PronunciationEditor({ slug }) {
  const [entries, setEntries] = useState(null);
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    api.getPron(slug).then((d) => setEntries(d.entries || []));
  }, [slug]);

  if (entries === null) return <p className="text-ink-muted"><Spinner /> chargement…</p>;

  const dirty = () => setSaved(false);
  const setRow = (i, patch) => {
    setEntries(entries.map((e, j) => (j === i ? { ...e, ...patch } : e)));
    dirty();
  };
  const add = () => { setEntries([...entries, { term: "", replacement: "", enabled: true }]); dirty(); };
  const remove = (i) => { setEntries(entries.filter((_, j) => j !== i)); dirty(); };
  const save = async () => {
    await api.putPron(slug, { entries: entries.filter((e) => e.term) });
    setSaved(true);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <p className="text-sm text-ink-muted">
          Corrigez la graphie des mots mal prononcés. La colonne « prononciation » remplace le terme avant la synthèse.
        </p>
        <button className="btn-ghost ml-auto" onClick={add}>+ ajouter</button>
        <button className="btn-primary" onClick={save}>{saved ? "✓ enregistré" : "Enregistrer"}</button>
      </div>

      {entries.length === 0 ? (
        <p className="text-ink-muted">Aucune entrée. Lancez l'étape <b>Prononciations</b> ou ajoutez-en.</p>
      ) : (
        <div className="card divide-y divide-ink-edge">
          <div className="grid grid-cols-[1fr_1fr_auto_auto] gap-3 px-4 py-2 text-xs uppercase text-ink-muted">
            <span>Terme</span><span>Prononciation</span><span>Actif</span><span></span>
          </div>
          {entries.map((e, i) => (
            <div key={i} className="grid grid-cols-[1fr_1fr_auto_auto] items-center gap-3 px-4 py-2">
              <input className="input" value={e.term}
                onChange={(ev) => setRow(i, { term: ev.target.value })} />
              <input className="input" value={e.replacement}
                onChange={(ev) => setRow(i, { replacement: ev.target.value })} />
              <input type="checkbox" checked={e.enabled !== false}
                onChange={(ev) => setRow(i, { enabled: ev.target.checked })} />
              <button className="text-ink-muted hover:text-red-400" onClick={() => remove(i)}>✕</button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
