// site-pages.jsx — Gallery, Shop, Commission, Detail overlay.

const { useState: _us2, useEffect: _ue2, useRef: _ur2, useMemo: _um2 } = React;

// ───────────────────────── Gallery ─────────────────────────

function Gallery({ openPainting, t }) {
  const { paintings, c } = useData();
  const [filter, setFilter] = React.useState('All');
  const [layout, setLayout] = React.useState(t.galleryLayout || 'grid');
  React.useEffect(() => { setLayout(t.galleryLayout || 'grid'); }, [t.galleryLayout]);

  const series = React.useMemo(
    () => ['All', ...Array.from(new Set(paintings.map(p => p.series)))],
    [paintings]
  );
  const filtered = React.useMemo(
    () => filter === 'All' ? paintings : paintings.filter(p => p.series === filter),
    [filter, paintings]
  );

  return (
    <main className="page page-gallery">
      <header className="g-header">
        <div className="g-kicker">
          <span className="hero-dot" />
          The gallery · {paintings.length} paintings
        </div>
        <h1 className="g-title">
          {c('gallery.titlePre')}<em>{c('gallery.titleEm')}</em>
        </h1>
        <p className="g-lede">{c('gallery.lede')}</p>
      </header>

      <div className="g-controls">
        <div className="g-filters" role="tablist">
          {series.map(s => (
            <button
              key={s}
              role="tab"
              aria-selected={filter === s}
              className={`g-filter ${filter === s ? 'is-on' : ''}`}
              onClick={() => setFilter(s)}
            >
              {s}
              <span className="g-filter-count">
                {s === 'All' ? paintings.length : paintings.filter(p => p.series === s).length}
              </span>
            </button>
          ))}
        </div>
        <div className="g-layout">
          <span className="g-layout-label">view</span>
          {[
            { k: 'grid',     label: 'grid' },
            { k: 'masonry',  label: 'masonry' },
            { k: 'salon',    label: 'salon wall' },
          ].map(opt => (
            <button
              key={opt.k}
              className={`g-layout-btn ${layout === opt.k ? 'is-on' : ''}`}
              onClick={() => setLayout(opt.k)}
            >
              {opt.label}
            </button>
          ))}
        </div>
      </div>

      {layout === 'grid' && (
        <div className="g-grid">
          {filtered.map((p, i) => (
            <PaintingCard key={p.id} p={p} onClick={() => openPainting(p)} seed={i + 40} />
          ))}
        </div>
      )}

      {layout === 'masonry' && (
        <div className="g-masonry">
          {filtered.map((p, i) => {
            const aspects = ['3 / 4', '4 / 5', '1 / 1', '5 / 6', '2 / 3'];
            const asp = aspects[i % aspects.length];
            return (
              <article className="m-card" key={p.id} onClick={() => openPainting(p)}>
                <PaintedPlaceholder src={p.image} palette={p.palette} aspect={asp} seed={i + 60} alt={p.title} label={`${p.title.toUpperCase()}`} />
                <div className="m-meta">
                  <div className="m-title">{p.title}</div>
                  <div className="m-sub">
                    <span>{p.size}</span>
                    <span className="dot">·</span>
                    <span>{p.year}</span>
                    <span className="dot">·</span>
                    <span>{p.available ? `€${p.price}` : <span className="sold script">sold</span>}</span>
                  </div>
                </div>
              </article>
            );
          })}
        </div>
      )}

      {layout === 'salon' && (
        <div className="g-salon">
          {/* Salon-style hung wall: mixed sizes, irregular placement */}
          {filtered.map((p, i) => {
            // Fixed-ish positioning using a seeded grid-ish layout
            const layouts = [
              { col: '1 / span 3', row: '1 / span 3', rot: -0.6 },
              { col: '4 / span 2', row: '1 / span 2', rot:  0.4 },
              { col: '6 / span 2', row: '1 / span 3', rot: -0.3 },
              { col: '8 / span 3', row: '1 / span 2', rot:  0.5 },
              { col: '4 / span 2', row: '3 / span 2', rot: -0.4 },
              { col: '8 / span 2', row: '3 / span 3', rot:  0.2 },
              { col: '1 / span 2', row: '4 / span 2', rot:  0.3 },
              { col: '3 / span 2', row: '5 / span 2', rot: -0.2 },
              { col: '5 / span 3', row: '5 / span 2', rot:  0.4 },
              { col: '10 / span 2', row: '4 / span 2', rot: -0.5 },
              { col: '1 / span 2', row: '6 / span 2', rot:  0.3 },
              { col: '8 / span 2', row: '6 / span 2', rot: -0.3 },
              { col: '10 / span 2', row: '6 / span 2', rot:  0.5 },
            ];
            const L = layouts[i % layouts.length];
            return (
              <div
                key={p.id}
                className="s-frame"
                style={{
                  gridColumn: L.col, gridRow: L.row,
                  transform: `rotate(${L.rot}deg)`,
                }}
                onClick={() => openPainting(p)}
                title={p.title}
              >
                <PaintedPlaceholder src={p.image} palette={p.palette} aspect="auto" seed={i + 80} showLabel={false} alt={p.title} style={{ height: '100%' }} />
                <div className="s-plaque">
                  <div className="s-plaque-name">{p.title}</div>
                  <div className="s-plaque-year">{p.year}</div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </main>
  );
}

// ───────────────────────── Shop ─────────────────────────

function Shop({ openPainting, t }) {
  const { paintings, c } = useData();
  const [sort, setSort] = React.useState('newest');
  const avail = React.useMemo(() => {
    const a = paintings.filter(p => p.available);
    if (sort === 'price-lo') a.sort((x, y) => x.price - y.price);
    if (sort === 'price-hi') a.sort((x, y) => y.price - x.price);
    if (sort === 'newest')   a.sort((x, y) => y.year - x.year);
    return a;
  }, [sort, paintings]);

  return (
    <main className="page page-shop">
      <header className="g-header">
        <div className="g-kicker">
          <span className="hero-dot" />
          {avail.length} originals available
        </div>
        <h1 className="g-title">
          {c('shop.titlePre')}<em>{c('shop.titleEm')}</em>
        </h1>
        <p className="g-lede">{c('shop.lede')}</p>
      </header>

      <div className="shop-bar">
        <div className="shop-note script">{c('shop.note')}</div>
        <div className="shop-sort">
          <span className="g-layout-label">sort</span>
          {[
            { k: 'newest',   label: 'newest' },
            { k: 'price-lo', label: 'price ↑' },
            { k: 'price-hi', label: 'price ↓' },
          ].map(opt => (
            <button
              key={opt.k}
              className={`g-layout-btn ${sort === opt.k ? 'is-on' : ''}`}
              onClick={() => setSort(opt.k)}
            >
              {opt.label}
            </button>
          ))}
        </div>
      </div>

      <div className="shop-grid">
        {avail.map((p, i) => (
          <article key={p.id} className="shop-card" onClick={() => openPainting(p)}>
            <div className="shop-media">
              <PaintedPlaceholder src={p.image} palette={p.palette} aspect="4 / 5" seed={i + 100} alt={p.title} label={`${p.title.toUpperCase()} — ${p.medium}`} />
              <div className="shop-no">№ {String(i + 1).padStart(2, '0')}</div>
            </div>
            <div className="shop-meta">
              <div className="shop-top">
                <div>
                  <div className="shop-title">{p.title}</div>
                  <div className="shop-series script">{p.series.toLowerCase()}</div>
                </div>
                <div className="shop-price">€{p.price.toLocaleString()}</div>
              </div>
              <div className="shop-specs">
                <div><span>Size</span>{p.size}</div>
                <div><span>Medium</span>{p.medium}</div>
                <div><span>Year</span>{p.year}</div>
              </div>
              <button className="btn btn-dark btn-sm" onClick={e => { e.stopPropagation(); openPainting(p); }}>
                View & enquire <span className="btn-arr">→</span>
              </button>
            </div>
          </article>
        ))}
      </div>
    </main>
  );
}

// ───────────────────────── Commission form ─────────────────────────

function Commission({ setPage, t }) {
  const { c } = useData();
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({
    name: '', email: '',
    subject: '', description: '',
    reference: null, referenceName: '',
    size: '40 × 50 cm', sizeCustom: '',
    medium: 'Oil on linen',
    budget: 1500,
    deadline: '',
    notes: '',
  });
  const [sent, setSent] = React.useState(false);

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const fileIn = React.useRef(null);
  const [dragOver, setDragOver] = React.useState(false);

  const handleFile = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => {
      update('reference', e.target.result);
      update('referenceName', file.name);
    };
    reader.readAsDataURL(file);
  };

  const steps = [
    { n: 1, label: 'About you' },
    { n: 2, label: 'The painting' },
    { n: 3, label: 'Details' },
    { n: 4, label: 'Review' },
  ];

  const budgetBrackets = [
    { label: 'Small study',  range: '€400 — €800',     min: 400 },
    { label: 'Medium',       range: '€800 — €1,800',   min: 1200 },
    { label: 'Large',        range: '€1,800 — €3,500', min: 2500 },
    { label: 'Statement',    range: '€3,500 +',        min: 4000 },
  ];

  const sizes = [
    '25 × 30 cm · study',
    '30 × 40 cm · small',
    '40 × 50 cm · medium',
    '50 × 70 cm · large',
    '60 × 80 cm · gallery',
    'Custom size',
  ];

  const mediums = ['Oil on panel', 'Oil on linen', 'Oil on canvas'];

  const canNext =
    (step === 1 && form.name && form.email) ||
    (step === 2 && form.subject) ||
    (step === 3 && form.size && form.medium && form.budget) ||
    step === 4;

  if (sent) {
    return (
      <main className="page page-commission">
        <div className="sent-wrap">
          <div className="sent-mark">
            <PaintedPlaceholder palette="floral-peach" aspect="1 / 1" seed={111} showLabel={false} />
          </div>
          <div className="sent-eyebrow script">— thank you, truly.</div>
          <h1 className="sent-title">Your note is in the studio.</h1>
          <p className="sent-body">
            I read every commission request myself, usually within a few days.
            You'll hear back from me at <strong>{form.email || 'your email'}</strong> with
            a few gentle questions and a small sketch proposal.
          </p>
          <div className="sent-receipt">
            <div className="sent-row"><span>For</span><b>{form.name}</b></div>
            <div className="sent-row"><span>Subject</span><b>{form.subject}</b></div>
            <div className="sent-row"><span>Size</span><b>{form.size === 'Custom size' ? form.sizeCustom || 'Custom' : form.size}</b></div>
            <div className="sent-row"><span>Medium</span><b>{form.medium}</b></div>
            <div className="sent-row"><span>Budget</span><b>€{Number(form.budget).toLocaleString()}</b></div>
            {form.deadline && <div className="sent-row"><span>By</span><b>{form.deadline}</b></div>}
          </div>
          <div className="sent-actions">
            <button className="btn btn-dark" onClick={() => setPage('gallery')}>Back to the gallery</button>
            <button className="btn btn-ghost" onClick={() => { setSent(false); setStep(1); setForm({ ...form, subject: '', description: '', reference: null, referenceName: '' }); }}>
              Send another
            </button>
          </div>
        </div>
      </main>
    );
  }

  return (
    <main className="page page-commission">
      <header className="c-header">
        <div className="c-header-left">
          <div className="g-kicker">
            <span className="hero-dot" />
            {c('commission.kicker')}
          </div>
          <h1 className="g-title">
            {c('commission.titlePre')}<em>{c('commission.titleEm')}</em>
          </h1>
          <p className="g-lede">{c('commission.lede')}</p>
          <div className="c-sig script">{c('commission.signature')}</div>
        </div>
        <div className="c-header-right">
          <div className="c-timeline">
            <div className="c-timeline-title">{c('commission.timelineTitle')}</div>
            <ol>
              <li><b>01</b> You send this note</li>
              <li><b>02</b> I reply with a sketch & quote</li>
              <li><b>03</b> 40% deposit, I begin painting</li>
              <li><b>04</b> Progress photos, your notes</li>
              <li><b>05</b> Final piece ships to your door</li>
            </ol>
          </div>
        </div>
      </header>

      <div className="c-stepbar">
        {steps.map((s, i) => (
          <button
            key={s.n}
            className={`c-step ${step === s.n ? 'is-on' : ''} ${step > s.n ? 'is-done' : ''}`}
            onClick={() => { if (step > s.n || (canNext && s.n === step + 1)) setStep(s.n); }}
          >
            <span className="c-step-n">{String(s.n).padStart(2, '0')}</span>
            <span className="c-step-l">{s.label}</span>
          </button>
        ))}
      </div>

      <form className="c-form" onSubmit={e => { e.preventDefault(); if (step < 4) setStep(step + 1); else setSent(true); }}>
        {/* Step 1 */}
        {step === 1 && (
          <div className="c-panel">
            <div className="c-pan-head">
              <div className="c-pan-no">01</div>
              <h2>A little about you</h2>
              <p>So I know who's writing.</p>
            </div>
            <div className="c-fields">
              <label className="c-field">
                <span>Your name</span>
                <input type="text" value={form.name} onChange={e => update('name', e.target.value)} placeholder="Full name" required />
              </label>
              <label className="c-field">
                <span>Email</span>
                <input type="email" value={form.email} onChange={e => update('email', e.target.value)} placeholder="you@studio.com" required />
              </label>
              <label className="c-field c-field-wide">
                <span>How did you find me? <em>(optional)</em></span>
                <input type="text" value={form.notes} onChange={e => update('notes', e.target.value)} placeholder="Instagram, a friend, a gallery..." />
              </label>
            </div>
          </div>
        )}

        {/* Step 2 */}
        {step === 2 && (
          <div className="c-panel">
            <div className="c-pan-head">
              <div className="c-pan-no">02</div>
              <h2>The painting</h2>
              <p>Describe what you'd like — in as much, or as little, detail as feels right.</p>
            </div>
            <div className="c-fields">
              <label className="c-field c-field-wide">
                <span>Subject</span>
                <input type="text" value={form.subject} onChange={e => update('subject', e.target.value)} placeholder="A portrait of my mother, a still life of pears on a linen..." required />
              </label>
              <label className="c-field c-field-wide">
                <span>Tell me more <em>(mood, setting, colours, meaning)</em></span>
                <textarea rows={5} value={form.description} onChange={e => update('description', e.target.value)} placeholder="She always sat by the window in the afternoon. I'd love a warm, quiet portrait — nothing posed..." />
              </label>

              <div className="c-field c-field-wide">
                <span>Reference image <em>(optional but very helpful)</em></span>
                <div
                  className={`c-drop ${dragOver ? 'is-over' : ''} ${form.reference ? 'has-file' : ''}`}
                  onDragOver={e => { e.preventDefault(); setDragOver(true); }}
                  onDragLeave={() => setDragOver(false)}
                  onDrop={e => { e.preventDefault(); setDragOver(false); handleFile(e.dataTransfer.files[0]); }}
                  onClick={() => fileIn.current?.click()}
                >
                  {form.reference ? (
                    <div className="c-drop-preview">
                      <img src={form.reference} alt="reference" />
                      <div>
                        <div className="c-drop-name">{form.referenceName}</div>
                        <button type="button" className="c-drop-clear" onClick={e => { e.stopPropagation(); update('reference', null); update('referenceName', ''); }}>
                          remove
                        </button>
                      </div>
                    </div>
                  ) : (
                    <>
                      <div className="c-drop-icon">
                        <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2">
                          <path d="M4 15v3a2 2 0 002 2h12a2 2 0 002-2v-3"/><path d="M12 4v12"/><path d="M7 9l5-5 5 5"/>
                        </svg>
                      </div>
                      <div className="c-drop-text">
                        <b>Drop a photo here</b>
                        <span> or click to choose a file</span>
                      </div>
                      <div className="c-drop-hint script">photos of people, places, or anything that helps me see it with you</div>
                    </>
                  )}
                  <input ref={fileIn} type="file" accept="image/*" style={{ display: 'none' }} onChange={e => handleFile(e.target.files[0])} />
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Step 3 */}
        {step === 3 && (
          <div className="c-panel">
            <div className="c-pan-head">
              <div className="c-pan-no">03</div>
              <h2>Size, surface, and budget</h2>
              <p>The practical bits. Everything is negotiable.</p>
            </div>
            <div className="c-fields">
              <div className="c-field c-field-wide">
                <span>Canvas size</span>
                <div className="c-chips">
                  {sizes.map(s => (
                    <button type="button" key={s} className={`c-chip ${form.size === s ? 'is-on' : ''}`} onClick={() => update('size', s)}>
                      {s}
                    </button>
                  ))}
                </div>
                {form.size === 'Custom size' && (
                  <input type="text" value={form.sizeCustom} onChange={e => update('sizeCustom', e.target.value)} placeholder="e.g. 45 × 65 cm" style={{ marginTop: 10 }} />
                )}
              </div>

              <div className="c-field c-field-wide">
                <span>Medium</span>
                <div className="c-chips">
                  {mediums.map(m => (
                    <button type="button" key={m} className={`c-chip ${form.medium === m ? 'is-on' : ''}`} onClick={() => update('medium', m)}>
                      {m}
                    </button>
                  ))}
                </div>
              </div>

              <div className="c-field c-field-wide">
                <span>Budget <em>(sliding scale — I work with what feels right to you)</em></span>
                <div className="c-budget">
                  <input
                    type="range"
                    min="300" max="6000" step="50"
                    value={form.budget}
                    onChange={e => update('budget', Number(e.target.value))}
                    className="c-slider"
                  />
                  <div className="c-budget-val">€{Number(form.budget).toLocaleString()}</div>
                </div>
                <div className="c-brackets">
                  {budgetBrackets.map(b => (
                    <button type="button" key={b.label} className={`c-bracket ${Math.abs(form.budget - b.min) < 200 ? 'is-on' : ''}`} onClick={() => update('budget', b.min)}>
                      <div className="c-bracket-l">{b.label}</div>
                      <div className="c-bracket-r">{b.range}</div>
                    </button>
                  ))}
                </div>
              </div>

              <label className="c-field c-field-wide">
                <span>Deadline <em>(optional)</em></span>
                <input type="date" value={form.deadline} onChange={e => update('deadline', e.target.value)} />
                <span className="c-hint script">most commissions take 6 — 10 weeks.</span>
              </label>
            </div>
          </div>
        )}

        {/* Step 4 */}
        {step === 4 && (
          <div className="c-panel">
            <div className="c-pan-head">
              <div className="c-pan-no">04</div>
              <h2>A last look</h2>
              <p>Everything feel right?</p>
            </div>
            <div className="c-review">
              <div className="c-review-left">
                {form.reference ? (
                  <img src={form.reference} alt="reference" className="c-review-img" />
                ) : (
                  <div className="c-review-img">
                    <PaintedPlaceholder palette="floral-peach" aspect="1 / 1" seed={222} showLabel={false} />
                  </div>
                )}
                <div className="c-review-subject script">“{form.subject || 'your painting'}”</div>
              </div>
              <dl className="c-review-list">
                <div><dt>From</dt><dd>{form.name}<span>· {form.email}</span></dd></div>
                <div><dt>Subject</dt><dd>{form.subject || '—'}</dd></div>
                {form.description && <div><dt>Notes</dt><dd className="c-review-desc">{form.description}</dd></div>}
                <div><dt>Size</dt><dd>{form.size === 'Custom size' ? form.sizeCustom || 'Custom' : form.size}</dd></div>
                <div><dt>Medium</dt><dd>{form.medium}</dd></div>
                <div><dt>Budget</dt><dd>€{Number(form.budget).toLocaleString()}</dd></div>
                {form.deadline && <div><dt>Deadline</dt><dd>{form.deadline}</dd></div>}
              </dl>
            </div>
          </div>
        )}

        {/* Nav */}
        <div className="c-nav">
          <button type="button" className="btn btn-ghost" onClick={() => step > 1 ? setStep(step - 1) : setPage('home')}>
            ← {step > 1 ? 'Back' : 'Home'}
          </button>
          <div className="c-nav-dots">
            {steps.map(s => (
              <span key={s.n} className={`c-dot ${step === s.n ? 'is-on' : ''} ${step > s.n ? 'is-done' : ''}`} />
            ))}
          </div>
          <button type="submit" className="btn btn-dark" disabled={!canNext}>
            {step === 4 ? 'Send to Atiye' : 'Continue'} <span className="btn-arr">→</span>
          </button>
        </div>
      </form>
    </main>
  );
}

// ───────────────────────── Detail overlay ─────────────────────────

function DetailOverlay({ painting, onClose, setPage }) {
  React.useEffect(() => {
    if (!painting) return;
    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 = '';
    };
  }, [painting, onClose]);

  if (!painting) return null;
  const p = painting;

  return (
    <div className="overlay" onClick={onClose}>
      <div className="overlay-sheet" onClick={e => e.stopPropagation()}>
        <button className="overlay-close" onClick={onClose} aria-label="close">✕</button>
        <div className="ov-media">
          <PaintedPlaceholder src={p.image} palette={p.palette} aspect="4 / 5" seed={999} showLabel={false} fit="contain" alt={p.title} />
          <div className="ov-plate">
            <span>№ {p.id.toUpperCase()}</span>
            <span>{p.year}</span>
          </div>
        </div>
        <div className="ov-info">
          <div className="ov-series script">{p.series.toLowerCase()}</div>
          <h2 className="ov-title">{p.title}</h2>
          {p.note && <p className="ov-note script">“{p.note}”</p>}
          <dl className="ov-specs">
            <div><dt>Medium</dt><dd>{p.medium}</dd></div>
            <div><dt>Dimensions</dt><dd>{p.size}</dd></div>
            <div><dt>Year</dt><dd>{p.year}</dd></div>
            <div><dt>Edition</dt><dd>One of one · signed on reverse</dd></div>
          </dl>
          <div className="ov-price-row">
            {p.available ? (
              <>
                <div className="ov-price">€{p.price.toLocaleString()}</div>
                <div className="ov-ship script">free shipping · ready in 5 days</div>
              </>
            ) : (
              <div className="ov-sold">
                <span className="sold script">sold</span>
                <span className="ov-ship">From a private collection. Similar pieces available on commission.</span>
              </div>
            )}
          </div>
          <div className="ov-actions">
            {p.available ? (
              <>
                <button className="btn btn-dark" onClick={() => { onClose(); setPage('commission'); }}>
                  Enquire about this piece <span className="btn-arr">→</span>
                </button>
                <button className="btn btn-ghost" onClick={() => { onClose(); setPage('shop'); }}>
                  Back to shop
                </button>
              </>
            ) : (
              <button className="btn btn-dark" onClick={() => { onClose(); setPage('commission'); }}>
                Commission something similar <span className="btn-arr">→</span>
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Gallery, Shop, Commission, DetailOverlay });
