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

<AdminLayout title="Edit project">
  <a href="/admin/projects" class="back">← All projects</a>
  <h1 id="ptitle">Project</h1>
  <p class="lead">Edit the details, gallery, and reel — then publish to the live site.</p>

  <section class="block two">
    <div>
      <label for="f-title">Title</label>
      <input type="text" id="f-title" />
    </div>
    <div>
      <label for="f-status">Status</label>
      <div class="sel">
        <select id="f-status">
          <option value="live">Live</option>
          <option value="building">In development</option>
          <option value="archived">Archived</option>
          <option value="concept">Concept</option>
        </select>
      </div>
    </div>
    <div>
      <label for="f-kind">Type</label>
      <input type="text" id="f-kind" placeholder="SaaS, Tooling, SaaS / Media…" />
    </div>
    <div>
      <label for="f-period">Timeline</label>
      <input type="text" id="f-period" placeholder="2020 — present" />
    </div>
    <div class="wide">
      <label for="f-role">Role</label>
      <input type="text" id="f-role" placeholder="Founder — product, engineering…" />
    </div>
    <div class="wide">
      <label for="f-cats">Categories (comma-separated)</label>
      <input type="text" id="f-cats" placeholder="Websites, SaaS, Agentic" />
    </div>
    <div class="wide">
      <label for="f-stack">Built with (comma-separated)</label>
      <input type="text" id="f-stack" placeholder="Astro, PHP, MariaDB" />
    </div>
  </section>

  <section class="block">
    <label for="f-summary">Summary (one line, shown on the projects list)</label>
    <textarea id="f-summary" rows="2"></textarea>
  </section>

  <section class="block">
    <label for="f-lede">Lede (the big opening line on the project page)</label>
    <textarea id="f-lede" rows="2"></textarea>
  </section>

  <section class="block">
    <label for="f-body">Case study (Markdown — use ## for headings, - for bullets)</label>
    <textarea id="f-body" rows="14" class="mono"></textarea>
  </section>

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

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

  <section class="block">
    <label for="ig">Instagram reel URL</label>
    <input type="url" id="ig" placeholder="https://instagram.com/reel/…" />
  </section>

  <section class="block">
    <div class="head">
      <label>Gallery</label>
      <button type="button" class="btn ghost sm" id="addSlot">+ Add image</button>
    </div>
    <div id="gallery" class="grid"></div>
  </section>

  <div class="footer">
    <button type="button" class="btn" id="save">Save &amp; publish</button>
    <a class="view" id="viewLink" target="_blank">View live ↗</a>
    <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.75rem 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; }
    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; }
    .sel select { width:100%; border:0; border-bottom:1px solid var(--rule); background:var(--paper);
      padding:.5rem 0; font-size:.95rem; color:var(--ink); font-family:var(--sans); }
    .sel select:focus { outline:none; border-bottom-color:var(--seal); }
    .sel select option { background:var(--paper); color:var(--ink); }
    .btn.sm { padding:.35rem .7rem; font-size:.7rem; }
    .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; }
    .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); }
    .view { font-family:var(--mono); font-size:.62rem; letter-spacing:.1em; text-transform:uppercase;
      color:var(--ink4); text-decoration:none; } .view:hover { color:var(--ink); }
  </style>

  <script>
    const slug = new URLSearchParams(location.search).get("slug") || "";
    const galleryEl = document.getElementById("gallery");
    const msg = document.getElementById("msg");
    const $ = (id) => document.getElementById(id);
    const setMsg = (t, cls = "") => { msg.textContent = t; msg.className = "msg " + cls; };
    let items = [];        // gallery
    let skills = [];       // [{group, items:[...]}]
    let metrics = [];      // [{value, label, note}]
    const skillsEl = document.getElementById("skills");
    const metricsEl = document.getElementById("metrics");

    function render() {
      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); render(); });
        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; render(); }
        else setMsg(d?.error?.message || "Upload failed.", "error");
      } catch { setMsg("Upload failed.", "error"); }
      finally { thumb.classList.remove("busy"); }
    }

    $("addSlot").addEventListener("click", () => { items.push({ src: "", alt: "", caption: "" }); render(); });

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

    // ---- 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(); });

    $("save").addEventListener("click", async () => {
      const btn = $("save"); btn.disabled = true; setMsg("Saving…");
      try {
        const links = {};
        const ig = $("ig").value.trim();
        if (ig) links.instagram = ig;
        const payload = {
          slug,
          title: $("f-title").value.trim(),
          status: $("f-status").value,
          kind: $("f-kind").value.trim(),
          period: $("f-period").value.trim(),
          role: $("f-role").value.trim(),
          summary: $("f-summary").value.trim(),
          lede: $("f-lede").value.trim(),
          body: $("f-body").value,
          categories: splitList($("f-cats").value),
          stack: splitList($("f-stack").value),
          skills,
          metrics,
          gallery: items,
          links,
        };
        const save = await fetch("/api/adminprojects/save", {
          method: "POST", credentials: "same-origin",
          headers: { "content-type": "application/json" }, body: JSON.stringify(payload),
        });
        const sd = await save.json();
        if (!save.ok || !sd?.data?.ok) { setMsg(sd?.error?.message || "Save failed.", "error"); btn.disabled = false; return; }
        setMsg("Saved — publishing to the live site…");
        const pub = await fetch("/devconsole/rebuild", { method: "POST", credentials: "same-origin" });
        setMsg(pub.ok ? "Published. Changes are live." : "Saved, but the publish build failed.", pub.ok ? "ok" : "error");
      } catch { setMsg("Something went wrong.", "error"); }
      finally { btn.disabled = false; }
    });

    (async () => {
      if (!slug) { setMsg("No project specified.", "error"); return; }
      $("viewLink").href = "/projects/" + slug;
      try {
        const r = await fetch("/api/adminprojects/get?slug=" + encodeURIComponent(slug), { credentials: "same-origin" });
        const d = await r.json();
        if (!r.ok || !d?.data) { setMsg("Couldn't load the project.", "error"); return; }
        const p = d.data;
        $("ptitle").textContent = p.title || slug;
        $("f-title").value = p.title || "";
        $("f-status").value = p.status || "building";
        $("f-kind").value = p.kind || "";
        $("f-period").value = p.period || "";
        $("f-role").value = p.role || "";
        $("f-summary").value = p.summary || "";
        $("f-lede").value = p.lede || "";
        $("f-body").value = p.body || "";
        $("f-cats").value = (p.categories || []).join(", ");
        $("f-stack").value = (p.stack || []).join(", ");
        $("ig").value = p.links?.instagram || "";
        items = Array.isArray(p.gallery) ? p.gallery : [];
        skills = Array.isArray(p.skills) ? p.skills : [];
        metrics = Array.isArray(p.metrics) ? p.metrics : [];
        render(); renderSkills(); renderMetrics();
      } catch { setMsg("Couldn't load the project.", "error"); }
    })();
  </script>
</AdminLayout>
