/* global React, ChamberChrome */
const { useState, useEffect } = React;

function Prints({ onBack }) {
  const cat = window.PRINTS_CATALOGUE || {};
  const photos = window.DARSHAN || [];
  const available = (cat.availableIds || []).map(id => photos.find(p => p.id === id)).filter(Boolean);

  const [picked, setPicked] = useState(null);

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") { picked ? setPicked(null) : onBack(); } };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [picked, onBack]);

  if (picked) {
    return <PrintConfigurator photo={picked} catalogue={cat} onBack={() => setPicked(null)} />;
  }

  return (
    <div className="chamber chamber-prints">
      <ChamberChrome onBack={onBack} num="ii." dev="मुद्रण" en="Prints" />

      <header className="chamber-head">
        <h1 className="chamber-title">
          owning a fragment <em>of silence.</em>
        </h1>
        <p className="chamber-sub">
          twelve photographs are offered as limited, hand-numbered prints on archival cotton-rag. each is signed in archival ink on the reverse, and posted in an acid-free portfolio sleeve.
        </p>
      </header>

      {/* The note */}
      <div className="prints-note">
        <div className="rule"></div>
        <p>{cat.note}</p>
      </div>

      {/* Paper + size legend */}
      <div className="prints-legend">
        <div className="legend-col">
          <div className="legend-eyebrow">कागज़ — papers</div>
          <ul>
            {(cat.papers || []).map(p => (
              <li key={p.key}>
                <b>{p.name}</b>{p.pop && <span className="pop">{p.pop}</span>}
                <span>— {p.blurb}</span>
              </li>
            ))}
          </ul>
        </div>
        <div className="legend-col">
          <div className="legend-eyebrow">आकार — sizes &amp; editions</div>
          <ul>
            {(cat.sizes || []).map(s => (
              <li key={s.key}>
                <b>{s.label}</b>
                <span>{s.dimension} · {s.edition}</span>
                <span className="price">₹{s.priceINR.toLocaleString("en-IN")} · ${s.priceUSD}</span>
              </li>
            ))}
          </ul>
        </div>
        <div className="legend-col">
          <div className="legend-eyebrow">डाक — shipping</div>
          <ul>
            {(cat.shipping || []).map(s => (
              <li key={s.region}>
                <b>{s.region}</b>
                <span>{s.time}</span>
                <span className="quiet">{s.fee}</span>
              </li>
            ))}
          </ul>
        </div>
      </div>

      <div className="prints-section-head">
        <h2 className="prints-section-title">— twelve photographs offered —</h2>
        <p className="prints-section-sub">click any photograph to configure your edition.</p>
      </div>

      <div className="prints-grid">
        {available.map((p, i) => {
          const cat2 = window.PRINTS_CATALOGUE;
          const minPrice = Math.min(...(cat2.sizes || []).map(s => s.priceINR));
          return (
            <button key={p.id} className="print-card" onClick={() => setPicked(p)} data-cursor>
              <div className="print-card-img">
                <img src={p.file} alt={p.title} loading="lazy" />
                <div className="print-card-overlay">
                  <span>configure →</span>
                </div>
              </div>
              <div className="print-card-meta">
                <div className="print-card-num">{p.id}</div>
                <div className="print-card-titles">
                  <span className="dev">{p.dev}</span>
                  <span className="ttl">{p.title}</span>
                </div>
                <div className="print-card-price">from ₹{minPrice.toLocaleString("en-IN")}</div>
              </div>
            </button>
          );
        })}
      </div>

      <footer className="chamber-foot">
        <div className="rule"></div>
        <p>for custom sizes, exhibition enquiries, or to commission a portfolio — write to rahul@darshan.archive</p>
      </footer>
    </div>
  );
}

function PrintConfigurator({ photo, catalogue, onBack }) {
  const [size, setSize] = useState(catalogue.sizes[1]);   // default medium
  const [paper, setPaper] = useState(catalogue.papers[0]); // default cotton
  const [framed, setFramed] = useState(false);
  const [added, setAdded] = useState(false);

  const framedSurcharge = framed ? 2400 : 0;
  const total = size.priceINR + framedSurcharge;

  return (
    <div className="chamber chamber-print-config">
      <ChamberChrome onBack={onBack} num={photo.id} dev={photo.dev} en="Print Configurator" hint="back to the catalogue" />

      <div className="config-body">
        <div className="config-photo">
          <div className="config-photo-frame" data-framed={framed}>
            <div className="config-photo-mat">
              <img src={photo.file} alt={photo.title} />
            </div>
          </div>
          <div className="config-photo-caption">
            <span className="dev">{photo.dev}</span>
            <span className="ttl">{photo.title}</span>
            <span className="loc">{photo.place} · {photo.year}</span>
          </div>
        </div>

        <div className="config-form">
          <div className="config-head">
            <div className="config-eyebrow">configuring print</div>
            <h2 className="config-title">{photo.title}</h2>
            <p className="config-line">{photo.line}</p>
          </div>

          <div className="config-group">
            <div className="group-label">आकार · size</div>
            <div className="group-options">
              {catalogue.sizes.map(s => (
                <button
                  key={s.key}
                  className={`group-opt ${size.key === s.key ? "active" : ""}`}
                  onClick={() => setSize(s)}
                  data-cursor
                >
                  <span className="opt-label">{s.label}</span>
                  <span className="opt-sub">{s.dimension}</span>
                  <span className="opt-edition">{s.edition}</span>
                  <span className="opt-price">₹{s.priceINR.toLocaleString("en-IN")}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="config-group">
            <div className="group-label">कागज़ · paper</div>
            <div className="group-options group-papers">
              {catalogue.papers.map(p => (
                <button
                  key={p.key}
                  className={`group-opt ${paper.key === p.key ? "active" : ""}`}
                  onClick={() => setPaper(p)}
                  data-cursor
                >
                  <span className="opt-label">{p.name}{p.pop && <i> · {p.pop}</i>}</span>
                  <span className="opt-sub">{p.blurb}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="config-group">
            <div className="group-label">ढाँचा · framing</div>
            <div className="group-options group-frame">
              <button className={`group-opt ${!framed ? "active" : ""}`} onClick={() => setFramed(false)} data-cursor>
                <span className="opt-label">unframed</span>
                <span className="opt-sub">posted flat in archival sleeve</span>
              </button>
              <button className={`group-opt ${framed ? "active" : ""}`} onClick={() => setFramed(true)} data-cursor>
                <span className="opt-label">walnut frame  + ₹2,400</span>
                <span className="opt-sub">hand-finished, with museum mat</span>
              </button>
            </div>
          </div>

          <div className="config-summary">
            <div className="summary-row">
              <span>{size.label} · {paper.name}</span>
              <span>₹{size.priceINR.toLocaleString("en-IN")}</span>
            </div>
            {framed && (
              <div className="summary-row">
                <span>walnut frame</span>
                <span>₹2,400</span>
              </div>
            )}
            <div className="summary-rule"></div>
            <div className="summary-total">
              <span>total</span>
              <span>₹{total.toLocaleString("en-IN")}</span>
            </div>
          </div>

          <button
            className={`config-add ${added ? "added" : ""}`}
            onClick={() => { setAdded(true); setTimeout(() => setAdded(false), 2400); }}
            data-cursor
          >
            <span className="dev">{added ? "धन्यवाद" : "मुद्रण"}</span>
            <span>{added ? "noted · the print is reserved" : "reserve this print"}</span>
            <span className="arrow">{added ? "✓" : "→"}</span>
          </button>

          <div className="config-fineprint">
            this is a portfolio archive · prints are made to order and posted within seven working days. <br/>
            for now, "reserve" simply lets the photographer know — he will write to you to confirm.
          </div>
        </div>
      </div>
    </div>
  );
}

window.Prints = Prints;
