/* ============================================================================
   CONTENT AGENT — pestaña CONTENIDO (Mission 2 · Fase 1).

   Vista local de transformación idea → pieza. Cero red, cero IA externa.
   Lee/escribe únicamente sobre state.content (namespace aislado).

   CSS namespace: cta-*  (Content Agent)
   Notas:
     - "ca-*" estaba ocupado por el modal Custom Agents en agents.css.
       Renombrado a "cta-*" para evitar colisión de cascada.
     - IIFE wrap mandatory: `const { useState } = React;` collisions occur
       if left at file top — Babel standalone evaluates every <script
       type="text/babel"> in the same global realm.
============================================================================ */
(function () {
  "use strict";

  const { useState, useEffect, useMemo, useCallback } = React;

  // ---------- guard: required globals ----------
  function MissingDeps() {
    return (
      <div style={{ padding: 24, color: "#ffb47e", fontFamily: "Inter, sans-serif" }}>
        Falta cargar window.MissionState o window.ContentTemplates.
      </div>
    );
  }

  // ---------- format / tone metadata ----------
  const FORMATS = [
    { id: "hook",     label: "Hook",     hint: "Apertura potente, 1–2 líneas." },
    { id: "caption",  label: "Caption",  hint: "Texto fluido, 3–6 líneas." },
    { id: "carousel", label: "Carrusel", hint: "3–7 slides numeradas." },
    { id: "story",    label: "Story",    hint: "Narrativo breve, 2–4 líneas." },
  ];

  const TONES = [
    { id: "directa",   label: "Directa" },
    { id: "emocional", label: "Emocional" },
    { id: "educativa", label: "Educativa" },
    { id: "resumida",  label: "Resumida" },
  ];

  function formatLabel(id) { const f = FORMATS.find(x => x.id === id); return f ? f.label : id; }
  function toneLabel(id)   { const t = TONES.find(x => x.id === id);   return t ? t.label   : id; }

  function formatRelative(iso) {
    if (!iso) return "";
    const t = Date.parse(iso);
    if (!isFinite(t)) return "";
    const diff = Date.now() - t;
    const min = Math.floor(diff / 60000);
    if (min < 1)  return "ahora";
    if (min < 60) return "hace " + min + " min";
    const h = Math.floor(min / 60);
    if (h < 24)   return "hace " + h + " h";
    const d = Math.floor(h / 24);
    return "hace " + d + " d";
  }

  // ============================================================================
  // OUTPUT RENDERERS
  // ============================================================================
  function HookView({ output }) {
    const lines = (output && output.lines) || [];
    return (
      <div className="cta-out-hook">
        {lines.map((l, i) => <div key={i} className="cta-out-hook-line">{l}</div>)}
      </div>
    );
  }

  function CaptionView({ output }) {
    const paragraphs = (output && output.paragraphs) || [];
    return (
      <div className="cta-out-caption">
        {paragraphs.map((p, i) => <p key={i} className="cta-out-caption-p">{p}</p>)}
      </div>
    );
  }

  function CarouselView({ output }) {
    const slides = (output && output.slides) || [];
    return (
      <div className="cta-out-carousel">
        {slides.map((s, i) => (
          <div key={i} className="cta-out-slide">
            <div className="cta-out-slide-head">
              <span className="cta-out-slide-num">
                {String(s.index || (i + 1)).padStart(2, "0")}
              </span>
              <span className="cta-out-slide-title">{s.title}</span>
            </div>
            {s.body ? <div className="cta-out-slide-body">{s.body}</div> : null}
          </div>
        ))}
      </div>
    );
  }

  function StoryView({ output }) {
    return (
      <div className="cta-out-story">
        <div className="cta-out-story-bar" aria-hidden="true"></div>
        <div className="cta-out-story-text">{output && output.text}</div>
      </div>
    );
  }

  function OutputRenderer({ output }) {
    if (!output || !output.kind) return null;
    if (output.kind === "hook")     return <HookView     output={output} />;
    if (output.kind === "caption")  return <CaptionView  output={output} />;
    if (output.kind === "carousel") return <CarouselView output={output} />;
    if (output.kind === "story")    return <StoryView    output={output} />;
    return null;
  }

  // ============================================================================
  // EMPTY STATE
  // ============================================================================
  function EmptyOutput({ format, tone }) {
    return (
      <div className="cta-empty">
        <div className="cta-empty-icon" aria-hidden="true">◇</div>
        <div className="cta-empty-eyebrow">SALIDA</div>
        <div className="cta-empty-title">Sin pieza generada todavía</div>
        <div className="cta-empty-hint">
          Escribe una idea, elige formato y tono, y pulsa <strong>GENERAR</strong>.
        </div>
        <div className="cta-empty-meta">
          <span>Formato: <strong>{formatLabel(format)}</strong></span>
          <span className="cta-empty-sep">·</span>
          <span>Tono: <strong>{toneLabel(tone)}</strong></span>
        </div>
      </div>
    );
  }

  // ============================================================================
  // DRAFT STRIP
  // ============================================================================
  function DraftCard({ draft, onClick }) {
    const ideaPreview = (draft.idea || "").slice(0, 80);
    return (
      <button type="button" className="cta-draft-card" onClick={onClick} title="Cargar este draft">
        <div className="cta-draft-meta">
          <span className="cta-draft-fmt">{formatLabel(draft.format)}</span>
          <span className="cta-draft-dot" aria-hidden="true">·</span>
          <span className="cta-draft-tone">{toneLabel(draft.activeTone || draft.tone)}</span>
          <span className="cta-draft-when">{formatRelative(draft.updatedAt || draft.createdAt)}</span>
        </div>
        <div className="cta-draft-text">
          {ideaPreview}{(draft.idea || "").length > 80 ? "…" : ""}
        </div>
      </button>
    );
  }

  function DraftsBar({ drafts, open, onToggle, onLoad }) {
    const sorted = useMemo(() => {
      return drafts.slice().sort((a, b) =>
        String(b.updatedAt || b.createdAt || "").localeCompare(String(a.updatedAt || a.createdAt || ""))
      );
    }, [drafts]);

    const cls = "cta-drafts-bar" + (open ? " cta-drafts-bar--open" : "");

    return (
      <div className={cls}>
        <button type="button" className="cta-drafts-toggle" onClick={onToggle} aria-expanded={open}>
          <span className="cta-drafts-caret" aria-hidden="true">{open ? "▾" : "▸"}</span>
          <span className="cta-drafts-label">DRAFTS RECIENTES</span>
          <span className="cta-drafts-count">{drafts.length}</span>
        </button>
        {open ? (
          <div className="cta-drafts-list">
            {sorted.length === 0 ? (
              <div className="cta-drafts-empty">
                Aún no has guardado ningún draft. Genera una pieza y pulsa “Guardar draft”.
              </div>
            ) : (
              sorted.map(d => <DraftCard key={d.id} draft={d} onClick={() => onLoad(d.id)} />)
            )}
          </div>
        ) : null}
      </div>
    );
  }

  // ============================================================================
  // MAIN APP
  // ============================================================================
  function ContentAgentApp() {
    const MS  = window.MissionState;
    const TPL = window.ContentTemplates;

    // ---- inputs ----
    const initial = MS.getContent ? MS.getContent() : { lastIdea: "", lastFormat: "hook", lastTone: "directa" };
    const [idea,   setIdea]   = useState(initial.lastIdea   || "");
    const [format, setFormat] = useState(initial.lastFormat || "hook");
    const [tone,   setTone]   = useState(initial.lastTone   || "directa");

    // ---- working draft (in-memory until "Guardar draft") ----
    // shape: { id?, idea, format, activeTone, variants: { tone: { output, variantIndex } } }
    const [working, setWorking] = useState(null);

    // ---- transient UI state ----
    const [error,  setError]  = useState("");
    const [notice, setNotice] = useState("");

    // ---- drafts list (subscribed) ----
    const [drafts, setDrafts] = useState(MS.getContentDrafts ? MS.getContentDrafts() : []);
    const [draftsOpen, setDraftsOpen] = useState(false);

    useEffect(() => {
      if (!MS.subscribe) return;
      const unsub = MS.subscribe((s, evt) => {
        if (!evt) return;
        if (evt.type && evt.type.indexOf("content") === 0) {
          setDrafts(MS.getContentDrafts ? MS.getContentDrafts().slice() : []);
        }
      });
      return unsub;
    }, []);

    // Persist last inputs when they change.
    useEffect(() => {
      if (!MS.setContentInputs) return;
      MS.setContentInputs({ lastIdea: idea, lastFormat: format, lastTone: tone });
    }, [idea, format, tone]);

    // Auto-clear notices.
    useEffect(() => {
      if (!notice) return;
      const t = setTimeout(() => setNotice(""), 1800);
      return () => clearTimeout(t);
    }, [notice]);

    useEffect(() => {
      if (!error) return;
      const t = setTimeout(() => setError(""), 3500);
      return () => clearTimeout(t);
    }, [error]);

    // ---------- helpers ----------
    const trimmedLen = idea.trim().length;
    const canGenerate = trimmedLen >= TPL.MIN_IDEA_LEN;

    function flash(msg) { setNotice(msg); }
    function fail(msg)  { setError(msg); }

    // ---------- actions ----------
    const onGenerate = useCallback(() => {
      const result = TPL.generate({ idea, format, tone, variantIndex: 0 });
      if (!result.ok) { fail(result.reason); return; }
      setWorking({
        id: null,
        idea: idea.trim(),
        format: format,
        activeTone: tone,
        variants: { [tone]: { output: result.output, variantIndex: result.variantIndex } },
      });
      setError("");
    }, [idea, format, tone, TPL]);

    const onRegenerate = useCallback(() => {
      if (!working) return;
      const current = working.variants[working.activeTone];
      const nextIdx = ((current && current.variantIndex) || 0) + 1;
      const result = TPL.generate({
        idea: working.idea,
        format: working.format,
        tone: working.activeTone,
        variantIndex: nextIdx,
      });
      if (!result.ok) { fail(result.reason); return; }
      const nextVariants = Object.assign({}, working.variants, {
        [working.activeTone]: { output: result.output, variantIndex: result.variantIndex },
      });
      const next = Object.assign({}, working, { variants: nextVariants });
      setWorking(next);
      if (next.id && MS.updateContentDraft) {
        MS.updateContentDraft(next.id, { variants: next.variants });
      }
      flash("Variante regenerada");
    }, [working, TPL, MS]);

    const onPickTone = useCallback((nextTone) => {
      setTone(nextTone);
      if (!working) return;
      if (working.variants[nextTone]) {
        setWorking(Object.assign({}, working, { activeTone: nextTone }));
        return;
      }
      const result = TPL.generate({
        idea: working.idea,
        format: working.format,
        tone: nextTone,
        variantIndex: 0,
      });
      if (!result.ok) { fail(result.reason); return; }
      const nextVariants = Object.assign({}, working.variants, {
        [nextTone]: { output: result.output, variantIndex: result.variantIndex },
      });
      const next = Object.assign({}, working, { activeTone: nextTone, variants: nextVariants });
      setWorking(next);
      if (next.id && MS.updateContentDraft) {
        MS.updateContentDraft(next.id, { variants: next.variants });
      }
      flash("Variante " + toneLabel(nextTone) + " generada");
    }, [working, TPL, MS]);

    const onSaveDraft = useCallback(() => {
      if (!working) return;
      if (working.id && MS.updateContentDraft) {
        MS.updateContentDraft(working.id, {
          idea: working.idea,
          format: working.format,
          activeTone: working.activeTone,
          variants: working.variants,
        });
        flash("Draft actualizado");
        return;
      }
      if (!MS.addContentDraft) return;
      const saved = MS.addContentDraft({
        idea: working.idea,
        format: working.format,
        activeTone: working.activeTone,
        variants: working.variants,
      });
      if (saved) {
        setWorking(Object.assign({}, working, { id: saved.id }));
        flash("Draft guardado");
      }
    }, [working, MS]);

    const onCopy = useCallback(() => {
      if (!working) return;
      const v = working.variants[working.activeTone];
      const text = TPL.serialize(v && v.output);
      if (!text) { fail("Nada que copiar."); return; }
      const tryClipboard = (txt) => {
        try { return navigator.clipboard.writeText(txt); }
        catch (e) { return null; }
      };
      const p = tryClipboard(text);
      if (p && typeof p.then === "function") {
        p.then(() => flash("Copiado al portapapeles"))
         .catch(() => fail("No se pudo copiar al portapapeles."));
      } else {
        try {
          const ta = document.createElement("textarea");
          ta.value = text;
          ta.style.position = "fixed"; ta.style.opacity = "0";
          document.body.appendChild(ta);
          ta.select();
          const ok2 = document.execCommand("copy");
          document.body.removeChild(ta);
          if (ok2) flash("Copiado al portapapeles");
          else fail("No se pudo copiar.");
        } catch (e) { fail("No se pudo copiar."); }
      }
    }, [working, TPL]);

    const onLoadDraft = useCallback((id) => {
      const d = MS.getContentDraftById ? MS.getContentDraftById(id) : null;
      if (!d) return;
      setIdea(d.idea || "");
      setFormat(d.format || "hook");
      const activeTone = d.activeTone || "directa";
      setTone(activeTone);
      setWorking({
        id: d.id,
        idea: d.idea || "",
        format: d.format || "hook",
        activeTone: activeTone,
        variants: d.variants && typeof d.variants === "object" ? d.variants : {},
      });
      setDraftsOpen(false);
      flash("Draft cargado");
    }, [MS]);

    // ---------- render ----------
    const activeOutput = working && working.variants[working.activeTone]
      ? working.variants[working.activeTone].output
      : null;

    const headerCount = drafts.length === 1 ? "1 draft guardado" : drafts.length + " drafts guardados";

    return (
      <div className="cta-shell">
        {/* HEADER */}
        <div className="cta-header">
          <div className="cta-header-titlebox">
            <span className="cta-header-eyebrow">CONTENT AGENT · FLUJO LOCAL</span>
            <div className="cta-header-titlerow">
              <span className="cta-header-title">CONTENIDO</span>
              <span
                className="cta-header-phase"
                title="Generación local por reglas. Sin red, sin API externa."
              >
                <span className="cta-header-phase-dot" aria-hidden="true"></span>
                Fase 1 · Local / Demo
              </span>
            </div>
            <span className="cta-header-sub">
              Flujo validado: idea → pieza → draft. Cerebro real pendiente para fase posterior.
            </span>
          </div>
          <div className="cta-header-meta">
            <span className="cta-header-led" aria-hidden="true"></span>
            <span className="cta-header-status">Listo</span>
            <span className="cta-header-pipe" aria-hidden="true">|</span>
            <span className="cta-header-count">{headerCount}</span>
          </div>
        </div>

        {/* MAIN — two-column */}
        <div className="cta-main">
          {/* LEFT — entrada */}
          <section className="cta-input-col" aria-label="Entrada">
            <div className="cta-section-eyebrow">ENTRADA</div>

            <div className="cta-field">
              <label className="cta-field-label" htmlFor="cta-idea">Idea base</label>
              <textarea
                id="cta-idea"
                className="cta-textarea"
                placeholder="¿Qué quieres comunicar? Una frase clara basta. Ej: «construir un agente local te enseña más sobre disciplina que cualquier curso»."
                value={idea}
                onChange={(e) => setIdea(e.target.value.slice(0, TPL.MAX_IDEA_LEN))}
                maxLength={TPL.MAX_IDEA_LEN}
                rows={6}
                spellCheck={true}
              />
              <div className="cta-field-foot">
                <span className={"cta-field-counter" + (canGenerate ? "" : " cta-field-counter--low")}>
                  {trimmedLen} / {TPL.MAX_IDEA_LEN}
                </span>
                {!canGenerate ? (
                  <span className="cta-field-hint">mínimo {TPL.MIN_IDEA_LEN} caracteres</span>
                ) : null}
              </div>
            </div>

            <div className="cta-field">
              <span className="cta-field-label">Formato</span>
              <div className="cta-chip-group">
                {FORMATS.map(f => (
                  <button
                    type="button"
                    key={f.id}
                    className={"cta-chip" + (format === f.id ? " cta-chip--active" : "")}
                    onClick={() => setFormat(f.id)}
                    title={f.hint}
                  >{f.label}</button>
                ))}
              </div>
            </div>

            <div className="cta-field">
              <span className="cta-field-label">Tono</span>
              <div className="cta-chip-group">
                {TONES.map(t => (
                  <button
                    type="button"
                    key={t.id}
                    className={"cta-chip" + (tone === t.id ? " cta-chip--active" : "")}
                    onClick={() => setTone(t.id)}
                  >{t.label}</button>
                ))}
              </div>
            </div>

            <button
              type="button"
              className="cta-generate-btn"
              onClick={onGenerate}
              disabled={!canGenerate}
              title={canGenerate ? "Generar pieza" : "Escribe al menos " + TPL.MIN_IDEA_LEN + " caracteres"}
            >
              <span className="cta-generate-icon" aria-hidden="true">▶</span>
              <span>GENERAR</span>
            </button>

            {error ? <div className="cta-error" role="alert">{error}</div> : null}
          </section>

          {/* RIGHT — salida */}
          <section className="cta-output-col" aria-label="Salida">
            {!working ? (
              <div className="cta-output-inner">
                <div className="cta-section-eyebrow cta-section-eyebrow--right">SALIDA</div>
                <EmptyOutput format={format} tone={tone} />
              </div>
            ) : (
              <div className="cta-output-inner">
                <div className="cta-out-header">
                  <div className="cta-out-headline">
                    <span className="cta-out-fmt">{formatLabel(working.format)}</span>
                    <span className="cta-out-sep" aria-hidden="true">·</span>
                    <span className="cta-out-tone">Tono {toneLabel(working.activeTone)}</span>
                  </div>
                  <div className="cta-out-id">
                    {working.id ? "Draft " + working.id : "Sin guardar"}
                  </div>
                </div>

                <div className="cta-out-body">
                  <OutputRenderer output={activeOutput} />
                </div>

                <div className="cta-variant-tabs" role="tablist" aria-label="Variantes de tono">
                  {TONES.map(t => {
                    const exists = !!working.variants[t.id];
                    const active = working.activeTone === t.id;
                    const cls =
                      "cta-vt" +
                      (active ? " cta-vt--active" : "") +
                      (exists ? " cta-vt--exists" : "");
                    return (
                      <button
                        type="button"
                        key={t.id}
                        role="tab"
                        aria-selected={active}
                        className={cls}
                        onClick={() => onPickTone(t.id)}
                        title={exists ? "Mostrar variante " + t.label : "Generar variante " + t.label}
                      >
                        {exists ? <span className="cta-vt-dot" aria-hidden="true">●</span> : null}
                        <span className="cta-vt-label">{t.label}</span>
                      </button>
                    );
                  })}
                </div>

                <div className="cta-action-row">
                  <button type="button" className="cta-action cta-action--primary" onClick={onSaveDraft}>
                    {working.id ? "✓ Actualizar draft" : "✓ Guardar draft"}
                  </button>
                  <button type="button" className="cta-action" onClick={onCopy}>⧉ Copiar</button>
                  <button type="button" className="cta-action" onClick={onRegenerate}>↻ Regenerar</button>
                  <button
                    type="button"
                    className="cta-action"
                    onClick={() => {
                      const cur = TONES.findIndex(t => t.id === working.activeTone);
                      const next = TONES[(cur + 1) % TONES.length];
                      onPickTone(next.id);
                    }}
                    title="Genera o muestra el siguiente tono"
                  >↳ Variar tono</button>
                </div>

                {notice ? <div className="cta-notice" role="status">{notice}</div> : null}
              </div>
            )}
          </section>
        </div>

        {/* DRAFTS BAR */}
        <DraftsBar
          drafts={drafts}
          open={draftsOpen}
          onToggle={() => setDraftsOpen(v => !v)}
          onLoad={onLoadDraft}
        />
      </div>
    );
  }

  // ---------- mount ----------
  function mount() {
    const root = document.getElementById("content-react-root");
    if (!root) return;
    if (!window.MissionState || !window.ContentTemplates) {
      ReactDOM.createRoot(root).render(<MissingDeps />);
      return;
    }
    ReactDOM.createRoot(root).render(<ContentAgentApp />);
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", mount);
  } else {
    mount();
  }
})();
