// Gallery, artwork detail (with pricing breakdown), commission builder
const { useEffect, useMemo, useRef, useState } = React;

// --- pricing engine
function computePrice(piece, opts) {
  const surfaceMul = { canvas: 1.0, wall: 1.6, wearable: 0.7, furniture: 1.4, shoes: 0.55, helmet: 0.6, skate: 0.5, interior: 2.4, glass: 0.9, metal: 1.1, digital: 0.8 };
  const sizeMul   = { S: 0.7, M: 1.0, L: 1.4, XL: 1.9 };
  const frameAdd  = { none: 0, wood: 320, oak: 540, brass: 880, museum: 1400 };
  const textureMul= { Subtle: 1.0, Layered: 1.18, Heavy: 1.36, Sculptural: 1.6 };
  const realismMul= { Atmospheric: 0.95, Figurative: 1.1, Hyperreal: 1.3 };
  const rushAdd   = { Standard: 0, Priority: 880, Rush: 2200 };

  const base = piece.basePrice;
  const sub =
    base
    * (sizeMul[opts.size] ?? 1)
    * (textureMul[opts.texture] ?? 1)
    * (realismMul[opts.realism] ?? 1)
    * (surfaceMul[opts.surface] ?? 1);
  const frame = frameAdd[opts.frame] ?? 0;
  const rush = rushAdd[opts.rush] ?? 0;
  const custom = opts.customDepth * 180; // 0..5
  return {
    base: Math.round(sub),
    frame, rush, custom,
    total: Math.round(sub + frame + rush + custom),
    hours: Math.round(piece.hours * (sizeMul[opts.size] ?? 1) * (textureMul[opts.texture] ?? 1)),
  };
}

const fmt = (n) => "$" + n.toLocaleString("en-US");

// --- gallery (editorial mosaic)
function Gallery({ artworks, onOpen, accentTo }) {
  // editorial layout — six tiles with intentional asymmetry
  const layout = [
    { col: "1 / span 7", row: "span 14", scale: "lg" },
    { col: "8 / span 5", row: "span 9",  scale: "md" },
    { col: "8 / span 5", row: "span 5",  scale: "sm" },
    { col: "1 / span 4", row: "span 8",  scale: "md" },
    { col: "5 / span 4", row: "span 8",  scale: "md" },
    { col: "9 / span 4", row: "span 8",  scale: "md" },
    { col: "1 / span 6", row: "span 9",  scale: "lg" },
    { col: "7 / span 6", row: "span 9",  scale: "lg" },
  ];
  return (
    <div className="gallery-grid">
      {artworks.map((a, i) => {
        const cell = layout[i % layout.length];
        return (
          <article
            key={a.id}
            className="tile"
            style={{ gridColumn: cell.col, gridRow: cell.row }}
            data-cursor="Open"
            onMouseEnter={() => accentTo(a.accent)}
            onClick={() => onOpen(a)}
          >
            <div className="tile-inner">
              <ArtSurface piece={a} density={cell.scale === "lg" ? 1.1 : 0.85} />
              <div className="tile-shade" />
              <div className="tile-meta">
                <div className="tile-meta-row">
                  <span className="m-num">{String(i + 1).padStart(2, "0")}</span>
                  <span className="m-cat">{a.category}</span>
                </div>
                <h3 className="tile-title">{a.title}</h3>
                <div className="tile-meta-row tile-meta-bot">
                  <span>{a.dimensions}</span>
                  <span>{fmt(a.basePrice)}</span>
                </div>
              </div>
            </div>
          </article>
        );
      })}
    </div>
  );
}

// --- detail modal
function ArtworkDetail({ piece, onClose, accentTo }) {
  const [opts, setOpts] = useState({
    size: "M", surface: piece.surfaces[0] || "canvas",
    frame: "none", texture: piece.complexity === "Heavy texture" ? "Heavy" : "Layered",
    realism: "Figurative", rush: "Standard", customDepth: 1,
  });
  useEffect(() => { accentTo(piece.accent); }, [piece, accentTo]);
  const price = useMemo(() => computePrice(piece, opts), [piece, opts]);
  const set = (k, v) => setOpts(o => ({ ...o, [k]: v }));

  // ESC close
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [onClose]);

  return (
    <div className="detail-root" onClick={onClose}>
      <div className="detail-shell" onClick={(e) => e.stopPropagation()}>
        <button className="detail-close" onClick={onClose} data-cursor="Close" aria-label="Close">
          <span /> <span />
        </button>

        <header className="detail-head">
          <div className="d-eyebrow">
            <span>SNIGDHA · {piece.category}</span>
            <span>{piece.year} · {piece.edition}</span>
          </div>
          <h2 className="d-title">{piece.title}</h2>
          <p className="d-tagline">{piece.tagline}</p>
        </header>

        <div className="detail-body">
          <figure className="detail-canvas">
            <div className="detail-frame">
              <ArtSurface piece={piece} density={1.4} />
            </div>
            <figcaption className="detail-caption">
              <div><span>Medium</span><b>{piece.medium}</b></div>
              <div><span>Dimensions</span><b>{piece.dimensions}</b></div>
              <div><span>Hours invested</span><b>{piece.hours} h</b></div>
              <div><span>Availability</span><b>{piece.availability}</b></div>
            </figcaption>
          </figure>

          <aside className="detail-aside">
            <h3 className="aside-title">
              <span className="t-num">II.</span> Configure the work
            </h3>

            <Field label="Size">
              {["S","M","L","XL"].map(v =>
                <Chip key={v} active={opts.size===v} onClick={()=>set("size", v)}>{v}</Chip>
              )}
            </Field>

            <Field label="Surface">
              {["canvas","wall","wearable","furniture","glass","metal"].map(v =>
                <Chip key={v} active={opts.surface===v} onClick={()=>set("surface", v)}>{v}</Chip>
              )}
            </Field>

            <Field label="Framing">
              {[["none","Unframed"],["wood","Walnut"],["oak","Oak"],["brass","Brass"],["museum","Museum"]].map(([k,l]) =>
                <Chip key={k} active={opts.frame===k} onClick={()=>set("frame", k)}>{l}</Chip>
              )}
            </Field>

            <Field label="Texture complexity">
              {["Subtle","Layered","Heavy","Sculptural"].map(v =>
                <Chip key={v} active={opts.texture===v} onClick={()=>set("texture", v)}>{v}</Chip>
              )}
            </Field>

            <Field label="Realism">
              {["Atmospheric","Figurative","Hyperreal"].map(v =>
                <Chip key={v} active={opts.realism===v} onClick={()=>set("realism", v)}>{v}</Chip>
              )}
            </Field>

            <Field label="Custom depth" hint={["Faithful","One twist","Two twists","Reimagined","Bespoke","Co-authored"][opts.customDepth]}>
              <input
                type="range" min="0" max="5" step="1"
                value={opts.customDepth}
                onChange={(e) => set("customDepth", parseInt(e.target.value))}
                className="ranger"
                style={{ accentColor: piece.accent }}
              />
            </Field>

            <Field label="Delivery">
              {[["Standard","6–10 wk"],["Priority","4–6 wk"],["Rush","≤ 3 wk"]].map(([k,l]) =>
                <Chip key={k} active={opts.rush===k} onClick={()=>set("rush", k)}>{l}</Chip>
              )}
            </Field>

            <div className="price-card" style={{ borderColor: piece.accent + "55" }}>
              <div className="price-row"><span>Base · sized</span><span>{fmt(price.base)}</span></div>
              {price.frame > 0 && <div className="price-row"><span>Framing</span><span>{fmt(price.frame)}</span></div>}
              {price.custom > 0 && <div className="price-row"><span>Customization</span><span>{fmt(price.custom)}</span></div>}
              {price.rush > 0 && <div className="price-row"><span>Priority</span><span>{fmt(price.rush)}</span></div>}
              <div className="price-rule" />
              <div className="price-row total">
                <span>Total · all in</span>
                <span style={{ color: piece.accent }}>{fmt(price.total)}</span>
              </div>
              <div className="price-meta">
                <span>≈ {price.hours} h studio time</span>
                <span>·</span>
                <span>signed · authenticity card</span>
              </div>

              <div className="price-cta">
                <button className="btn btn-primary" data-cursor="Reserve" style={{ background: piece.accent }}>
                  Reserve <span className="arr">↗</span>
                </button>
                <button className="btn btn-ghost" data-cursor="AR">View in your space</button>
              </div>

              <p className="price-fineprint">
                Pricing scales with detailing, scale, texture, materials, and creative complexity.
                Final number confirmed after a 20-minute studio call.
              </p>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

function Field({ label, hint, children }) {
  return (
    <div className="field">
      <div className="field-label">
        <span>{label}</span>
        {hint && <em>{hint}</em>}
      </div>
      <div className="field-body">{children}</div>
    </div>
  );
}
function Chip({ active, onClick, children }) {
  return (
    <button
      type="button"
      className={`chip ${active ? "is-active" : ""}`}
      onClick={onClick}
      data-cursor=""
    >{children}</button>
  );
}

// --- commission builder (multi-step)
function CommissionBuilder({ surfaces }) {
  const STEPS = ["Surface", "Style", "Scale", "Story", "Send"];
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    surface: "wall",
    style: "Atmospheric",
    palette: "Warm",
    scale: "Mid (4-6 ft)",
    timeline: "8 weeks",
    budget: "5–10k",
    note: "",
    name: "",
    email: "",
  });
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));

  // Replace with your Google Apps Script Web App deployment URL
  const FORM_ENDPOINT = "PASTE_YOUR_WEB_APP_URL_HERE";

  const sendInquiry = async () => {
    if (!data.email) { alert("Please add an email so I can reply."); return; }
    setSending(true);
    try {
      await fetch(FORM_ENDPOINT, {
        method: "POST",
        mode: "no-cors",
        body: JSON.stringify({ ...data, sentAt: new Date().toISOString() }),
      });
      setSent(true);
    } catch (err) {
      alert("Send failed — please email studio@snigdha.art directly.");
    } finally {
      setSending(false);
    }
  };

  const goto = (i) => setStep(Math.max(0, Math.min(STEPS.length - 1, i)));

  return (
    <div className="commission">
      <div className="commission-rail">
        <div className="rail-eyebrow">Commission · 04</div>
        <h2 className="rail-title">
          <em>Bring me</em><br/>
          your surface,<br/>
          and a feeling.
        </h2>
        <p className="rail-body">
          A jacket, a ceiling, a console, a wall that feels too quiet.
          The brief begins here. We'll meet in five short steps —
          then on a call, in the studio, or in your room.
        </p>
        <ul className="rail-list">
          {surfaces.slice(0, 7).map(s => (
            <li key={s.id}>
              <span className="rl-dot" />
              <span className="rl-label">{s.label}</span>
              <span className="rl-note">{s.note}</span>
            </li>
          ))}
        </ul>
      </div>

      <div className="commission-form">
        <div className="form-stepper">
          {STEPS.map((s, i) => (
            <button key={s} className={`stp ${i===step?"is-on":""} ${i<step?"is-done":""}`} onClick={() => goto(i)} data-cursor="">
              <span className="stp-n">{String(i+1).padStart(2,"0")}</span>
              <span className="stp-l">{s}</span>
            </button>
          ))}
        </div>

        <div className="form-stage">
          {step === 0 && (
            <Step title="Where will the art live?">
              <div className="grid-3">
                {surfaces.map(s => (
                  <label key={s.id} className={`surface-card ${data.surface===s.id?"is-on":""}`} data-cursor="Pick">
                    <input type="radio" name="surface" checked={data.surface===s.id} onChange={()=>set("surface", s.id)} />
                    <div className="sc-label">{s.label}</div>
                    <div className="sc-note">{s.note}</div>
                    <div className="sc-scale">×{s.scale.toFixed(2)}</div>
                  </label>
                ))}
              </div>
            </Step>
          )}

          {step === 1 && (
            <Step title="Pick a register.">
              <div className="grid-2">
                {[
                  ["Atmospheric", "Mood, weather, low contrast."],
                  ["Figurative",  "Bodies, objects, recognisable forms."],
                  ["Abstract",    "Gesture, mark, surface."],
                  ["Hyperreal",   "Detail at the limits."],
                ].map(([k, sub]) => (
                  <label key={k} className={`mode-card ${data.style===k?"is-on":""}`} data-cursor="Pick">
                    <input type="radio" name="style" checked={data.style===k} onChange={()=>set("style", k)} />
                    <strong>{k}</strong><span>{sub}</span>
                  </label>
                ))}
              </div>
              <div className="palette-row">
                {["Warm","Cool","Earthen","Monochrome","Jewel","Pastel"].map(p => (
                  <button key={p} type="button" className={`pal ${data.palette===p?"is-on":""}`} onClick={()=>set("palette", p)} data-cursor="">
                    <span className={`pal-swatch s-${p.toLowerCase()}`} />{p}
                  </button>
                ))}
              </div>
            </Step>
          )}

          {step === 2 && (
            <Step title="Scale & schedule.">
              <div className="grid-2">
                <Field label="Size">
                  <div className="chips">
                  {["Intimate (≤ 2 ft)","Mid (4-6 ft)","Statement (8-12 ft)","Architectural (12 ft+)"].map(v =>
                    <Chip key={v} active={data.scale===v} onClick={()=>set("scale", v)}>{v}</Chip>
                  )}
                  </div>
                </Field>
                <Field label="Timeline">
                  <div className="chips">
                  {["4 weeks","8 weeks","12 weeks","Open"].map(v =>
                    <Chip key={v} active={data.timeline===v} onClick={()=>set("timeline", v)}>{v}</Chip>
                  )}
                  </div>
                </Field>
                <Field label="Budget">
                  <div className="chips">
                  {["≤ 2k","2–5k","5–10k","10–25k","25k+"].map(v =>
                    <Chip key={v} active={data.budget===v} onClick={()=>set("budget", v)}>{v}</Chip>
                  )}
                  </div>
                </Field>
              </div>
            </Step>
          )}

          {step === 3 && (
            <Step title="Tell me the feeling.">
              <textarea
                className="story"
                placeholder="The room faces north. My grandmother's coat is the colour I keep coming back to. We listen to a lot of Arvo Pärt. I don't know what I want — only what I want it to feel like."
                value={data.note}
                onChange={(e)=>set("note", e.target.value)}
                rows={9}
              />
              <div className="upload">
                <div className="upload-box" data-cursor="Upload">
                  <span className="up-plus">+</span>
                  <span>Drop reference images, room photos, or a Pinterest URL</span>
                </div>
              </div>
            </Step>
          )}

          {step === 4 && (
            <Step title={sent ? "Sent." : "Ready."}>
              {sent ? (
                <p style={{ fontFamily: "var(--font-display)", fontSize: 22, color: "var(--bone)", lineHeight: 1.5, maxWidth: "44ch" }}>
                  Thank you, {data.name || "friend"}. Your brief has reached the studio. I'll write back to <em style={{ color: "var(--accent)" }}>{data.email}</em> within 48 hours.
                </p>
              ) : (
                <React.Fragment>
                  <div className="contact-row">
                    <input
                      className="contact-input"
                      placeholder="Your name"
                      value={data.name}
                      onChange={(e) => set("name", e.target.value)}
                    />
                    <input
                      className="contact-input"
                      type="email"
                      placeholder="Email"
                      value={data.email}
                      onChange={(e) => set("email", e.target.value)}
                    />
                  </div>
                  <dl className="summary">
                    <Row k="Surface" v={(surfaces.find(s=>s.id===data.surface)||{}).label} />
                    <Row k="Register" v={`${data.style} · ${data.palette}`} />
                    <Row k="Scale" v={data.scale} />
                    <Row k="Timeline" v={data.timeline} />
                    <Row k="Budget" v={data.budget} />
                    <Row k="Note" v={data.note ? data.note.slice(0, 140) + (data.note.length > 140 ? "…" : "") : "—"} />
                  </dl>
                  <div className="send-row">
                    <button
                      className="btn btn-primary"
                      data-cursor="Send"
                      onClick={sendInquiry}
                      disabled={sending}
                    >
                      {sending ? "Sending…" : "Send to studio"} <span className="arr">↗</span>
                    </button>
                    <span className="send-meta">
                      Replies within 48 h · No-cost first call
                    </span>
                  </div>
                </React.Fragment>
              )}
            </Step>
          )}
        </div>

        <div className="form-foot">
          <button className="btn btn-ghost" disabled={step===0} onClick={()=>goto(step-1)} data-cursor="">
            ← Back
          </button>
          <div className="prog">
            <div className="prog-bar" style={{ width: ((step+1)/STEPS.length*100) + "%" }} />
          </div>
          <button className="btn btn-ghost" disabled={step===STEPS.length-1} onClick={()=>goto(step+1)} data-cursor="">
            Continue →
          </button>
        </div>
      </div>
    </div>
  );
}

function Step({ title, children }) {
  return (
    <div className="step">
      <h3 className="step-title">{title}</h3>
      <div className="step-body">{children}</div>
    </div>
  );
}
function Row({ k, v }) {
  return <React.Fragment><dt>{k}</dt><dd>{v || "—"}</dd></React.Fragment>;
}

Object.assign(window, { Gallery, ArtworkDetail, CommissionBuilder });
