/* ============================================================
   IRONLOG — The Wall: a fully admin-managed grid of custom
   "blocks" (extra divs) stored in MongoDB. Add as many as you
   like: image cards, text panels, big-number stats, side notes.
   Each block persists to the DB and shows on the public page.
   ============================================================ */

const BLOCK_KINDS = [
  ["text", "Text panel"],
  ["image", "Image card"],
  ["stat", "Big number"],
];
const BLOCK_COLUMNS = [
  ["wide", "Wide (2 cols)"],
  ["side", "Side (1 col)"],
  ["full", "Full width"],
];

function BlockCard({ block, admin, onEdit, onRemove }) {
  const span = block.column === "full" ? "wall-full" : block.column === "wide" ? "wall-wide" : "wall-side";
  return (
    <Editable admin={admin} label="Edit block" penPos="tr" className={"wall-cell " + span}>
      <div className={"card card-hover wall-block wall-" + block.kind}>
        {block.kind === "image" && (
          <div className="ph wall-img">
            {block.image
              ? <img src={block.image} alt={block.title || "block"} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              : <span className="ph-label">no image yet</span>}
          </div>
        )}
        {block.kind === "stat" && (
          <div className="wall-stat-num display tnum">{block.stat || "—"}<span className="wall-stat-lbl">{block.statLabel}</span></div>
        )}
        {block.title && <div className="wall-title head">{block.title}</div>}
        {block.body && <p className="wall-body muted">{block.body}</p>}
        {admin && (
          <div className="wall-actions">
            <button className="pen pen-sm" onClick={onEdit} aria-label="Edit block"><Icons.Pen /></button>
            <button className="pen pen-sm" onClick={() => onRemove(block.id)} aria-label="Remove block"><Icons.Trash /></button>
          </div>
        )}
      </div>
    </Editable>
  );
}

function Gallery({ blocks, admin, onAdd, onSave, onRemove }) {
  const [editing, setEditing] = useState(null); // block | {new:true}
  const sorted = [...(blocks || [])].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));

  // Hide the whole section on the public page when there's nothing to show.
  if (!admin && sorted.length === 0) return null;

  return (
    <section id="gallery" className="section">
      <div className="container">
        <Reveal className="section-head">
          <div>
            <div className="section-index">★ — THE WALL</div>
            <h2 className="section-title">The<br/>Journey</h2>
          </div>
          <div style={{ maxWidth: 320 }}>
            <p className="muted" style={{ margin: 0 }}>Photos, milestones, and notes from the road — 230 to 180, the cut, the switch, the pulls. Built block by block.</p>
            {admin && <button className="btn btn-primary" style={{ marginTop: 16 }} onClick={() => setEditing({ new: true })}><Icons.Plus size={15}/> Add block</button>}
          </div>
        </Reveal>

        {sorted.length === 0 ? (
          <Reveal className="wall-empty card">
            <Icons.Image size={26} />
            <p className="muted">No blocks yet. Add image cards, notes, or milestones — they’ll persist and show here.</p>
          </Reveal>
        ) : (
          <Reveal className="wall-grid">
            {sorted.map((b) => (
              <BlockCard key={b.id} block={b} admin={admin}
                onEdit={() => setEditing(b)} onRemove={onRemove} />
            ))}
          </Reveal>
        )}
      </div>

      {editing && (
        <BlockEdit block={editing.new ? null : editing}
          onClose={() => setEditing(null)}
          onSave={(b) => { editing.new ? onAdd(b) : onSave(b); setEditing(null); }} />
      )}
    </section>
  );
}

function BlockEdit({ block, onClose, onSave }) {
  const isNew = !block;
  const [kind, setKind] = useState(block ? block.kind : "text");
  const [column, setColumn] = useState(block ? block.column : "wide");
  const [title, setTitle] = useState(block ? block.title : "");
  const [body, setBody] = useState(block ? block.body : "");
  const [stat, setStat] = useState(block ? block.stat : "");
  const [statLabel, setStatLabel] = useState(block ? block.statLabel : "");
  const [image, setImage] = useState(block ? block.image : null);
  const [imageId, setImageId] = useState(block ? block.imageId : null);
  const [busy, setBusy] = useState(false);

  async function upload() {
    const picked = await pickImageFile();
    if (!picked) return;
    setBusy(true);
    try { const r = await API.upload(picked.dataUrl, { target: "block" }); setImage(r.url); setImageId(r.id); }
    catch (ex) { alert(ex.message || "Upload failed"); }
    finally { setBusy(false); }
  }

  return (
    <Modal title={isNew ? "Add block" : "Edit block"} onClose={onClose} maxWidth={560}
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary"
          onClick={() => onSave({ ...(block || { id: "blk-" + Date.now() }), kind, column, title, body, stat, statLabel, image, imageId })}>
          <Icons.Check size={15}/> {isNew ? "Add" : "Save"}</button>
      </>}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div className="field"><label>Type</label>
          <select className="select" value={kind} onChange={(e) => setKind(e.target.value)}>
            {BLOCK_KINDS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
          </select>
        </div>
        <div className="field"><label>Width</label>
          <select className="select" value={column} onChange={(e) => setColumn(e.target.value)}>
            {BLOCK_COLUMNS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
          </select>
        </div>
      </div>

      <div className="field"><label>Title</label>
        <input className="input" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. The Cut · Feb 15 – Apr 1" /></div>

      {kind === "stat" && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <div className="field"><label>Big number</label><input className="input tnum" value={stat} onChange={(e) => setStat(e.target.value)} placeholder="50" /></div>
          <div className="field"><label>Number label</label><input className="input" value={statLabel} onChange={(e) => setStatLabel(e.target.value)} placeholder="lbs lost" /></div>
        </div>
      )}

      <div className="field"><label>Body</label>
        <textarea className="textarea" value={body} onChange={(e) => setBody(e.target.value)} placeholder="A line or two about this moment." /></div>

      {kind === "image" && (
        <div className="field" style={{ marginBottom: 0 }}>
          <label>Image</label>
          <div className="ph" style={{ height: 150, borderRadius: 7, overflow: "hidden" }}>
            {image ? <img src={image} alt="block" style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : <span className="ph-label">no image</span>}
          </div>
          <button type="button" className="btn" style={{ marginTop: 10 }} onClick={upload} disabled={busy}>
            <Icons.Image size={15}/> {busy ? "Uploading…" : (image ? "Replace image" : "Upload image")}
          </button>
        </div>
      )}
    </Modal>
  );
}

Object.assign(window, { Gallery });
