// ── add-release-edit-pane.jsx ──────────────────────────────────
// EDIT pane for the Add Release modal. Replaces the old 6-step wizard
// (BASICS / DETAILS / LABEL / TRACKS / ART / DIST) with the Add-Work
// Rights pattern: optional helper note + accordion sections, plus a
// left rail listing Editions. Currently only Edition 1 exists at
// create time; +ADD EDITION is disabled with a tooltip directing users
// to the Release detail page after first save.
//
// All form helpers (_ArInp, _ArLbl, _ArSeg, _arReleaseTypes,
// _arConfigs, _arParentalOpts, _AR_DSPS, _AR_ART_SWATCHES,
// _arCreditLine, _ArArtistsField, _ArTrackRow, _ArPicker) are defined
// in add-release-modal.jsx and shared via global scope (Babel inline
// transpilation makes top-level consts module-scoped per script tag,
// so we re-pluck them off the IIFE-shared `window` namespace via the
// `_AR` props bundle the host passes in).
//
// Exposes window.ReleaseEditionEditPane({ form, set, AR, … }).

const { useState: _RxS } = React;

function _RxSection({ id, title, icon, right, children, defaultOpen = false, forceOpen = false }) {
  const [open, setOpen] = _RxS(defaultOpen || forceOpen);
  // In wizard/forceOpen mode, render flat — no header, no collapse
  if (forceOpen) {
    return (
      <div style={{ marginBottom: 14 }}>
        {right &&
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 6 }}>{right}</div>
        }
        {children}
      </div>);

  }
  return (
    <section id={id} style={{
      marginBottom: 12,
      border: '1px solid var(--rule)',
      background: 'var(--bg-2)' }}>
      <header onClick={() => setOpen(o => !o)}
        style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '11px 14px', cursor: 'pointer',
          borderBottom: open ? '1px solid var(--rule)' : '0',
          background: 'var(--bg-2)' }}>
        <span style={{ fontSize: 13, color: 'var(--ink-3)', width: 16, textAlign: 'center' }}>{icon}</span>
        <div className="ff-display" style={{ fontSize: 13, fontWeight: 600, flex: 1, letterSpacing: '-0.01em' }}>{title}</div>
        {right && <div onClick={e => e.stopPropagation()}>{right}</div>}
        <span style={{
          fontSize: 14, color: 'var(--ink-3)',
          transform: open ? 'rotate(90deg)' : 'rotate(0deg)',
          transition: 'transform .15s' }}>›</span>
      </header>
      {open && <div style={{ padding: '14px 14px 4px' }}>{children}</div>}
    </section>);

}

// ── STATUS PILL ────────────────────────────────────────────────
const _RX_STATUSES = [
{ v: 'draft',     l: 'Draft',      tone: '#999' },
{ v: 'scheduled', l: 'Scheduled',  tone: '#c4a252' },
{ v: 'live',      l: 'Live',       tone: '#3a8a52' },
{ v: 'takendown', l: 'Taken down', tone: '#a83232' },
{ v: 'archived',  l: 'Archived',   tone: '#5c5c5c' }];


// ── MAIN PANE ──────────────────────────────────────────────────
// Map wizard step → which _RxSection ids show.
// When visibleStep is null/undefined, all sections show (legacy single-pane mode).
const _STEP_SECTIONS = {
  basics: ['basics'],
  details: ['identity', 'label', 'dates', 'classification'],
  tracks: ['tracks'],
  art: ['art'],
  dist: ['dist']
};

function ReleaseEditionEditPane({ form, set, AR, visibleStep }) {
  const _showIds = visibleStep ? _STEP_SECTIONS[visibleStep] || [] : null;
  const _shouldShow = (id) => _showIds === null || _showIds.includes(id);
  // When in wizard mode, force-open the visible sections (no collapse needed)
  const _wizardMode = !!visibleStep;
  const {
    Lbl, Inp, Seg, ArtistsField, TrackRow, Picker,
    ART_SWATCHES, DSPS, releaseTypes, configs, parentalOpts,
    creditLine,
    tracks, totalSeconds, totalMin, dspCount,
    removeTrack, moveTrack, togglePromo, updateTrack, addTrackFromRec, openCreateRecording, toggleDsp,
    genreOpts, langOpts } = AR;

  const editionStatus = form.editionStatus || 'draft';
  const setStatus = (v) => set({ editionStatus: v });
  const st = _RX_STATUSES.find(s => s.v === editionStatus) || _RX_STATUSES[0];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: _wizardMode ? '1fr' : '180px 1fr', minHeight: _wizardMode ? '40vh' : '52vh' }}>
      {/* ─── LEFT RAIL — EDITIONS (hidden in wizard mode) ─────── */}
      {!_wizardMode &&
      <aside style={{
        borderRight: '1px solid var(--rule)',
        background: 'var(--bg-2)',
        padding: '14px 0' }}>
        <div className="ff-mono upper" style={{
          fontSize: 9, letterSpacing: '.12em', color: 'var(--ink-3)',
          padding: '0 14px 8px' }}>
          EDITIONS · 1
        </div>

        <button
          style={{
            display: 'block', width: '100%', textAlign: 'left',
            padding: '10px 14px',
            background: 'var(--bg)', border: 0,
            borderLeft: '3px solid var(--ink)',
            cursor: 'pointer', marginBottom: 2 }}>
          <div className="ff-mono upper" style={{
            fontSize: 10, letterSpacing: '.06em',
            color: 'var(--ink)', fontWeight: 600 }}>
            {form.editionLabel || 'Original'}
          </div>
          <div className="ff-mono" style={{
            fontSize: 9, color: 'var(--ink-3)', marginTop: 3,
            display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{
              display: 'inline-block', width: 6, height: 6,
              borderRadius: '50%', background: st.tone }} />
            {st.l}
          </div>
        </button>

        <button disabled
          title="Available after first save · use the Release detail page to add editions"
          className="ff-mono upper"
          style={{
            display: 'block', width: '100%', textAlign: 'left',
            padding: '10px 14px', marginTop: 6,
            background: 'transparent', border: 0,
            cursor: 'not-allowed',
            fontSize: 9, letterSpacing: '.1em',
            color: 'var(--ink-4)' }}>
          + ADD EDITION
        </button>
        <div className="ff-mono" style={{
          padding: '4px 14px 0', fontSize: 9,
          color: 'var(--ink-4)', lineHeight: 1.5 }}>
          Save first, then add re-releases, deluxe & format editions from the release page.
        </div>
      </aside>
      }

      {/* ─── RIGHT PANE — release-group strip + edition accordion ── */}
      <div style={{ overflowY: 'auto', padding: _wizardMode ? '14px 24px 28px' : '18px 22px 80px', background: 'var(--bg)' }}>

        {/* Release-group header strip (hidden in wizard mode) */}
        {!_wizardMode && <>
        <div style={{
          display: 'flex', alignItems: 'flex-start', gap: 14,
          padding: '4px 0 16px',
          borderBottom: '1px solid var(--rule)', marginBottom: 14 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="ff-mono upper" style={{
              fontSize: 9, letterSpacing: '.12em',
              color: 'var(--ink-3)', marginBottom: 4 }}>
              EDITION
            </div>
            <input
              value={form.editionLabel || ''}
              onChange={e => set({ editionLabel: e.target.value })}
              placeholder="Original"
              className="ff-display"
              style={{
                fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em',
                background: 'transparent', border: 0, padding: 0,
                width: '100%', color: 'var(--ink)', outline: 'none' }} />
          </div>
          <div>
            <div className="ff-mono upper" style={{
              fontSize: 9, letterSpacing: '.12em',
              color: 'var(--ink-3)', marginBottom: 4 }}>
              STATUS
            </div>
            <select
              value={editionStatus}
              onChange={e => setStatus(e.target.value)}
              className="ff-mono"
              style={{
                padding: '6px 10px',
                background: 'var(--bg)', border: '1px solid var(--rule)',
                fontSize: 11, color: st.tone, fontWeight: 600 }}>
              {_RX_STATUSES.map(s => <option key={s.v} value={s.v}>{s.l}</option>)}
            </select>
          </div>
        </div>

        {/* Helper note */}
        <div className="ff-mono" style={{
          fontSize: 11, color: 'var(--ink-3)',
          padding: '10px 12px',
          background: 'var(--bg-2)', border: '1px solid var(--rule-soft)',
          marginBottom: 16, lineHeight: 1.55,
          display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <span style={{ color: 'var(--ink-2)', fontSize: 13, lineHeight: 1 }}>ⓘ</span>
          <span>
            <strong style={{ color: 'var(--ink-2)', fontWeight: 600 }}>Optional — fill in over time.</strong>
            {' '}Only release title, primary artist, label and at least one configuration are required to save.
            Open a section to add detail. Tracklist, artwork and DSP delivery can be wired up later from the release page.
          </span>
        </div>
        </>}

        {/* RELEASE-GROUP fields — title, version, primary artists, type */}
        {_shouldShow('basics') && <_RxSection id="basics" title="Title & Artists" icon="◇" defaultOpen={true} forceOpen={_wizardMode}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div style={{ gridColumn: '1 / -1' }}>
              <Lbl>Release title</Lbl>
              <Inp value={form.title} onChange={v => set({ title: v })}
                placeholder="A Seat at the Table" autoFocus />
            </div>
            <div style={{ gridColumn: '1 / -1' }}>
              <Lbl>Version <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}>· optional</span></Lbl>
              <Inp value={form.versionSubtitle} onChange={v => set({ versionSubtitle: v })}
                placeholder="Deluxe Edition · 10th Anniversary · Remixes" />
            </div>
            <div style={{ gridColumn: '1 / -1' }}>
              <Lbl>Primary artists</Lbl>
              <ArtistsField value={form.artists} onChange={v => {
                const primaryCount = (v || []).filter(a => a && a.name && (a.role || 'primary') === 'primary').length;
                const isSingle = form.type === 'Single';
                const autoVA = primaryCount >= 5 && !isSingle;
                const useVA = autoVA || (form.variousArtists && primaryCount >= 5 && !isSingle);
                const credit = useVA ? 'Various Artists' : creditLine(v);
                const first = (v || []).find(a => a && a.name);
                set({
                  artists: v,
                  artist: credit,
                  variousArtists: autoVA ? true : (form.variousArtists && !isSingle && primaryCount >= 5),
                  searchArtist: first?.name || '',
                  artistAid: first?.aid || null });

              }} />
              {(() => {
                const primaryCount = (form.artists || []).filter(a => a && a.name && (a.role || 'primary') === 'primary').length;
                const isSingle = form.type === 'Single';
                const autoVA = primaryCount >= 5 && !isSingle;
                const tooManyForNonVA = primaryCount >= 5 && !isSingle;
                const lockOff = primaryCount < 5 || isSingle; // can't manually toggle on
                const checked = autoVA || !!form.variousArtists;
                const onToggle = () => {
                  if (autoVA || lockOff) return; // auto state — no manual override
                  const next = !form.variousArtists;
                  const credit = next ? 'Various Artists' : creditLine(form.artists);
                  set({ variousArtists: next, artist: credit });
                };
                return (
                  <div style={{ marginTop: 4, marginBottom: 8 }}>
                    <label style={{ display:'inline-flex', alignItems:'flex-start', gap:8, cursor: (autoVA || lockOff) ? 'not-allowed' : 'pointer', opacity: lockOff && !autoVA ? .55 : 1 }}>
                      <input type="checkbox" checked={checked} disabled={autoVA || lockOff} onChange={onToggle}
                        style={{ marginTop: 2, accentColor: 'var(--ink)' }} />
                      <span className="ff-mono" style={{ fontSize: 11, color: 'var(--ink-2)', lineHeight: 1.45 }}>
                        <strong style={{ color:'var(--ink)', fontWeight: 600 }}>Various Artists</strong>
                        {autoVA && <span style={{ color:'var(--ink-3)' }}> · auto-applied — 5+ primary artists on a non-single</span>}
                        {!autoVA && !lockOff && <span style={{ color:'var(--ink-3)' }}> · credit this release as “Various Artists”</span>}
                        {lockOff && !autoVA && isSingle && <span style={{ color:'var(--ink-3)' }}> · disabled for singles</span>}
                        {lockOff && !autoVA && !isSingle && <span style={{ color:'var(--ink-3)' }}> · requires 5+ primary artists</span>}
                      </span>
                    </label>
                    {tooManyForNonVA && (form.artists || []).filter(a => a && a.name && (a.role || 'primary') === 'primary').length > 4 && !checked && (
                      <div className="ff-mono" style={{ fontSize: 10, color: 'var(--danger, #c44)', marginTop: 4, paddingLeft: 24 }}>
                        ⚠ Non-single releases must list ≤4 primary artists or use “Various Artists”.
                      </div>
                    )}
                  </div>
                );
              })()}
              {form.artist &&
              <div className="ff-mono" style={{
                fontSize: 10, color: 'var(--ink-3)',
                marginTop: -2, marginBottom: 8, paddingLeft: 2 }}>
                  Display credit: <span style={{ color: 'var(--ink-2)' }}>{form.artist}</span>
                </div>
              }
            </div>
          </div>

          <Lbl>Release type</Lbl>
          {(() => {const _ARTS = releaseTypes();return (
              <>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 6, marginBottom: 8 }}>
                  {_ARTS.filter(t => t.group === 'distributable').map(t => {
                    const active = form.type === t.k;
                    return (
                      <button key={t.k} onClick={() => {
                        const primaryCount = (form.artists || []).filter(a => a && a.name && (a.role || 'primary') === 'primary').length;
                        const isSingle = t.k === 'Single';
                        const autoVA = primaryCount >= 5 && !isSingle;
                        const nextVA = autoVA ? true : (isSingle ? false : !!form.variousArtists);
                        const credit = nextVA ? 'Various Artists' : creditLine(form.artists);
                        set({ type: t.k, variousArtists: nextVA, artist: credit });
                      }}
                        style={{
                          padding: '10px 12px', textAlign: 'left', cursor: 'pointer',
                          background: active ? 'var(--ink)' : 'var(--bg)',
                          color: active ? 'var(--bg)' : 'var(--ink-2)',
                          border: '1px solid ' + (active ? 'var(--ink)' : 'var(--rule)') }}>
                          <div className="ff-mono upper" style={{ fontSize: 11, letterSpacing: '.08em', fontWeight: 600 }}>{t.k}</div>
                          <div className="ff-mono" style={{ fontSize: 9, opacity: .7, marginTop: 3 }}>{t.hint}</div>
                        </button>);

                  })}
                </div>
                <div className="ff-mono upper" style={{ fontSize: 8, letterSpacing: '.1em', color: 'var(--ink-3)', marginBottom: 6, marginTop: 10 }}>SUB-CLASSIFICATION</div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 6, marginBottom: 12 }}>
                  {_ARTS.filter(t => t.group === 'other').map(t => {
                    const active = form.type === t.k;
                    return (
                      <button key={t.k} onClick={() => {
                        const primaryCount = (form.artists || []).filter(a => a && a.name && (a.role || 'primary') === 'primary').length;
                        const isSingle = t.k === 'Single';
                        const autoVA = primaryCount >= 5 && !isSingle;
                        const nextVA = autoVA ? true : (isSingle ? false : !!form.variousArtists);
                        const credit = nextVA ? 'Various Artists' : creditLine(form.artists);
                        set({ type: t.k, variousArtists: nextVA, artist: credit });
                      }}
                        style={{
                          padding: '7px 8px', textAlign: 'left', cursor: 'pointer',
                          background: active ? 'var(--ink)' : 'var(--bg)',
                          color: active ? 'var(--bg)' : 'var(--ink-3)',
                          border: '1px solid ' + (active ? 'var(--ink)' : 'var(--rule)') }}>
                          <div className="ff-mono upper" style={{ fontSize: 9, letterSpacing: '.08em', fontWeight: 600 }}>{t.k}</div>
                          <div className="ff-mono" style={{ fontSize: 8, opacity: .7, marginTop: 2 }}>{t.hint}</div>
                        </button>);

                  })}
                </div>
              </>);

          })()}

          {/* CONFIGURATION — hoisted from Identifiers; gates downstream choices */}
          <Lbl>Configuration</Lbl>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {configs().map(c => {
              const cfgs = form.configurations || [];
              const active = cfgs.includes(c.k);
              const toggle = () => {
                const next = active ? cfgs.filter(x => x !== c.k) : [...cfgs, c.k];
                set({ configurations: next });
              };
              return (
                <button key={c.k} onClick={toggle}
                  style={{
                    padding: '7px 12px', cursor: 'pointer',
                    background: active ? 'var(--ink)' : 'var(--bg)',
                    color: active ? 'var(--bg)' : 'var(--ink-2)',
                    border: '1px solid ' + (active ? 'var(--ink)' : 'var(--rule)'),
                    display: 'flex', alignItems: 'baseline', gap: 8 }}>
                  <span className="ff-mono upper" style={{ fontSize: 10, letterSpacing: '.08em', fontWeight: 600 }}>{c.l}</span>
                  <span className="ff-mono" style={{ fontSize: 9, opacity: .7 }}>{c.hint}</span>
                </button>);

            })}
          </div>
        </_RxSection>}

        {/* IDENTITY — edition-level identifiers */}
        {_shouldShow('identity') && <_RxSection id="identity" title="Identifiers" icon="◈" forceOpen={_wizardMode}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div>
              <Lbl>UPC</Lbl>
              <Inp value={form.upc}
                onChange={v => set({ upc: v.replace(/\D/g, '').slice(0, 13) })}
                placeholder="886447988104" mono />
            </div>
            <div>
              <Lbl>Catalog number</Lbl>
              <Inp value={form.catalog} onChange={v => set({ catalog: v })}
                placeholder="SAINT-001" mono />
            </div>
          </div>
        </_RxSection>}

        {/* LABEL & RIGHTS */}
        {_shouldShow('label') && <_RxSection id="label" title="Label & Rights" icon="●" forceOpen={_wizardMode}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div>
              <Lbl>Recording label</Lbl>
              {window.LabelTypeahead ?
              <div style={{ marginBottom: 14 }}>
                  <window.LabelTypeahead value={form.label || ''} labelId={form.labelId}
                  onSelect={p => {
                    const yyyy = (form.digitalDate || form.originalDate || '').slice(0, 4) || String(new Date().getFullYear());
                    const patch = { label: p.name, labelId: p.labelId, labelCode: p.code };
                    if (!form.pLine) patch.pLine = '℗ ' + yyyy + ' ' + p.name;
                    if (!form.cLine) patch.cLine = '© ' + yyyy + ' ' + p.name;
                    set(patch);
                  }}
                  placeholder="Saint Records, Columbia, Ninja Tune…" />
                </div> :

              <select value={form.label || ''}
              onChange={e => set({ label: e.target.value })}
              className="ff-mono"
              style={{
                width: '100%', padding: '8px 10px',
                background: 'var(--bg)', border: '1px solid var(--rule)',
                fontSize: 13, color: form.label ? 'var(--ink)' : 'var(--ink-3)',
                boxSizing: 'border-box', cursor: 'pointer' }}>
                  <option value="">— select label —</option>
                  {(window.LABELS || []).map(l => <option key={l.id} value={l.name}>{l.code} · {l.name}</option>)}
                </select>
              }
            </div>
            <div>
              <Lbl>Marketing imprint <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}>· optional</span></Lbl>
              <Inp value={form.marketingLabel}
                onChange={v => set({ marketingLabel: v })}
                placeholder="Same as recording label" />
            </div>
            <div>
              <Lbl>℗ line <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}>· master rights</span></Lbl>
              <Inp value={form.pLine} onChange={v => set({ pLine: v })}
                placeholder="℗ 2016 Saint Records / Columbia" />
            </div>
            <div>
              <Lbl>© line <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}>· composition</span></Lbl>
              <Inp value={form.cLine} onChange={v => set({ cLine: v })}
                placeholder="© 2016 Saint Records" />
            </div>
          </div>
        </_RxSection>}

        {/* DATES */}
        {_shouldShow('dates') && <_RxSection id="dates" title="Release Dates" icon="◆" forceOpen={_wizardMode}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
            <div>
              <Lbl>Original release</Lbl>
              {window.DateField ?
              <window.DateField value={form.originalDate} onChange={v => set({ originalDate: v })} /> :

              <input type="date" value={form.originalDate}
              onChange={e => set({ originalDate: e.target.value })}
              className="ff-mono"
              style={{ width: '100%', padding: '8px 10px', background: 'var(--bg)', border: '1px solid var(--rule)', fontSize: 12, color: 'var(--ink)', marginBottom: 14, boxSizing: 'border-box' }} />
              }
            </div>
            <div>
              <Lbl>Digital release</Lbl>
              {window.DateField ?
              <window.DateField value={form.digitalDate} onChange={v => set({ digitalDate: v })} /> :

              <input type="date" value={form.digitalDate}
              onChange={e => set({ digitalDate: e.target.value })}
              className="ff-mono"
              style={{ width: '100%', padding: '8px 10px', background: 'var(--bg)', border: '1px solid var(--rule)', fontSize: 12, color: 'var(--ink)', marginBottom: 14, boxSizing: 'border-box' }} />
              }
            </div>
            <div>
              <Lbl>Pre-order date <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}>· optional</span></Lbl>
              {window.DateField ?
              <window.DateField value={form.preorderDate} onChange={v => set({ preorderDate: v })} /> :

              <input type="date" value={form.preorderDate}
              onChange={e => set({ preorderDate: e.target.value })}
              className="ff-mono"
              style={{ width: '100%', padding: '8px 10px', background: 'var(--bg)', border: '1px solid var(--rule)', fontSize: 12, color: 'var(--ink)', marginBottom: 14, boxSizing: 'border-box' }} />
              }
            </div>
          </div>
        </_RxSection>}

        {/* CLASSIFICATION */}
        {_shouldShow('classification') && <_RxSection id="classification" title="Classification" icon="⊡" forceOpen={_wizardMode}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div>
              <Lbl>Genre</Lbl>
              <select value={form.genre}
                onChange={e => set({ genre: e.target.value, subGenre: '' })}
                className="ff-mono"
                style={{
                  width: '100%', padding: '8px 10px',
                  background: 'var(--bg)', border: '1px solid var(--rule)',
                  fontSize: 12, color: form.genre ? 'var(--ink)' : 'var(--ink-3)',
                  marginBottom: 14, boxSizing: 'border-box' }}>
                <option value="">— select —</option>
                {genreOpts.map(g => <option key={g} value={g}>{g}</option>)}
              </select>
            </div>
            <div>
              <Lbl>Sub-genre</Lbl>
              {(() => {
                const subOpts = window.refSubGenreLabels ? window.refSubGenreLabels(form.genre) : [];
                if (subOpts.length === 0) {
                  return <Inp value={form.subGenre} onChange={v => set({ subGenre: v })}
                    placeholder={form.genre ? 'Type a sub-genre…' : 'Pick a genre first'} />;
                }
                return (
                  <select value={form.subGenre} onChange={e => set({ subGenre: e.target.value })}
                    className="ff-mono"
                    style={{
                      width: '100%', padding: '8px 10px',
                      background: 'var(--bg)', border: '1px solid var(--rule)',
                      fontSize: 12, color: form.subGenre ? 'var(--ink)' : 'var(--ink-3)',
                      marginBottom: 14, boxSizing: 'border-box', cursor: 'pointer' }}>
                    <option value="">— select —</option>
                    {subOpts.map(s => <option key={s} value={s}>{s}</option>)}
                  </select>);

              })()}
            </div>
            <div>
              <Lbl>Metadata language</Lbl>
              <select value={form.language}
                onChange={e => set({ language: e.target.value })}
                className="ff-mono"
                style={{
                  width: '100%', padding: '8px 10px',
                  background: 'var(--bg)', border: '1px solid var(--rule)',
                  fontSize: 12, color: 'var(--ink)',
                  marginBottom: 14, boxSizing: 'border-box' }}>
                {langOpts.map(l => <option key={l} value={l}>{l}</option>)}
              </select>
            </div>
            <div>
              <Lbl>Parental advisory</Lbl>
              <Seg options={parentalOpts()} value={form.parental} onChange={v => set({ parental: v })} />
            </div>
          </div>
        </_RxSection>}

        {/* TRACKLIST */}
        {_shouldShow('tracks') && <_RxSection id="tracks" forceOpen={_wizardMode} title={`Tracklist · ${tracks.length} ${tracks.length === 1 ? 'track' : 'tracks'}${totalSeconds > 0 ? ` · ${totalMin}:${String(totalSeconds % 60).padStart(2, '0')}` : ''}`} icon="▣">
          {tracks.length === 0 ?
          <div style={{
            padding: '20px 16px', border: '1px dashed var(--rule)',
            background: 'var(--bg-2)', textAlign: 'center', marginBottom: 10 }}>
              <div className="ff-display" style={{ fontSize: 16, fontWeight: 600, letterSpacing: '-0.02em', marginBottom: 6 }}>
                No tracks linked yet
              </div>
              <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginBottom: 12, lineHeight: 1.55 }}>
                Link existing recordings or create a new one — we'll save it
                and drop it onto this release in one go.
              </div>
              <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
                <button onClick={() => set({ showPicker: true })} className="ff-mono upper"
                style={{
                  padding: '8px 16px', fontSize: 10, letterSpacing: '.1em', fontWeight: 600,
                  background: 'var(--ink)', color: 'var(--bg)', border: 0, cursor: 'pointer' }}>
                  + LINK EXISTING
                </button>
                <button onClick={openCreateRecording} className="ff-mono upper"
                style={{
                  padding: '8px 16px', fontSize: 10, letterSpacing: '.1em', fontWeight: 600,
                  background: 'transparent', color: 'var(--ink)',
                  border: '1px solid var(--ink)', cursor: 'pointer' }}>
                  + CREATE NEW RECORDING
                </button>
              </div>
            </div> :

          <div style={{ border: '1px solid var(--rule)', marginBottom: 10 }}>
              {tracks.map((t, i) =>
            <TrackRow key={i} track={t} idx={i}
            isFirst={i === 0} isLast={i === tracks.length - 1}
            onRemove={() => removeTrack(i)}
            onMoveUp={() => moveTrack(i, -1)}
            onMoveDown={() => moveTrack(i, 1)}
            onTogglePromo={() => togglePromo(i)}
            onUpdate={(next) => updateTrack(i, next)} />
            )}
            </div>
          }

          {!form.showPicker && tracks.length > 0 &&
          <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
              <button onClick={() => set({ showPicker: true })}
            style={{
              flex: 1, display: 'flex', gap: 8, alignItems: 'center', justifyContent: 'center',
              padding: '9px 14px',
              border: '1px dashed var(--rule)', background: 'transparent', cursor: 'pointer',
              color: 'var(--ink-2)', fontSize: 11 }}>
                <span style={{ color: 'var(--ink-3)' }}>+</span> Link another recording
              </button>
              <button onClick={openCreateRecording} className="ff-mono upper"
            style={{
              padding: '9px 14px', fontSize: 9, letterSpacing: '.08em', fontWeight: 600,
              background: 'transparent', color: 'var(--ink)',
              border: '1px solid var(--ink)', cursor: 'pointer', whiteSpace: 'nowrap' }}>
                + CREATE NEW
              </button>
            </div>
          }

          {form.showPicker &&
          <Picker
            excludeIds={tracks.map(t => t.recId)}
            primaryArtistName={form.artist}
            onPick={r => addTrackFromRec(r)}
            onCreateNew={openCreateRecording} />
          }
        </_RxSection>}

        {/* ARTWORK */}
        {_shouldShow('art') && <_RxSection id="art" title="Artwork" icon="◨" forceOpen={_wizardMode}>
          {window.ArtworkManager
            ? <window.ArtworkManager
                value={form.artwork}
                onChange={(next) => set({ artwork: next })} />
            : <div className="ff-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>Artwork manager loading…</div>
          }
        </_RxSection>}

        {/* TERRITORY & DISTRIBUTION */}
        {_shouldShow('dist') && <_RxSection id="dist" title={`Territory & Distribution${dspCount ? ` · ${dspCount}/${DSPS.length} DSPs` : ''}`} icon="✎" forceOpen={_wizardMode}>
          <Lbl>Territory</Lbl>
          <Seg
            options={[{ k: 'world', l: 'WORLDWIDE' }, { k: 'include', l: 'SPECIFIC ONLY' }, { k: 'exclude', l: 'WORLD EXCEPT' }]}
            value={form.territoryMode}
            onChange={v => set({ territoryMode: v, territories: v === 'world' ? ['World'] : [] })} />
          {form.territoryMode !== 'world' && window.TerritoriesField &&
          <div style={{ marginBottom: 14 }}>
              <Lbl>{form.territoryMode === 'include' ? 'Distribute in' : 'Exclude'}</Lbl>
              <window.TerritoriesField value={form.territories}
              onChange={v => set({ territories: v })} />
            </div>
          }

          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            marginTop: 6, marginBottom: 8 }}>
            <Lbl>DSP delivery <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}>· {dspCount}/{DSPS.length}</span></Lbl>
            <div style={{ display: 'flex', gap: 6 }}>
              <button onClick={() => set({ dsps: new Set(DSPS) })} className="ff-mono upper"
                style={{ padding: '4px 10px', fontSize: 9, letterSpacing: '.08em',
                  background: 'transparent', color: 'var(--ink-2)',
                  border: '1px solid var(--rule)', cursor: 'pointer' }}>ALL</button>
              <button onClick={() => set({ dsps: new Set() })} className="ff-mono upper"
                style={{ padding: '4px 10px', fontSize: 9, letterSpacing: '.08em',
                  background: 'transparent', color: 'var(--ink-2)',
                  border: '1px solid var(--rule)', cursor: 'pointer' }}>NONE</button>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px 12px', marginBottom: 14 }}>
            {DSPS.map(d => {
              const on = form.dsps.has(d);
              return (
                <label key={d} style={{
                  display: 'flex', alignItems: 'center', gap: 9,
                  padding: '6px 0', cursor: 'pointer',
                  color: on ? 'var(--ink)' : 'var(--ink-3)' }}>
                  <span onClick={() => toggleDsp(d)}
                    style={{
                      width: 14, height: 14,
                      background: on ? 'var(--accent)' : 'transparent',
                      border: '1px solid ' + (on ? 'var(--accent)' : 'var(--rule)'),
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      color: 'var(--bg)', fontSize: 10, fontWeight: 700, flexShrink: 0 }}>{on ? '✓' : ''}</span>
                  <span className="ff-mono" style={{ fontSize: 11, fontWeight: on ? 500 : 400 }} onClick={() => toggleDsp(d)}>{d}</span>
                </label>);

            })}
          </div>

          <Lbl>Audio formats</Lbl>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
              <input type="checkbox" checked={form.hiRes}
                onChange={e => set({ hiRes: e.target.checked })} />
              <span style={{ fontSize: 11 }}>Hi-Res Lossless <span className="ff-mono" style={{ fontSize: 9, color: 'var(--ink-3)', marginLeft: 6 }}>24-bit / ≥48 kHz · Tidal, Apple, Qobuz, Amazon HD</span></span>
            </label>
            <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
              <input type="checkbox" checked={form.atmos}
                onChange={e => set({ atmos: e.target.checked })} />
              <span style={{ fontSize: 11 }}>Dolby Atmos <span className="ff-mono" style={{ fontSize: 9, color: 'var(--ink-3)', marginLeft: 6 }}>spatial mix · Apple, Tidal, Amazon</span></span>
            </label>
          </div>

          <Lbl>Delivery date</Lbl>
          {window.DateField ?
          <window.DateField value={form.deliveryDate} onChange={v => set({ deliveryDate: v })} /> :

          <input type="date" value={form.deliveryDate}
          onChange={e => set({ deliveryDate: e.target.value })}
          className="ff-mono"
          style={{ width: '100%', padding: '8px 10px', background: 'var(--bg)', border: '1px solid var(--rule)', fontSize: 12, color: 'var(--ink)', boxSizing: 'border-box' }} />
          }
          <div className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 6, lineHeight: 1.5 }}>
            ERN 4.3 manifest builds at this date and pushes to selected DSPs. Most platforms acknowledge in 24-72h.
          </div>
        </_RxSection>}

      </div>
    </div>);

}

Object.assign(window, { ReleaseEditionEditPane });
