// ===========================================================
// Purchase metadata: shared field group + the per-item detail/edit view.
//
// PurchaseFields is the single source of the price / gift / date / where
// inputs, used by BOTH the add flow (MyCollectionAdd_v2) and the edit view
// below, so the two behave identically. Ticking "gift" zeroes and locks the
// price; an empty price stays null (cost unknown), which is distinct from 0.
//
// CollectionItemDetail_v2 is a modal: read-only details, with an Edit toggle
// that makes the four purchase fields editable and persists via onSave.
//
// Globals: React, Sleeve. Exposes window.PurchaseFields,
// window.purchaseFromItem, window.purchasePayload, window.purchaseInvalid,
// window.CollectionItemDetail_v2.
// ===========================================================
const { useState: useDetailState, useEffect: useDetailEffect } = React;

// ---- helpers shared with the add flow --------------------------------------
// Read the four purchase fields off a collection_items row into editable state.
function purchaseFromItem(it) {
  const v = it || {};
  return {
    purchase_price: (v.purchase_price === null || v.purchase_price === undefined) ? null : v.purchase_price,
    is_gift: !!v.is_gift,
    purchase_date: v.purchase_date || null,
    purchase_location: v.purchase_location || "",
  };
}
// True only when a non-gift price was typed and it isn't a non-negative number.
function purchaseInvalid(p) {
  if (!p || p.is_gift) return false;
  const raw = p.purchase_price;
  if (raw === null || raw === undefined || raw === "") return false;
  const n = Number(raw);
  return !isFinite(n) || n < 0;
}
// Editable state -> the four columns to write. A gift is price 0 (not null);
// an empty price is null (unknown). Location trimmed; empties become null.
function purchasePayload(p) {
  const v = p || {};
  const loc = (v.purchase_location || "").trim();
  if (v.is_gift) {
    return { purchase_price: 0, is_gift: true, purchase_date: v.purchase_date || null, purchase_location: loc || null };
  }
  const raw = v.purchase_price;
  const price = (raw === null || raw === undefined || raw === "") ? null : Number(raw);
  return { purchase_price: price, is_gift: false, purchase_date: v.purchase_date || null, purchase_location: loc || null };
}

function pmGbp(n) { return "£" + (Math.round((n || 0) * 100) / 100).toLocaleString("en-GB", { minimumFractionDigits: 2, maximumFractionDigits: 2 }); }
function pmGrade(code) { return code ? code.replace("_PLUS", "+") : "—"; }
function pmDate(s) {
  if (!s) return null;
  const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(s));
  if (!m) return String(s);
  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  return parseInt(m[3], 10) + " " + months[parseInt(m[2], 10) - 1] + " " + m[1];
}

// ---- the shared field group ------------------------------------------------
// value: { purchase_price, is_gift, purchase_date, purchase_location }
function PurchaseFields({ value, onChange }) {
  const v = value || {};
  function set(patch) { onChange(Object.assign({}, v, patch)); }
  function toggleGift(checked) {
    // tick -> lock price at 0; untick -> clear back to "unknown" (null)
    if (checked) set({ is_gift: true, purchase_price: 0 });
    else set({ is_gift: false, purchase_price: null });
  }
  return (
    <div className="av2-purchase">
      <label className="av2-pf">
        <span className="av2-pf-label">Purchase price</span>
        <div className={"av2-price-wrap" + (v.is_gift ? " disabled" : "")}>
          <span className="av2-price-cur">£</span>
          <input
            className="av2-pf-input av2-price-input"
            type="number" min="0" step="0.01" inputMode="decimal"
            placeholder={v.is_gift ? "Gift" : "0.00"}
            disabled={!!v.is_gift}
            value={v.is_gift ? "" : (v.purchase_price === null || v.purchase_price === undefined ? "" : v.purchase_price)}
            onChange={(e) => set({ purchase_price: e.target.value === "" ? null : e.target.value })}
          />
        </div>
      </label>
      <label className="av2-pf-gift">
        <input type="checkbox" checked={!!v.is_gift} onChange={(e) => toggleGift(e.target.checked)} />
        <span>It was a gift</span>
      </label>
      <label className="av2-pf">
        <span className="av2-pf-label">Date bought</span>
        <input className="av2-pf-input" type="date" value={v.purchase_date || ""}
          onChange={(e) => set({ purchase_date: e.target.value || null })} />
      </label>
      <label className="av2-pf">
        <span className="av2-pf-label">Where you bought it</span>
        <input className="av2-pf-input" type="text" maxLength={120}
          placeholder="Rough Trade East, eBay, a car boot…"
          value={v.purchase_location || ""}
          onChange={(e) => set({ purchase_location: e.target.value })} />
      </label>
    </div>
  );
}

// ---- per-item detail / edit modal ------------------------------------------
// item: a resolved collection record (has .album, .value, .media_condition,
//   .sleeve_condition + the four purchase columns).
// onSave: async (id, patch) => persist. onClose: () => dismiss.
function CollectionItemDetail_v2({ item, folders, onSave, onClose }) {
  const [editing, setEditing] = useDetailState(false);
  const [draft, setDraft] = useDetailState(() => purchaseFromItem(item));
  // Folder assignment is edited alongside the purchase fields. "" = Unfiled.
  const [folderDraft, setFolderDraft] = useDetailState(() => (item && item.folder_id) || "");
  const [saving, setSaving] = useDetailState(false);
  const [err, setErr] = useDetailState(false);

  // Back button (mobile/iOS) closes this modal instead of leaving the page.
  window.BBR_useModalBack(onClose);

  // Full-screen overlay on mobile: lock the page behind it. iOS Safari ignores
  // body{overflow:hidden} (the page still pans, dragging the fixed layer so the
  // sticky header — and its × close button — scroll out of reach), so pin the
  // body with position:fixed at -scrollY and restore on close. Same pattern as
  // the add flow and the importer.
  useDetailEffect(() => {
    const scrollY = window.scrollY || window.pageYOffset || 0;
    const b = document.body;
    const prev = {
      position: b.style.position, top: b.style.top, left: b.style.left,
      right: b.style.right, width: b.style.width, overflow: b.style.overflow,
    };
    b.style.position = "fixed";
    b.style.top = "-" + scrollY + "px";
    b.style.left = "0"; b.style.right = "0"; b.style.width = "100%"; b.style.overflow = "hidden";
    return () => {
      b.style.position = prev.position; b.style.top = prev.top;
      b.style.left = prev.left; b.style.right = prev.right;
      b.style.width = prev.width; b.style.overflow = prev.overflow;
      window.scrollTo(0, scrollY);
    };
  }, []);

  if (!item) return null;

  const folderList = folders || [];
  const invalid = purchaseInvalid(draft);

  function startEdit() { setErr(false); setDraft(purchaseFromItem(item)); setFolderDraft(item.folder_id || ""); setEditing(true); }
  function cancelEdit() { setErr(false); setEditing(false); }
  async function save() {
    if (invalid || saving) return;
    setSaving(true); setErr(false);
    try {
      // Merge the folder assignment into the patch; "" -> null (Unfiled).
      await onSave(item.id, Object.assign({}, purchasePayload(draft), { folder_id: folderDraft || null }));
      setEditing(false);
    } catch (e) {
      setErr(true);
    } finally { setSaving(false); }
  }
  const currentFolder = folderList.find(f => f.id === item.folder_id);

  // read-only "Paid" line off the live item row
  const paid = item.is_gift ? "Gift"
    : (item.purchase_price === null || item.purchase_price === undefined) ? "Not recorded"
    : pmGbp(item.purchase_price);
  const when = pmDate(item.purchase_date);
  const where = (item.purchase_location || "").trim();

  return (
    <div className="av2-backdrop" onClick={onClose}>
      <div className="av2-modal" onClick={(e) => e.stopPropagation()}>
        <div className="av2-head">
          <div className="av2-head-left">
            <button className="av2-back-arrow" aria-label="Back to collection" onClick={onClose}>
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M12 4l-5 6 5 6" /></svg>
            </button>
            <span className="av2-head-title">Record details</span>
          </div>
          <button className="av2-x" onClick={onClose}>×</button>
        </div>
        <div className="av2-body">
          <div className="av2-pane">
            <div className="av2-chosen">
              {window.Sleeve && <Sleeve album={item.album} size={64} />}
              <div>
                <div className="av2-chosen-t"><b>{item.artist}</b> — {item.title}</div>
                <div className="av2-chosen-meta">
                  {[item.year, item.genre].filter(Boolean).join(" · ")}
                  {" · "}{pmGrade(item.media_condition)}/{pmGrade(item.sleeve_condition)}
                  {item.pending
                    ? " · valuation loading (live price, up to 48h)"
                    : (item.value > 0 ? " · est. " + ("£" + Math.round(item.value).toLocaleString("en-GB")) : " · unvalued")}
                </div>
              </div>
            </div>

            {!editing ? (
              <div className="cid-readout">
                <div className="cid-row"><span className="cid-k">Paid</span><span className="cid-v">{paid}</span></div>
                <div className="cid-row"><span className="cid-k">Date bought</span><span className="cid-v">{when || "Not recorded"}</span></div>
                <div className="cid-row"><span className="cid-k">Where bought</span><span className="cid-v">{where || "Not recorded"}</span></div>
                <div className="cid-row"><span className="cid-k">Folder</span><span className="cid-v">{currentFolder ? currentFolder.name : "Unfiled"}</span></div>
                <div className="av2-foot">
                  <span />
                  <button className="av2-next" onClick={startEdit}>Edit details</button>
                </div>
              </div>
            ) : (
              <div>
                <h3 className="av2-title" style={{ fontSize: 16, marginTop: 4 }}>Purchase details</h3>
                <p className="av2-hint">All optional. A gift counts as £0 spend.</p>
                <PurchaseFields value={draft} onChange={setDraft} />
                <label className="av2-pf" style={{ marginTop: 14 }}>
                  <span className="av2-pf-label">Folder</span>
                  <div className="mc-select" style={{ display: "block" }}>
                    <select className="cid-folder-select" value={folderDraft}
                      onChange={(e) => setFolderDraft(e.target.value)}>
                      <option value="">Unfiled</option>
                      {folderList.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
                    </select>
                  </div>
                </label>
                {invalid && <p className="av2-pf-err">Enter a price of 0 or more, or leave it blank.</p>}
                {err && <p className="av2-pf-err">Couldn't save just now. Try again.</p>}
                <div className="av2-foot">
                  <button className="av2-back" onClick={cancelEdit} disabled={saving}>Cancel</button>
                  <button className="av2-next" onClick={save} disabled={invalid || saving}>{saving ? "Saving…" : "Save"}</button>
                </div>
              </div>
            )}

            {/* Value-over-time chart (Brief B). Read-only view only, below the
                core facts, so the edit form stays focused when open. */}
            {!editing && window.ValueHistoryChart && (
              <ValueHistoryChart itemId={item.id} />
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PurchaseFields, purchaseFromItem, purchasePayload, purchaseInvalid, CollectionItemDetail_v2 });
