// Shared article editor — used by Category (new) and Article (edit).
// Submits via window.KOL_STORE.upsertArticle / moveArticle.
// onSaved(article, catId) — receives the saved article and the (possibly new) category id.
const { useState: useStateAE, useEffect: useEffectAE } = React;

function todayISO_AE() { return new Date().toISOString().slice(0, 10); }

function ArticleEditor({ cat, article, mode, onClose, onSaved }) {
  const isNew = mode === "new";
  const [draft, setDraft] = useStateAE(() => ({
    catId:   cat?.id || (window.CATEGORIES[0]?.id || ""),
    id:      article?.id || "",
    title:   article?.title || "",
    lede:    article?.lede || "",
    updated: article?.updated || todayISO_AE(),
    readMin: article?.readMin || 5,
    markdown: article?.markdown || article?.body || "",
  }));
  const [err, setErr] = useStateAE("");

  useEffectAE(() => {
    if (!isNew) return;
    setDraft(d => ({ ...d, id: window.KOL_STORE.slugify(d.title) }));
  }, [draft.title, isNew]);

  function save() {
    if (!draft.title.trim()) return setErr("Title is required.");
    if (!draft.markdown.trim()) return setErr("Body is required.");
    if (!draft.catId) return setErr("Please select a category.");
    const id = (draft.id || window.KOL_STORE.slugify(draft.title)).trim();
    if (!id) return setErr("Could not derive an id from the title.");

    const targetCat = window.CATEGORIES.find(c => c.id === draft.catId);
    if (!targetCat) return setErr("Selected category not found.");

    // Collision check on create
    if (isNew && targetCat.articles.some(a => a.id === id)) {
      return setErr("An article with id '" + id + "' already exists in that category.");
    }

    const out = {
      id,
      title:   draft.title.trim(),
      lede:    draft.lede.trim(),
      updated: draft.updated || todayISO_AE(),
      readMin: Number(draft.readMin) || 5,
      markdown: draft.markdown,
    };

    if (!isNew && draft.catId !== cat.id) {
      // Moving to a different category
      window.KOL_STORE.moveArticle(cat.id, out, draft.catId);
    } else {
      window.KOL_STORE.upsertArticle(draft.catId, out);
    }

    onSaved?.(out, draft.catId);
    onClose?.();
  }

  return (
    <div className="session-editor" style={{ marginBottom: 28 }}>
      <h3>{isNew ? "New article" : `Editing: ${article.title}`}</h3>

      <div className="field">
        <label>Category</label>
        <select value={draft.catId} onChange={e => setDraft({ ...draft, catId: e.target.value })}>
          {window.CATEGORIES.map(c => (
            <option key={c.id} value={c.id}>{c.title}</option>
          ))}
        </select>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 140px 100px", gap: 10 }}>
        <div className="field">
          <label>Title</label>
          <input value={draft.title} onChange={e => setDraft({ ...draft, title: e.target.value })} placeholder="e.g. Picking a hypervisor" />
        </div>
        <div className="field">
          <label>Updated</label>
          <input type="date" value={draft.updated} onChange={e => setDraft({ ...draft, updated: e.target.value })} />
        </div>
        <div className="field">
          <label>Read (min)</label>
          <input type="number" min="1" value={draft.readMin} onChange={e => setDraft({ ...draft, readMin: e.target.value })} />
        </div>
      </div>

      {isNew ? (
        <div className="field">
          <label>URL slug (id)</label>
          <input value={draft.id} onChange={e => setDraft({ ...draft, id: e.target.value.replace(/[^a-z0-9-]/gi, "-").toLowerCase() })} placeholder="auto-derived from title" />
        </div>
      ) : null}

      <div className="field">
        <label>Summary (one sentence)</label>
        <input value={draft.lede} onChange={e => setDraft({ ...draft, lede: e.target.value })} placeholder="Shown under the title and on cards." />
      </div>

      <div className="field">
        <label>Body — Markdown</label>
        <textarea
          value={draft.markdown}
          onChange={e => setDraft({ ...draft, markdown: e.target.value })}
          placeholder={`Opening paragraph.\n\n## A heading\n\n- bullet\n- bullet\n\nMore prose with **bold**, _italic_, [a link](https://example.com), and \`inline code\`.`}
          style={{ minHeight: 240, fontFamily: "var(--font-mono)", fontSize: 13 }}
        />
      </div>

      {err ? <div className="modal-err" style={{ marginBottom: 10 }}>{err}</div> : null}

      <div className="row">
        <button className="btn" onClick={save}>{isNew ? "Create article" : "Save changes"}</button>
        <button className="btn ghost" onClick={onClose}>Cancel</button>
      </div>
    </div>
  );
}

window.KOL_PAGES.ArticleEditor = ArticleEditor;
