// sections.jsx — Hero, Gallery, Detail overlay, Process spread, Commission, Contact

const { useState, useMemo, useEffect } = React;

// ── Hero ──────────────────────────────────────────────────────────────
function Masthead() {
  return (
    <div className="masthead">
      <div className="mast-row">
        <span>Vol. VII · Spring/Summer 2026</span>
      </div>
    </div>
  );
}

function Hero({ onNav }) {
  return (
    <section className="hero" data-screen-label="Hero">
      <div className="hero-grid">
        <h1>
          Olena<br />
          <span className="amp">&amp;</span> the graphite<br />
          portrait.
        </h1>
        <div className="hero-meta">
          <p className="hero-lede">
            Pencil portraits drawn from the photographs you send me. Of someone you love. Of someone you have lost. Made slowly, by hand, on paper. Currently open for commissions.
          </p>
          <div className="eyebrow">In this issue ↓</div>
        </div>
      </div>

      <div className="hero-feature">
        <div className="hero-feature-img">
          <img src="images/IMG_20200810_175229841_Original.jpg" alt="Featured portrait" className="portrait-img" />
        </div>
        <div className="feature-caption">
          <div>
            <div className="figno">Fig. 01 — Featured</div>
            <h2>Solenne</h2>
          </div>
          <dl className="cap-meta">
            <dt>Year</dt><dd>2025</dd>
            <dt>Medium</dt><dd>Graphite, Paper</dd>
            <dt>Size</dt><dd>40 × 50 cm</dd>
            <dt>From</dt><dd>A single photograph</dd>
            <dt>Note</dt><dd>Past commission, not for sale</dd>
          </dl>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <button className="nav-cta" onClick={() => onNav('detail', 'w01')} style={{ alignSelf: 'flex-start' }}>See the drawing →</button>
            <button className="nav-cta" onClick={() => onNav('commission')} style={{ alignSelf: 'flex-start', background: 'var(--ink)', color: 'var(--paper)', borderColor: 'var(--ink)' }}>Commission a portrait →</button>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Gallery ───────────────────────────────────────────────────────────
function FilterBar({ filters, set, count }) {
  return (
    <div className="filterbar">
      {Object.keys(window.FILTERS).map((k) => (
        <div className="filter-group" key={k}>
          <span className="lbl">{k}</span>
          <div className="opts">
            {window.FILTERS[k].map((opt) => (
              <button key={opt} className="filter-chip" data-on={filters[k] === opt ? '1' : '0'} onClick={() => set(k, opt)}>
                {opt}
              </button>
            ))}
          </div>
        </div>
      ))}
      <span className="filter-count">{count} {count === 1 ? 'work' : 'works'}</span>
    </div>
  );
}

function WorkCard({ w, onOpen }) {
  return (
    <article className="work" onClick={() => onOpen(w.id)}>
      <div className={`work-img ${w.orientation}`}>
        <img src={w.img || ''} alt={`${w.title}, ${w.year}`} className="portrait-img" />
        <div className="overlay"><span className="view">Open ↗</span></div>
      </div>
      <div className="work-cap">
        <span className="figno">Fig. {w.no}</span>
        <h3>{w.titleIt ? <em>{w.title}</em> : w.title}</h3>
        <span className="work-meta">{w.year} · {w.size}</span>
      </div>
    </article>
  );
}

function Gallery({ layout, onOpen }) {
  const [filters, setFilters] = useState({ subject: 'All', size: 'All', year: 'All' });
  const set = (k, v) => setFilters((f) => ({ ...f, [k]: v }));
  const works = useMemo(() => window.WORKS.filter((w) => (
    (filters.size === 'All' || w.size === filters.size) &&
    (filters.subject === 'All' || w.subject === filters.subject) &&
    (filters.year === 'All' || String(w.year) === filters.year)
  )), [filters]);

  const cls = layout === 'masonry' ? 'gallery-masonry' : layout === 'strip' ? 'gallery-strip' : 'gallery-grid';

  return (
    <section className="sec" id="works" data-screen-label="Selected works">
      <header className="sec-head">
        <span className="num">§ 02</span>
        <h2>Past commissions</h2>
        <span className="sec-meta">{window.WORKS.length} drawings · 2023–2025 · archive only</span>
      </header>
      <FilterBar filters={filters} set={set} count={works.length} />
      <div className={cls}>
        {works.map((w) => <WorkCard key={w.id} w={w} onOpen={onOpen} />)}
      </div>
      {works.length === 0 && (
        <p className="eyebrow" style={{ padding: '40px 0', textAlign: 'center' }}>No works match these filters.</p>
      )}
    </section>
  );
}

// ── Spread (removed — quote treatment was too heavy) ──────────────────
function Spread() { return null; }

// ── Process ───────────────────────────────────────────────────────────
function Process() {
  return (
    <section className="sec" id="process" data-screen-label="Process">
      <header className="sec-head">
        <span className="num">§ 03</span>
        <h2>The studio</h2>
        <span className="sec-meta">A portrait, end to end</span>
      </header>
      <div className="process-grid">
        <div className="process-copy">
          <h3>From a photograph. Drawn the old way.</h3>
          <p className="dropcap">Every portrait begins with a conversation and the photographs you send me. A wedding, a christening, a last birthday, a quiet morning at the kitchen table. The image you choose matters as much as the drawing that follows.</p>
          <p>From there, pencils. Grades 2H through 6B, kneaded eraser, cotton paper, hours. I work between four and eight weeks depending on scale, sending one progress photograph at the halfway mark. Most drawings take six to ten weeks in total.</p>
          <div className="process-steps">
            <div className="process-step">
              <div className="step-num">01 · Brief</div>
              <h4>The first letter</h4>
              <p>You write to me. Who is this for, who is in the photograph, what should I know.</p>
            </div>
            <div className="process-step">
              <div className="step-num">02 · Photographs</div>
              <h4>Choosing the reference</h4>
              <p>You send me what you have. Together we choose the image, or piece one together from several.</p>
            </div>
            <div className="process-step">
              <div className="step-num">03 · Drawing</div>
              <h4>Long, quiet hours</h4>
              <p>Worked in the studio over four to twelve weeks. One progress photograph by post or email.</p>
            </div>
            <div className="process-step">
              <div className="step-num">04 · Delivery</div>
              <h4>Signed and shipped</h4>
              <p>Archival framing on request, otherwise rolled or boxed flat. Insured worldwide.</p>
            </div>
          </div>
        </div>
        <div className="process-art">
          <div className="pa-1"><img src="images/20210526_215700_Original.jpg" alt="Studio — wall of drawings" className="portrait-img" /></div>
          <div className="pa-2"><img src="images/IMG_20200708_201128036_Original.jpg" alt="Pencils, kneaded eraser" className="portrait-img" /></div>
          <div className="pa-3"><img src="images/IMG_20210121_170838_370_Original.jpg" alt="Detail, in progress" className="portrait-img" /></div>
        </div>
      </div>
    </section>
  );
}

// ── Commission ────────────────────────────────────────────────────────
function CommissionForm({ preselected, onPick }) {
  const [sent, setSent] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [form, setForm] = useState({
    name: '', email: '',
    subject: 'One person', tier: preselected || 'M',
    timeline: 'Within 3 months', notes: '',
  });
  useEffect(() => { if (preselected) setForm((f) => ({ ...f, tier: preselected })); }, [preselected]);
  const update = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const submit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/commission', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (!res.ok) {
        const json = await res.json().catch(() => ({}));
        throw new Error(json.detail || 'Something went wrong — please try again.');
      }
      setSent(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  if (sent) {
    return (
      <div className="form-sent">
        <div className="ok">✓ Letter received</div>
        <h4>Thank you, {form.name || 'friend'}.</h4>
        <p style={{ margin: 0, fontFamily: 'var(--serif)', fontSize: 19, lineHeight: 1.4, color: 'var(--ink-soft)' }}>
          I read every commission inquiry myself. You will hear from me within a week, usually sooner. If it is urgent, write again — sometimes the post sleeps.
        </p>
        <button className="filter-chip" style={{ alignSelf: 'flex-start', marginTop: 8 }} onClick={() => setSent(false)}>Write another</button>
      </div>
    );
  }

  return (
    <form className="commission-form" onSubmit={submit}>
      <p className="form-intro">
        Tell me about the person you'd like drawn.
      </p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div className="field-row">
          <div className="field"><label>Your name</label><input value={form.name} onChange={update('name')} placeholder="—" /></div>
          <div className="field"><label>Email</label><input type="email" value={form.email} onChange={update('email')} placeholder="—" required /></div>
        </div>
      </div>
      <div className="field"><label>Subject</label>
        <select value={form.subject} onChange={update('subject')}>
          <option>One person</option><option>A couple</option><option>A family or group</option>
        </select>
      </div>
      <div className="field"><label>Tier</label>
        <select value={form.tier} onChange={update('tier')}>
          <option value="S">Petite — from €900</option>
          <option value="M">Standard — from €1,800</option>
          <option value="L">Atelier — from €3,400</option>
          <option value="?">Not sure yet</option>
        </select>
      </div>
      <div className="field"><label>Timeline</label>
        <select value={form.timeline} onChange={update('timeline')}>
          <option>Within 3 months</option><option>3–6 months</option><option>For a specific date</option><option>No rush</option>
        </select>
      </div>
      <div className="field field-grid-full"><label>The story</label>
        <textarea value={form.notes} onChange={update('notes')} placeholder="Who is this for? What should I know?" />
      </div>
      {error && (
        <p role="alert" style={{ gridColumn: '1 / -1', margin: 0, fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--accent)' }}>
          {error}
        </p>
      )}
      <div className="form-submit">
        <span className="note">No deposit until we've spoken.</span>
        <button type="submit" className="btn-submit" disabled={loading}>
          {loading ? 'Sending…' : 'Send the letter →'}
        </button>
      </div>
    </form>
  );
}

function Commission({ onNav }) {
  const [picked, setPicked] = useState(null);
  return (
    <section className="sec" id="commission" data-screen-label="Commission">
      <header className="sec-head">
        <span className="num">§ 04</span>
        <h2>Commission a portrait</h2>
        <span className="sec-meta">Three tiers · open quarterly</span>
      </header>
      <div className="tiers">
        {window.TIERS.map((t) => (
          <article key={t.key} className="tier" data-featured={t.featured ? 1 : 0}>
            <div className="tier-tag">Tier {t.key} · {t.name}</div>
            <h3 className="tier-name">{t.name}</h3>
            <div>
              <div className="tier-price">{t.price}</div>
              <div className="tier-price-note">{t.note}</div>
            </div>
            <dl className="tier-meta">
              <dt>Size</dt><dd>{t.size}</dd>
              <dt>From</dt><dd>{t.sittings}</dd>
              <dt>Timeline</dt><dd>{t.timeline}</dd>
            </dl>
            <ul className="tier-includes">
              {t.includes.map((inc, i) => <li key={i}>{inc}</li>)}
            </ul>
            <button className="tier-pick" onClick={() => { setPicked(t.key); document.getElementById('commission-form-anchor')?.scrollIntoView({ behavior: 'smooth', block: 'start' }); }}>
              Begin with {t.name} →
            </button>
          </article>
        ))}
      </div>
      <div id="commission-form-anchor" style={{ scrollMarginTop: 80 }}>
        <CommissionForm preselected={picked} />
      </div>
    </section>
  );
}

// ── Detail overlay ────────────────────────────────────────────────────
function Detail({ id, onClose, onOpen }) {
  const w = window.WORKS.find((x) => x.id === id);
  const idx = window.WORKS.findIndex((x) => x.id === id);
  const prev = window.WORKS[(idx - 1 + window.WORKS.length) % window.WORKS.length];
  const next = window.WORKS[(idx + 1) % window.WORKS.length];

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft') onOpen(prev.id);
      if (e.key === 'ArrowRight') onOpen(next.id);
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [prev, next, onOpen, onClose]);

  if (!w) return null;
  return (
    <div className="detail-overlay" data-screen-label={`Detail: ${w.title}`}>
      <div className="detail-bar">
        <span>Fig. {w.no} / {String(window.WORKS.length).padStart(2, '0')} · {w.title}</span>
        <div className="nav-arrows">
          <button onClick={() => onOpen(prev.id)} aria-label="Previous">←</button>
          <button onClick={() => onOpen(next.id)} aria-label="Next">→</button>
          <button className="detail-close" onClick={onClose}>✕</button>
        </div>
      </div>
      <div className="detail-body">
        <div className="detail-img">
          <img src={w.img || ''} alt={`${w.title}, ${w.year}`} className="portrait-img" />
        </div>
        <div className="detail-info">
          <div>
            <div className="figno">Fig. {w.no} — {w.subject}</div>
            <h2>{w.titleIt ? <em>{w.title}</em> : w.title}</h2>
          </div>
          <p className="lede">{w.lede}</p>
          <dl className="detail-meta">
            <dt>Year</dt><dd>{w.year}</dd>
            <dt>Medium</dt><dd>{w.medium}</dd>
            <dt>Dimensions</dt><dd>{w.dim}</dd>
            <dt>Size class</dt><dd>{w.size === 'S' ? 'Small' : w.size === 'M' ? 'Medium' : 'Large'}</dd>
            <dt>Subject</dt><dd>{w.subject}</dd>
            <dt>Note</dt><dd>Past commission · archive only</dd>
          </dl>
          {w.notes && (
            <p style={{ fontFamily: 'var(--serif)', fontSize: 17, lineHeight: 1.45, color: 'var(--ink-soft)', margin: 0 }}>
              <span className="eyebrow" style={{ display: 'block', marginBottom: 8 }}>Studio note</span>
              {w.notes}
            </p>
          )}
          <div className="detail-actions">
            <button className="btn primary" onClick={() => { onClose(); document.getElementById('commission')?.scrollIntoView({ behavior: 'smooth' }); }}>Commission a portrait like this →</button>
            <button className="btn" onClick={() => onOpen(next.id)}>Next drawing →</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Footer / Contact ──────────────────────────────────────────────────
function Foot() {
  return (
    <footer className="foot" id="contact" data-screen-label="Contact / Footer">
      <div className="foot-grid">
        <h3 className="foot-call">
          Send a photograph.<br />Receive a portrait.
        </h3>
        <div className="foot-block">
          <h5>Correspondence</h5>
          <a href="mailto:olenapodduyev@icloud.com">olenapodduyev@icloud.com</a>
          <a href="https://www.instagram.com/olena.portraits/" target="_blank" rel="noopener">Instagram · @olena.portraits</a>
          <a href="https://www.facebook.com/people/Olena-Portraits/100077370323138/" target="_blank" rel="noopener">Facebook · Olena Portraits</a>
        </div>
      </div>
      <div className="colophon">
        <span>© 2026 Olena Podduyev</span>
        <span>Set in Instrument Serif &amp; DM Sans</span>
        <span>Vol. VII · Spring/Summer 2026</span>
      </div>
    </footer>
  );
}

Object.assign(window, { Masthead, Hero, Gallery, Spread, Process, Commission, Detail, Foot });
