// Admin panel — novel writer for TROOPER.
// Terminology: ARCOS (top-level) → CAPÍTULOS (inside arcs).
// Shares localStorage with the reader via window.NovelStore.

const { useState, useEffect, useRef } = React;

function AdminPanel({ user }) {
  const [storeRaw, setStoreRaw] = window.NovelStore.useNovelStore();
  // Normalize defensively in case the store ever lacks arcs/cards. The crash
  // we hit ("store.arcs is undefined") suggests something upstream returns a
  // partial object — guard here too so admin can never blank the screen.
  const store = {
    arcs: Array.isArray(storeRaw?.arcs) ? storeRaw.arcs : [],
    cards: Array.isArray(storeRaw?.cards) ? storeRaw.cards : [],
    characters: Array.isArray(storeRaw?.characters) ? storeRaw.characters : [],
  };
  const setStore = (next) => setStoreRaw({
    arcs: Array.isArray(next?.arcs) ? next.arcs : [],
    cards: Array.isArray(next?.cards) ? next.cards : [],
    characters: [],
  });
  if (typeof window !== "undefined") {
    // Helpful when chasing future "undefined" bugs.
    window.__adminLastStore = storeRaw;
  }
  const [view, setView] = useState("structure"); // structure | timeline | cards
  const [activeChapterId, setActiveChapterId] = useState(null);
  const [newArcTitle, setNewArcTitle] = useState("");

  // Find active chapter + its arc
  const findChapter = (id) => {
    for (const a of store.arcs) {
      const c = a.chapters.find(c => c.id === id);
      if (c) return { arc: a, chapter: c };
    }
    return null;
  };
  const active = activeChapterId ? findChapter(activeChapterId) : null;

  const update = (patch) => setStore({ ...store, ...patch });
  const updateArcs = (arcs) => update({ arcs });

  const addArc = () => {
    const i = store.arcs.length;
    const p = window.NovelStore.preset(i);
    const title = newArcTitle.trim() || `ARCO ${window.NovelStore.pad2(i + 1)}`;
    const arc = {
      id: window.NovelStore.newId(),
      num: window.NovelStore.pad2(i + 1),
      title: title.toUpperCase(),
      subtitle: "",
      year: `ARCO · ${window.NovelStore.pad2(i + 1)}`,
      tagline: "",
      spine: p.spine,
      cover: p.cover,
      chapters: [],
    };
    updateArcs([...store.arcs, arc]);
    setNewArcTitle("");
  };

  const addChapter = (arcId) => {
    const arcs = store.arcs.map(a => {
      if (a.id !== arcId) return a;
      const num = window.NovelStore.pad2(a.chapters.length + 1);
      const c = {
        id: window.NovelStore.newId(),
        num,
        title: `Capítulo ${num}`,
        desc: "",
        duration: "",
        body: [],
        image: "",
      };
      return { ...a, chapters: [...a.chapters, c] };
    });
    updateArcs(arcs);
    const arc = arcs.find(a => a.id === arcId);
    setActiveChapterId(arc.chapters[arc.chapters.length - 1].id);
  };

  const updateChapter = (chapterId, patch) => {
    const arcs = store.arcs.map(a => ({
      ...a,
      chapters: a.chapters.map(c => c.id === chapterId ? { ...c, ...patch } : c),
    }));
    updateArcs(arcs);
  };

  const updateArc = (arcId, patch) => {
    updateArcs(store.arcs.map(a => a.id === arcId ? { ...a, ...patch } : a));
  };

  const deleteArc = (arcId) => {
    if (!confirm("¿Eliminar este ARCO y TODOS sus capítulos?")) return;
    updateArcs(store.arcs.filter(a => a.id !== arcId));
    if (active && active.arc.id === arcId) setActiveChapterId(null);
  };

  const deleteChapter = (chapterId) => {
    if (!confirm("¿Eliminar este capítulo?")) return;
    const arcs = store.arcs.map(a => ({
      ...a,
      chapters: a.chapters.filter(c => c.id !== chapterId),
    }));
    updateArcs(arcs);
    if (activeChapterId === chapterId) setActiveChapterId(null);
  };

  const moveArc = (arcId, dir) => {
    const i = store.arcs.findIndex(a => a.id === arcId);
    const j = i + dir;
    if (i < 0 || j < 0 || j >= store.arcs.length) return;
    const arcs = [...store.arcs];
    [arcs[i], arcs[j]] = [arcs[j], arcs[i]];
    updateArcs(arcs);
  };

  const moveChapter = (arcId, chapterId, dir) => {
    updateArcs(store.arcs.map(a => {
      if (a.id !== arcId) return a;
      const i = a.chapters.findIndex(c => c.id === chapterId);
      const j = i + dir;
      if (i < 0 || j < 0 || j >= a.chapters.length) return a;
      const chapters = [...a.chapters];
      [chapters[i], chapters[j]] = [chapters[j], chapters[i]];
      return { ...a, chapters };
    }));
  };

  // Drag-and-drop reorder
  const reorderChapters = (arcId, srcId, targetId) => {
    updateArcs(store.arcs.map(a => {
      if (String(a.id) !== String(arcId)) return a;
      const list = [...a.chapters];
      const srcIdx = list.findIndex(c => String(c.id) === String(srcId));
      const tgtIdx = list.findIndex(c => String(c.id) === String(targetId));
      if (srcIdx < 0 || tgtIdx < 0) return a;
      const [moved] = list.splice(srcIdx, 1);
      list.splice(tgtIdx, 0, moved);
      return { ...a, chapters: list };
    }));
  };

  const reorderArcs = (srcId, targetId) => {
    const list = [...store.arcs];
    const srcIdx = list.findIndex(a => String(a.id) === String(srcId));
    const tgtIdx = list.findIndex(a => String(a.id) === String(targetId));
    if (srcIdx < 0 || tgtIdx < 0) return;
    const [moved] = list.splice(srcIdx, 1);
    list.splice(tgtIdx, 0, moved);
    updateArcs(list);
  };

  // Move a chapter from one arc to another. targetChId=null → append at end.
  const moveChapterToArc = (srcArcId, srcChId, targetArcId, targetChId) => {
    const arcs = store.arcs.map(a => ({ ...a, chapters: [...a.chapters] }));
    const srcArc = arcs.find(a => String(a.id) === String(srcArcId));
    const tgtArc = arcs.find(a => String(a.id) === String(targetArcId));
    if (!srcArc || !tgtArc) return;
    const srcIdx = srcArc.chapters.findIndex(c => String(c.id) === String(srcChId));
    if (srcIdx < 0) return;
    const [moved] = srcArc.chapters.splice(srcIdx, 1);
    if (targetChId == null) {
      tgtArc.chapters.push(moved);
    } else {
      const tgtIdx = tgtArc.chapters.findIndex(c => String(c.id) === String(targetChId));
      if (tgtIdx < 0) tgtArc.chapters.push(moved);
      else tgtArc.chapters.splice(tgtIdx, 0, moved);
    }
    updateArcs(arcs);
  };

  const [draggingArcId, setDraggingArcId] = useState(null);
  const [dragOverArcId, setDragOverArcId] = useState(null);

  const handleArcDragStart = (e, arcId) => {
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.setData("text/plain", `arc:${arcId}`);
    setDraggingArcId(arcId);
  };
  const handleArcDragOver = (e, arcId) => {
    if (!e.dataTransfer.types.includes("text/plain")) return;
    // Only react to arc drags here, not chapter drags
    if (!draggingArcId) return;
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";
    setDragOverArcId(arcId);
  };
  const handleArcDrop = (e, arcId) => {
    if (!draggingArcId) return;
    e.preventDefault();
    const payload = e.dataTransfer.getData("text/plain");
    setDragOverArcId(null);
    setDraggingArcId(null);
    if (!payload.startsWith("arc:")) return;
    const srcId = payload.slice(4);
    if (String(srcId) === String(arcId)) return;
    reorderArcs(srcId, arcId);
  };

  return (
    <div className="admin-panel">
      <div className="admin-header">
        <div className="admin-header-left">
          <div className="admin-badge">LECTOR · ADMIN</div>
          <h1 className="admin-title-h">TROOPER NOVELA</h1>
        </div>
        <div className="admin-header-right">
          <button className={"admin-view-btn" + (view === "structure" ? " active" : "")} onClick={() => setView("structure")}>
            ESTRUCTURA
          </button>
          <button className={"admin-view-btn" + (view === "timeline" ? " active" : "")} onClick={() => setView("timeline")}>
            TIMELINE
          </button>
          <button className={"admin-view-btn" + (view === "cards" ? " active" : "")} onClick={() => setView("cards")}>
            CARTAS
          </button>
          <AdminExportMenu store={store} />
        </div>
      </div>

      {view === "cards" ? (
        <window.CardAdmin store={store} setStore={setStore} />
      ) : view === "structure" ? (
        <div className="admin-grid">
          <aside className="admin-sidebar">
            <div className="admin-section-title">ARCOS & CAPÍTULOS</div>
            <div className="admin-arcs-list">
              {store.arcs.map((arc, idx) => (
                <ArcRow
                  key={arc.id}
                  arc={arc}
                  idx={idx}
                  total={store.arcs.length}
                  activeChapterId={activeChapterId}
                  onSelectChapter={setActiveChapterId}
                  onAddChapter={() => addChapter(arc.id)}
                  onUpdateArc={(patch) => updateArc(arc.id, patch)}
                  onDeleteArc={() => deleteArc(arc.id)}
                  onDeleteChapter={deleteChapter}
                  onReorderChapters={reorderChapters}
                  onMoveChapterToArc={moveChapterToArc}
                  onArcDragStart={handleArcDragStart}
                  onArcDragOver={handleArcDragOver}
                  onArcDrop={handleArcDrop}
                  draggingArc={draggingArcId}
                  dragOverArc={dragOverArcId}
                />
              ))}
            </div>
            <div className="admin-new-arc">
              <input
                className="admin-input"
                placeholder="Nombre del arco"
                value={newArcTitle}
                onChange={(e) => setNewArcTitle(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && addArc()}
              />
              <button className="admin-add-btn" onClick={addArc}>+ NUEVO ARCO</button>
            </div>
          </aside>

          <main className="admin-main">
            {active ? (
              <ChapterEditor
                key={active.chapter.id}
                arc={active.arc}
                chapter={active.chapter}
                onChange={(patch) => updateChapter(active.chapter.id, patch)}
                onDelete={() => deleteChapter(active.chapter.id)}
              />
            ) : (
              <div className="admin-empty">
                <div className="admin-empty-icon">▣</div>
                <div className="admin-empty-title">SELECCIONA UN CAPÍTULO</div>
                <div className="admin-empty-sub">
                  Crea un arco, agrega capítulos y empieza a escribir.<br/>
                  Los arcos sin capítulos escritos no se muestran en el lector.
                </div>
              </div>
            )}
          </main>
        </div>
      ) : (
        <div className="admin-tl-wrap">
          <window.ReaderTimelineView
            arcs={store.arcs}
            readIds={new Set()}
            onRead={(chapter) => { setActiveChapterId(chapter.id); setView("structure"); }}
          />
        </div>
      )}
    </div>
  );
}

window.AdminPanel = AdminPanel;
