// ESTÚDIO — Páginas D: Baú de Ideias (captura → IA) + Prompts. Portadas do Lorenna OS.
(function () {
  const { useState } = React;
  const { PageHead, Card, PerfilTag } = window.UI;
  const h = React.createElement;

  // ══════════════════ BAÚ DE IDEIAS ══════════════════
  function BauDeIdeias({ energy }) {
    const [text, setText] = useState("");
    const [processing, setProcessing] = useState(false);
    const [result, setResult] = useState(null);
    const [history, setHistory] = useState([
      { id: "h1", raw: "preciso lembrar de pedir o boleto do Igor Giordano, e ainda tenho que escrever a newsletter dessa semana — quem sabe sobre IA?", date: "Há 2 dias", tarefas: 2, ideias: 1 },
      { id: "h2", raw: "domingo, 47 ideias, zero energia. boa pra um reel.", date: "Há 5 dias", tarefas: 0, ideias: 1 },
    ]);
    const e = (window.ENERGY && window.ENERGY[energy]) || { emoji: "🌸", label: "Criativa", desc: "Modo expansão.", color: "#FF78B0" };

    function processar() {
      if (!text.trim()) return;
      setProcessing(true); setResult(null);
      setTimeout(() => {
        const tarefas = [], ideias = [];
        text.split(/[\n.,;]/).map((s) => s.trim()).filter((s) => s.length > 8).forEach((s) => {
          if (/preciso|tenho que|fazer|criar|escrever|entregar|enviar|gravar|agendar|responder/i.test(s)) tarefas.push(s[0].toUpperCase() + s.slice(1));
          else if (/ideia|seria legal|podia|pensei|série|reel|post|frase|carrossel/i.test(s)) ideias.push(s[0].toUpperCase() + s.slice(1));
        });
        if (!tarefas.length && !ideias.length) ideias.push(text.trim()[0].toUpperCase() + text.trim().slice(1));
        setResult({ tarefas, ideias, resumo: tarefas.length + " tarefa(s), " + ideias.length + " ideia(s) — bagunça organizada." });
        setProcessing(false);
      }, 900);
    }
    function salvar() {
      setHistory((p) => [{ id: Math.random().toString(36).slice(2), raw: text, date: "Agora", tarefas: result.tarefas.length, ideias: result.ideias.length }, ...p]);
      setText(""); setResult(null);
    }

    return h("div", { className: "page narrow" },
      h(PageHead, { titulo: "Baú de Ideias", sub: "Joga tudo aqui. Pensamento bagunçado, ideia solta, to-do. A IA organiza." }),
      h(Card, { className: "cap-card" },
        h("div", { className: "cap-strip", style: { background: e.color } }),
        h("div", { className: "cap-body" },
          h("div", { className: "cap-mode" }, h("span", { style: { fontSize: 16 } }, e.emoji), h("span", null, "Modo ", h("b", null, e.label), " — ", e.desc)),
          h("textarea", { className: "cap-textarea", value: text, onChange: (ev) => setText(ev.target.value), placeholder: "Pode começar de qualquer forma…\n\n“Preciso criar o roteiro do reel de branding, mas antes tenho que entregar os posts da academia essa semana. Ah, tive uma ideia sobre análise de marcas no TikTok…”", onKeyDown: (ev) => { if ((ev.metaKey || ev.ctrlKey) && ev.key === "Enter") processar(); } }),
          h("div", { className: "cap-foot" },
            h("span", { className: "cap-hint" }, "⌘ + Enter"),
            h("button", { className: "btn-pink", onClick: processar, disabled: !text.trim() || processing }, processing ? "Processando…" : "✨ Processar com IA")
          )
        )
      ),
      result && h(Card, { className: "cap-result" },
        h("div", { className: "cap-result-head" },
          h("div", { className: "psec-t", style: { margin: 0 } }, "⚡ Resultado da IA"),
          h("button", { className: "btn-pink sm", onClick: salvar }, "✓ Salvar tudo")
        ),
        h("p", { className: "cap-resumo" }, "“" + result.resumo + "”"),
        h("div", { className: "cap-cols" },
          h("div", null, h("div", { className: "mini-label" }, "⚡ " + result.tarefas.length + " tarefa(s)"),
            result.tarefas.length ? h("ul", { className: "cap-list" }, result.tarefas.map((t, i) => h("li", { key: i }, h("span", { className: "cap-arrow" }, "→"), t))) : h("p", { className: "cap-empty" }, "Nenhuma tarefa detectada.")),
          h("div", null, h("div", { className: "mini-label" }, "💡 " + result.ideias.length + " ideia(s)"),
            result.ideias.length ? h("ul", { className: "cap-list" }, result.ideias.map((t, i) => h("li", { key: i }, h("span", { className: "cap-arrow social" }, "→"), t))) : h("p", { className: "cap-empty" }, "Nenhuma ideia detectada."))
        )
      ),
      h("div", { className: "mini-label" }, "🗄 Histórico de capturas"),
      h("div", { className: "cap-hist" }, history.map((hh) => h(Card, { key: hh.id, className: "cap-hist-card" },
        h("p", { className: "cap-hist-raw" }, hh.raw),
        h("div", { className: "cap-hist-meta" },
          hh.tarefas > 0 && h("span", { className: "badge-pink" }, hh.tarefas + " tarefa" + (hh.tarefas > 1 ? "s" : "")),
          hh.ideias > 0 && h("span", { className: "badge-yellow" }, hh.ideias + " ideia" + (hh.ideias > 1 ? "s" : "")),
          h("span", { className: "cap-hist-date" }, hh.date)
        )
      )))
    );
  }

  // ══════════════════ PROMPTS ══════════════════
  const CAT_META = {
    conteudo: { emoji: "📝", cor: "#E8538D" }, roteiro: { emoji: "🎬", cor: "#6FA8D6" },
    blog: { emoji: "✍️", cor: "#9E8BCB" }, newsletter: { emoji: "📬", cor: "#E89B4C" },
    branding: { emoji: "💎", cor: "#E8538D" }, cliente: { emoji: "🤝", cor: "#0A66C2" },
    ugc: { emoji: "📱", cor: "#7FB68C" }, design: { emoji: "🎨", cor: "#D9A93E" },
    pesquisa: { emoji: "🔎", cor: "#6FA8D6" }, estrategia: { emoji: "♟️", cor: "#A89AC9" },
  };
  function catMeta(cat) { return CAT_META[cat] || { emoji: "✨", cor: "#E8538D" }; }

  function PromptCard({ p, onOpen }) {
    const [copied, setCopied] = useState(false);
    const cm = catMeta(p.cat);
    const iaCor = (window.IA_COLORS && window.IA_COLORS[p.ia]) || "#E8538D";
    function copy(e) { e.stopPropagation(); navigator.clipboard && navigator.clipboard.writeText(p.texto); setCopied(true); setTimeout(() => setCopied(false), 1800); }
    return h("button", { className: "prm-card", style: { background: cm.cor + "12", borderColor: cm.cor + "33" }, onClick: () => onOpen(p) },
      h("div", { className: "prm-head" },
        h("span", { className: "prm-ic" }, cm.emoji),
        h("span", { className: "prm-cat", style: { color: cm.cor } }, (window.PROMPT_CATS && window.PROMPT_CATS[p.cat]) || p.cat),
        h("span", { className: "ia-pill", style: { background: iaCor + "22", color: iaCor } }, p.ia)
      ),
      h("div", { className: "prm-body" },
        h("h3", { className: "prm-title" }, p.titulo),
        h("p", { className: "prm-desc" }, p.desc),
        h("div", { className: "prm-steps" }, p.etapas.map((et, i) => h(React.Fragment, { key: et },
          i > 0 && h("span", { className: "prm-arrow", style: { color: cm.cor } }, "→"),
          h("span", { className: "prm-step" }, et)
        )))
      ),
      h("div", { className: "prm-foot" },
        p.tool ? h("span", { className: "prm-tool" }, "🛠 " + p.tool) : h("span"),
        h("span", { className: "prm-copy", onClick: copy }, copied ? "✓ Copiado" : "⧉ Copiar")
      )
    );
  }

  function PromptModal({ p, onClose }) {
    const [copied, setCopied] = useState(false);
    const cm = catMeta(p.cat);
    const iaCor = (window.IA_COLORS && window.IA_COLORS[p.ia]) || "#E8538D";
    function copy() { navigator.clipboard && navigator.clipboard.writeText(p.texto); setCopied(true); setTimeout(() => setCopied(false), 1800); }
    return h("div", { className: "modal-bg", onClick: onClose },
      h("div", { className: "modal", onClick: (e) => e.stopPropagation() },
        h("button", { className: "modal-x", onClick: onClose }, "✕"),
        h("div", { className: "modal-tags" },
          h("span", { className: "prm-ic sm", style: { background: cm.cor + "16" } }, cm.emoji),
          h("span", { className: "prm-cat", style: { color: cm.cor } }, (window.PROMPT_CATS && window.PROMPT_CATS[p.cat]) || p.cat),
          h("span", { className: "ia-pill", style: { background: iaCor + "22", color: iaCor } }, p.ia)
        ),
        h("h2", { className: "modal-title" }, p.titulo),
        h("p", { className: "prm-desc", style: { marginBottom: 16 } }, p.desc),
        p.tool && h("p", { className: "prompt-tool" }, "🛠 " + p.tool),
        h("div", { className: "prm-steps", style: { marginBottom: 18 } }, p.etapas.map((et, i) => h(React.Fragment, { key: et },
          i > 0 && h("span", { className: "prm-arrow", style: { color: cm.cor } }, "→"),
          h("span", { className: "prm-step" }, et)
        ))),
        h("div", { className: "mini-label" }, "Prompt completo"),
        h("div", { className: "prompt-code" },
          h("pre", null, p.texto),
          h("button", { className: "code-copy", onClick: copy }, copied ? "✓" : "⧉")
        ),
        p.checklist && p.checklist.length > 0 && h("div", null,
          h("div", { className: "mini-label" }, "Checklist"),
          h("div", { className: "prompt-check" }, p.checklist.map((it, i) => h("div", { key: i, className: "chk-row" }, h("span", { className: "chk-box" }), it)))
        )
      )
    );
  }

  function PromptsEstudio() {
    const [q, setQ] = useState("");
    const [cat, setCat] = useState("todos");
    const [sel, setSel] = useState(null);
    const all = window.DEMO_PROMPTS || [];
    const lista = all.filter((p) => {
      const okQ = !q || p.titulo.toLowerCase().includes(q.toLowerCase()) || p.desc.toLowerCase().includes(q.toLowerCase());
      const okC = cat === "todos" || p.cat === cat;
      return okQ && okC;
    });
    const catsUsadas = [...new Set(all.map((p) => p.cat))];
    return h("div", { className: "page" },
      h(PageHead, { titulo: "Banco de Prompts", sub: "Prompts prontos com IA recomendada, etapas e checklists — voz Papel da Lola",
        right: h("input", { className: "search", placeholder: "Buscar prompts…", value: q, onChange: (e) => setQ(e.target.value) })
      }),
      h("div", { className: "prm-filters" },
        h("button", { className: "prm-fchip" + (cat === "todos" ? " on" : ""), onClick: () => setCat("todos") }, "Todos ", h("span", { className: "prm-fcount" }, all.length)),
        catsUsadas.map((c) => { const cm = catMeta(c); const n = all.filter((p) => p.cat === c).length;
          return h("button", { key: c, className: "prm-fchip" + (cat === c ? " on" : ""), onClick: () => setCat(c), style: cat === c ? { background: cm.cor, borderColor: cm.cor, color: "#fff" } : { borderColor: cm.cor + "44" } },
            h("span", null, cm.emoji), " ", (window.PROMPT_CATS && window.PROMPT_CATS[c]) || c, h("span", { className: "prm-fcount" }, n));
        })
      ),
      lista.length
        ? h("div", { className: "prm-grid" }, lista.map((p) => h(PromptCard, { key: p.id, p, onOpen: setSel })))
        : h("div", { className: "empty" }, "Nenhum prompt encontrado."),
      sel && h(PromptModal, { p: sel, onClose: () => setSel(null) })
    );
  }

  Object.assign(window, { BauDeIdeias, PromptsEstudio });
})();
