---
import AdminLayout from "../../../layouts/AdminLayout.astro";
---

<AdminLayout title="New project">
  <a href="/admin/projects" class="back">← All projects</a>
  <h1>New project</h1>
  <p class="lead">Give the Web Designer a brief — a rough draft, any special instructions, and your images. It reads the images and builds the whole page. You review everything before it goes live.</p>

  <section class="block two">
    <div class="wide">
      <label for="f-name">Project name</label>
      <input type="text" id="f-name" placeholder="Ginny Goldman — firm site" />
    </div>
    <div class="wide">
      <label for="f-cats">Category hint (comma-separated)</label>
      <input type="text" id="f-cats" placeholder="Websites, Law firms" />
    </div>
  </section>

  <section class="block">
    <label for="f-draft">Description draft</label>
    <textarea id="f-draft" rows="5" placeholder="Rough notes — what it is, who it's for, what you built, any results. Doesn't have to be polished."></textarea>
  </section>

  <section class="block">
    <label for="f-prompt">Special instructions for the Web Designer <span class="opt">optional</span></label>
    <textarea id="f-prompt" rows="3" placeholder="e.g. Lead with the results, keep it concise, emphasize the automation work, add a Highlights section."></textarea>
  </section>

  <section class="block">
    <div class="head">
      <label>Images</label>
      <button type="button" class="btn ghost sm" id="addSlot">+ Add image</button>
    </div>
    <div id="gallery" class="grid"></div>
    <p class="hint">Upload screenshots or photos. The Web Designer reads each one and captions it.</p>
  </section>

  <section class="block">
    <label for="ig">Instagram reel URL <span class="opt">optional</span></label>
    <input type="url" id="ig" placeholder="https://instagram.com/reel/…" />
    <p class="hint">Paste a link to an existing reel, or add one later from the editor.</p>
  </section>

  <div class="build-bar">
    <button type="button" class="btn" id="buildBtn">✷ Build with Web Designer</button>
    <p class="msg" id="buildMsg" role="status" aria-live="polite"></p>
  </div>

  <!-- ============ agent output — everything editable before creating ======= -->
  <section class="generated" id="genWrap" hidden>
    <p class="gen-head">The Web Designer built this. Edit anything, then create the project.</p>

    <div class="block">
      <label for="g-summary" class="sub">Summary <span class="opt">projects list</span></label>
      <textarea id="g-summary" rows="2"></textarea>
    </div>
    <div class="block">
      <label for="g-lede" class="sub">Lede <span class="opt">page opener</span></label>
      <textarea id="g-lede" rows="2"></textarea>
    </div>

    <div class="block two">
      <div><label for="g-kind" class="sub">Type</label><input type="text" id="g-kind" /></div>
      <div><label for="g-period" class="sub">Timeline</label><input type="text" id="g-period" /></div>
      <div class="wide"><label for="g-role" class="sub">Role</label><input type="text" id="g-role" /></div>
      <div class="wide"><label for="g-cats" class="sub">Categories (comma-separated)</label><input type="text" id="g-cats" /></div>
      <div class="wide"><label for="g-stack" class="sub">Built with (comma-separated)</label><input type="text" id="g-stack" /></div>
    </div>

    <div class="block">
      <div class="head"><label class="sub">Metrics</label><button type="button" class="btn ghost sm" id="addMetric">+ Add metric</button></div>
      <div id="metrics" class="rows"></div>
    </div>

    <div class="block">
      <div class="head"><label class="sub">Skills applied</label><button type="button" class="btn ghost sm" id="addSkill">+ Add group</button></div>
      <div id="skills" class="rows"></div>
    </div>

    <div class="block">
      <label for="g-body" class="sub">Case study (Markdown)</label>
      <textarea id="g-body" rows="14" class="mono"></textarea>
    </div>

    <p class="hint">Image captions are filled into each image above — scroll up to tweak them.</p>
  </section>

  <div class="footer">
    <button type="button" class="btn" id="create">Create project</button>
    <p class="msg" id="msg" role="status" aria-live="polite"></p>
  </div>

  <style>
    .back { font-family:var(--mono); font-size:.62rem; letter-spacing:.12em; text-transform:uppercase;
      color:var(--ink4); text-decoration:none; display:inline-block; margin-bottom:1.25rem; }
    .back:hover { color:var(--ink); }
    .block { margin:1.5rem 0; }
    .block.two { display:grid; grid-template-columns:1fr 1fr; gap:1.25rem 2rem; }
    .block.two .wide { grid-column:1 / -1; }
    .block .head { display:flex; align-items:center; gap:1rem; margin-bottom:1rem; }
    .block .head label { margin:0; }
    .opt { font-size:.55rem; color:var(--ink4); letter-spacing:.08em; }
    label.sub { margin-top:0; }
    textarea { width:100%; border:1px solid var(--rule); background:transparent; border-radius:2px;
      padding:.6rem .7rem; font-size:.9rem; color:var(--ink); font-family:var(--sans); line-height:1.55; resize:vertical; }
    textarea:focus { outline:none; border-color:var(--seal); }
    textarea.mono { font-family:var(--mono); font-size:.82rem; }
    .hint { font-size:.78rem; color:var(--ink3); margin:.5rem 0 0; }
    .btn.sm { padding:.35rem .7rem; font-size:.7rem; }

    .build-bar { display:flex; align-items:center; gap:1.25rem; margin:2rem 0; padding:1.1rem 0;
      border-top:1px solid var(--rule); border-bottom:1px solid var(--rule); }
    .generated { border-left:2px solid var(--seal); padding-left:1.25rem; margin:2rem 0; }
    .gen-head { font-family:var(--mono); font-size:.62rem; letter-spacing:.1em; text-transform:uppercase;
      color:var(--seal); margin:0 0 1.25rem; }

    /* skills / metrics rows */
    .rows { display:flex; flex-direction:column; gap:.6rem; }
    .row { display:flex; gap:.6rem; align-items:center; }
    .row input { flex:1; }
    .row .rm { flex:0 0 auto; width:1.9rem; height:1.9rem; border:1px solid var(--rule); background:transparent;
      color:var(--ink3); border-radius:2px; cursor:pointer; font-size:.9rem; line-height:1; }
    .row .rm:hover { color:var(--seal); border-color:var(--seal); }
    .row .grp { flex:0 0 9rem; }
    .row .val { flex:0 0 6rem; }

    /* gallery */
    .grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(11rem,1fr)); gap:1rem; }
    .slot { border:1px solid var(--rule); border-radius:2px; overflow:hidden; display:flex; flex-direction:column; }
    .thumb { position:relative; aspect-ratio:4/3; background:var(--card); display:flex; align-items:center;
      justify-content:center; overflow:hidden; }
    .thumb img { width:100%; height:100%; object-fit:cover; }
    .thumb .empty { font-family:var(--mono); font-size:.6rem; letter-spacing:.1em; text-transform:uppercase; color:var(--ink4); }
    .thumb.busy::after { content:"Uploading…"; position:absolute; inset:0; display:flex; align-items:center;
      justify-content:center; background:color-mix(in srgb, var(--paper) 80%, transparent);
      font-family:var(--mono); font-size:.65rem; color:var(--ink3); }
    .slot .cap { border:0; border-top:1px solid var(--rule); background:transparent; padding:.5rem .6rem;
      font-size:.8rem; color:var(--ink); font-family:var(--sans); width:100%; }
    .slot .cap:focus { outline:none; }
    .slot .acts { display:flex; border-top:1px solid var(--rule); }
    .slot .acts label, .slot .acts button { flex:1; text-align:center; padding:.45rem; font-family:var(--mono);
      font-size:.58rem; letter-spacing:.08em; text-transform:uppercase; color:var(--ink3); cursor:pointer;
      background:none; border:0; }
    .slot .acts label { border-right:1px solid var(--rule); }
    .slot .acts button:hover { color:var(--seal); } .slot .acts label:hover { color:var(--ink); }
    .slot .acts input { display:none; }

    .footer { position:sticky; bottom:0; display:flex; align-items:center; gap:1.5rem; padding:1rem 0;
      margin-top:2rem; border-top:1px solid var(--rule);
      background:color-mix(in srgb, var(--paper) 92%, transparent); }
  </style>

  <script>
    const $ = (id) => document.getElementById(id);
    const msg = $("msg"), buildMsg = $("buildMsg");
    const setMsg = (t, cls = "") => { msg.textContent = t; msg.className = "msg " + cls; };
    const galleryEl = $("gallery"), skillsEl = $("skills"), metricsEl = $("metrics");
    let items = [];        // gallery: [{src, alt, caption}]
    let skills = [];       // [{group, items:[...]}]
    let metrics = [];      // [{value, label, note}]

    // ---- gallery -----------------------------------------------------------
    function renderGallery() {
      galleryEl.innerHTML = "";
      items.forEach((it, i) => {
        const slot = document.createElement("div");
        slot.className = "slot";
        slot.innerHTML = `
          <div class="thumb" data-thumb>
            ${it.src ? `<img src="${it.src}" alt="">` : `<span class="empty">No image</span>`}
          </div>
          <input class="cap" placeholder="Caption" value="${(it.caption || "").replace(/"/g, "&quot;")}" data-cap>
          <div class="acts">
            <label>${it.src ? "Replace" : "Upload"}<input type="file" accept="image/*" data-file></label>
            <button type="button" data-remove>Remove</button>
          </div>`;
        slot.querySelector("[data-cap]").addEventListener("input", (e) => { items[i].caption = e.target.value; });
        slot.querySelector("[data-remove]").addEventListener("click", () => { items.splice(i, 1); renderGallery(); });
        slot.querySelector("[data-file]").addEventListener("change", (e) => upload(e.target.files[0], i, slot));
        galleryEl.appendChild(slot);
      });
    }
    async function upload(file, i, slot) {
      if (!file) return;
      const thumb = slot.querySelector("[data-thumb]");
      thumb.classList.add("busy");
      try {
        const fd = new FormData(); fd.append("file", file);
        const r = await fetch("/api/media/upload", { method: "POST", credentials: "same-origin", body: fd });
        const d = await r.json();
        if (r.ok && d?.data?.url) { items[i].src = d.data.url; renderGallery(); }
        else buildMsg.textContent = d?.error?.message || "Upload failed.";
      } catch { buildMsg.textContent = "Upload failed."; }
      finally { thumb.classList.remove("busy"); }
    }
    $("addSlot").addEventListener("click", () => { items.push({ src: "", alt: "", caption: "" }); renderGallery(); });

    // ---- skills groups -----------------------------------------------------
    function renderSkills() {
      skillsEl.innerHTML = "";
      skills.forEach((g, i) => {
        const row = document.createElement("div");
        row.className = "row";
        row.innerHTML = `
          <input class="grp" placeholder="Group (e.g. Engineering)" value="${(g.group || "").replace(/"/g, "&quot;")}" data-grp>
          <input placeholder="Items, comma-separated" value="${(g.items || []).join(", ").replace(/"/g, "&quot;")}" data-items>
          <button type="button" class="rm" title="Remove" data-rm>×</button>`;
        row.querySelector("[data-grp]").addEventListener("input", (e) => { skills[i].group = e.target.value; });
        row.querySelector("[data-items]").addEventListener("input", (e) => { skills[i].items = splitList(e.target.value); });
        row.querySelector("[data-rm]").addEventListener("click", () => { skills.splice(i, 1); renderSkills(); });
        skillsEl.appendChild(row);
      });
    }
    $("addSkill").addEventListener("click", () => { skills.push({ group: "", items: [] }); renderSkills(); });

    // ---- metrics -----------------------------------------------------------
    function renderMetrics() {
      metricsEl.innerHTML = "";
      metrics.forEach((m, i) => {
        const row = document.createElement("div");
        row.className = "row";
        row.innerHTML = `
          <input class="val" placeholder="Value" value="${(m.value || "").replace(/"/g, "&quot;")}" data-val>
          <input placeholder="Label" value="${(m.label || "").replace(/"/g, "&quot;")}" data-label>
          <input placeholder="Note (optional)" value="${(m.note || "").replace(/"/g, "&quot;")}" data-note>
          <button type="button" class="rm" title="Remove" data-rm>×</button>`;
        row.querySelector("[data-val]").addEventListener("input", (e) => { metrics[i].value = e.target.value; });
        row.querySelector("[data-label]").addEventListener("input", (e) => { metrics[i].label = e.target.value; });
        row.querySelector("[data-note]").addEventListener("input", (e) => { metrics[i].note = e.target.value; });
        row.querySelector("[data-rm]").addEventListener("click", () => { metrics.splice(i, 1); renderMetrics(); });
        metricsEl.appendChild(row);
      });
    }
    $("addMetric").addEventListener("click", () => { metrics.push({ value: "", label: "", note: "" }); renderMetrics(); });

    const splitList = (s) => s.split(",").map((x) => x.trim()).filter(Boolean);

    // ---- build with the Web Designer --------------------------------------
    $("buildBtn").addEventListener("click", async () => {
      const name = $("f-name").value.trim();
      if (!name) { buildMsg.textContent = "Add a project name first."; return; }
      const btn = $("buildBtn"); btn.disabled = true; $("create").disabled = true;
      buildMsg.textContent = "Web Designer is building your page — reading images, writing sections… (~1–2 min)";
      try {
        const r = await fetch("/devconsole/build-project", {
          method: "POST", credentials: "same-origin",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            name,
            category: $("f-cats").value.trim(),
            draft: $("f-draft").value.trim(),
            prompt: $("f-prompt").value.trim(),
            images: items.filter((it) => it.src).map((it) => ({ src: it.src })),
            instagram: $("ig").value.trim(),
          }),
        });
        const d = await r.json();
        if (!r.ok) { buildMsg.textContent = d?.error || "Couldn't build the page."; return; }

        $("g-summary").value = d.summary || "";
        $("g-lede").value = d.lede || "";
        $("g-body").value = d.body || "";
        $("g-kind").value = d.kind || "";
        $("g-period").value = d.period || "";
        $("g-role").value = d.role || "";
        $("g-cats").value = (d.categories || []).join(", ");
        $("g-stack").value = (d.stack || []).join(", ");
        skills = Array.isArray(d.skills) ? d.skills : [];
        metrics = Array.isArray(d.metrics) ? d.metrics : [];
        renderSkills(); renderMetrics();

        // merge the agent's captions back into the matching gallery slots
        if (Array.isArray(d.gallery)) {
          const bySrc = new Map(d.gallery.map((g) => [g.src, g]));
          items.forEach((it) => { const g = bySrc.get(it.src); if (g) { it.caption = g.caption; it.alt = g.alt; } });
          renderGallery();
        }
        $("genWrap").hidden = false;
        buildMsg.textContent = "Built — review everything below, then create.";
      } catch { buildMsg.textContent = "Couldn't reach the Web Designer."; }
      finally { btn.disabled = false; $("create").disabled = false; }
    });

    // ---- create ------------------------------------------------------------
    $("create").addEventListener("click", async () => {
      const name = $("f-name").value.trim();
      if (!name) { setMsg("Give the project a name.", "error"); return; }
      const btn = $("create"); btn.disabled = true; setMsg("Creating…");
      const built = !$("genWrap").hidden;
      try {
        const cr = await fetch("/api/adminprojects/create", {
          method: "POST", credentials: "same-origin",
          headers: { "content-type": "application/json" }, body: JSON.stringify({ title: name }),
        });
        const cd = await cr.json();
        if (!cr.ok || !cd?.data?.slug) { setMsg(cd?.error?.message || "Couldn't create the project.", "error"); btn.disabled = false; return; }
        const slug = cd.data.slug;

        const links = {};
        const ig = $("ig").value.trim();
        if (ig) links.instagram = ig;

        const payload = {
          slug, title: name,
          categories: built ? splitList($("g-cats").value) : splitList($("f-cats").value),
          stack: built ? splitList($("g-stack").value) : [],
          summary: built ? $("g-summary").value.trim() : "",
          lede: built ? $("g-lede").value.trim() : "",
          body: built ? $("g-body").value : $("f-draft").value,
          kind: built ? $("g-kind").value.trim() : "",
          period: built ? $("g-period").value.trim() : "",
          role: built ? $("g-role").value.trim() : "",
          skills: built ? skills : [],
          metrics: built ? metrics : [],
          gallery: items, links,
        };
        const sv = await fetch("/api/adminprojects/save", {
          method: "POST", credentials: "same-origin",
          headers: { "content-type": "application/json" }, body: JSON.stringify(payload),
        });
        const sd = await sv.json();
        if (!sv.ok || !sd?.data?.ok) { setMsg(sd?.error?.message || "Created, but saving details failed.", "error"); btn.disabled = false; return; }

        setMsg("Publishing to the live site…");
        const pub = await fetch("/devconsole/rebuild", { method: "POST", credentials: "same-origin" });
        if (pub.ok) { setMsg("Published — opening the editor…", "ok"); location.href = "/admin/projects/edit?slug=" + encodeURIComponent(slug); }
        else setMsg("Saved, but the publish build failed. Open the editor to retry.", "error");
      } catch { setMsg("Something went wrong.", "error"); btn.disabled = false; }
    });
  </script>
</AdminLayout>
