// ─────────────────────────────────────────────────────────────────────
// ADD STORY — a lightweight capture tool for the human history of a car.
//
// Not a wizard. A story starts from whatever you have in hand RIGHT NOW —
// a video of someone talking, an old photograph, or just words — and grows
// context later. One short landing, then one flexible editor.
//
//   Capture what you have now.  Add context when you know it.
//
// Three ways in:
//   · Upload Video  — preserve the recording, transcribe it, name who's telling it
//   · Upload Photo  — preserve the image, note who / where / when
//   · Write Story   — just start writing; attach media whenever
//   (· Audio / Document — the same editor, seeded with that attachment)
//
// Every field is optional. Save a draft any time, or add it to the archive.
// ─────────────────────────────────────────────────────────────────────

const { useState: useStory } = React;

// ── header — title + a quiet mode eyebrow, no step rail ─────────────────
function StoryBar({ eyebrow, title = 'Add Story', onBack }) {
  return (
    <div style={{
      padding: '10px 18px 12px', background: P.ink, flex: '0 0 auto',
      display: 'flex', alignItems: 'center', gap: 12, borderBottom: `1px solid ${P.graphite}`,
    }}>
      <button onClick={onBack} aria-label="Back" style={{
        background: P.gold, border: 'none', borderRadius: 999, width: 34, height: 34,
        flexShrink: 0, color: P.ink, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M5 12l6-6M5 12l6 6" /></svg>
      </button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: T.display, fontWeight: 600, fontSize: 15, letterSpacing: '0.02em', color: P.paper, lineHeight: 1.1 }}>{title}</div>
        <RcMono size={8.5} color={P.gold} tracking="0.16em" style={{ marginTop: 3, display: 'block' }}>{eyebrow}</RcMono>
      </div>
      <CAMonogram size={20} color={P.paper} stroke={1.6} />
    </div>
  );
}

// ── reusable quiet field — ledger-like, never boxy ──────────────────────
function Field({ icon, label, optional, children }) {
  return (
    <div style={{ display: 'flex', gap: 12, padding: '15px 0', borderBottom: `1px solid ${P.slate}` }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 7 }}>
          <RcMono size={8} color={P.mute} tracking="0.16em">{label}</RcMono>
          {optional && <RcMono size={7.5} color={P.slate} tracking="0.12em">OPTIONAL</RcMono>}
        </div>
        {children}
      </div>
    </div>
  );
}

const storyInputStyle = (filled) => ({
  width: '100%', boxSizing: 'border-box', background: 'transparent', border: 'none',
  borderBottom: `1px solid ${filled ? P.gold : P.slate}`, outline: 'none',
  color: P.paper, fontFamily: T.body, fontSize: 15, padding: '2px 0 7px',
});

// ── vehicle option for the related-car picker ───────────────────────────
function VehicleOption({ v, on, onClick }) {
  const code = (v.make || '').replace(/[^A-Za-z]/g, '').slice(0, 2).toUpperCase();
  return (
    <button onClick={onClick} style={{
      flexShrink: 0, width: 128, textAlign: 'left', cursor: 'pointer',
      background: on ? P.graphite : 'transparent', border: `1px solid ${on ? P.gold : P.slate}`,
      padding: 0, transition: 'border-color .15s, background .15s',
    }}>
      <span style={{ display: 'block', height: 70, overflow: 'hidden', borderBottom: `1px solid ${on ? P.gold : P.slate}`, position: 'relative' }}>
        {v.hero
          ? <PhotoSlot dirId="concours" height={70} tone="dark" src={v.hero} />
          : <span style={{ width: '100%', height: '100%', background: P.ink, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: T.mono, fontSize: 16, fontWeight: 600, color: P.gold }}>{code}</span>}
        {on && <span style={{ position: 'absolute', top: 6, right: 6, width: 18, height: 18, borderRadius: 999, background: P.gold, color: P.ink, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
        </span>}
      </span>
      <span style={{ display: 'block', padding: '8px 9px 10px' }}>
        <RcMono size={7.5} color={P.gold} tracking="0.12em">{v.year}</RcMono>
        <span style={{ display: 'block', fontFamily: T.display, fontSize: 12.5, fontWeight: 600, color: P.paper, marginTop: 3, lineHeight: 1.1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{v.nickname || v.model}</span>
      </span>
    </button>
  );
}

// ── inline searchable vehicle field — scales from 1 car to hundreds ─────
// A text input; as soon as the user types, matching cars appear in a list
// below (searched across make / model / year / nickname / VIN / project).
// Picking one selects it; selected state collapses to the chosen car with
// a Change affordance. No modal — the list lives inline under the field.
function VehicleSearchField({ pool, selectedId, onSelect }) {
  const [query, setQuery] = useStory('');
  const [focused, setFocused] = useStory(false);
  const byId = {}; pool.forEach(v => { byId[v.id] = v; });
  const selected = selectedId ? byId[selectedId] : null;

  const results = query.trim() ? searchVehicles(pool, query) : [];
  const CAP = 8;
  const shown = results.slice(0, CAP);
  const more = Math.max(0, results.length - CAP);

  // Selected state — show the chosen car, offer Change.
  if (selected) {
    return (
      <div style={{ border: `1px solid ${P.gold}`, background: P.graphite, display: 'flex', alignItems: 'center', gap: 12, padding: '9px 11px' }}>
        <span style={{ flex: 1, minWidth: 0 }}>
          <span style={{ display: 'block', fontFamily: T.display, fontSize: 14, fontWeight: 600, color: P.paper, lineHeight: 1.15, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{selected.year} {selected.make} {selected.model}</span>
          <VehSub v={selected} />
        </span>
        <button onClick={() => { onSelect(null); setQuery(''); }} style={{
          flexShrink: 0, height: 30, padding: '0 12px', background: 'transparent', border: `1px solid ${P.slate}`,
          color: P.gold, cursor: 'pointer', fontFamily: T.mono, fontSize: 8.5, fontWeight: 600, letterSpacing: '0.12em', textTransform: 'uppercase',
        }}>Change</button>
      </div>
    );
  }

  return (
    <div>
      <div style={{ position: 'relative' }}>
        <span style={{ position: 'absolute', left: 12, top: 0, bottom: 0, display: 'flex', alignItems: 'center', pointerEvents: 'none' }}>
          <Icon name="search" size={14} color={query.trim() ? P.gold : P.mute} strokeWidth={1.8} />
        </span>
        <input value={query} onChange={e => setQuery(e.target.value)}
          onFocus={() => setFocused(true)} onBlur={() => setTimeout(() => setFocused(false), 150)}
          placeholder="Search by vehicle, nickname, VIN, or project"
          style={{ width: '100%', height: 44, boxSizing: 'border-box', background: P.ink, border: `1px solid ${query.trim() ? P.gold : P.slate}`, outline: 'none', color: P.paper, fontFamily: T.body, fontSize: 12.5, padding: '0 14px 0 36px' }} />
        {query.trim() && (
          <button onClick={() => setQuery('')} aria-label="Clear search" style={{ position: 'absolute', right: 6, top: 0, bottom: 0, width: 30, background: 'transparent', border: 'none', color: P.mute, cursor: 'pointer', fontFamily: T.mono, fontSize: 15 }}>×</button>
        )}
      </div>

      {query.trim() ? (
        <div style={{ marginTop: 8, border: `1px solid ${P.slate}` }}>
          {shown.length === 0 ? (
            <div style={{ padding: '15px 13px', textAlign: 'center' }}>
              <RcMono size={9} color={P.mute} tracking="0.02em" style={{ textTransform: 'none' }}>No vehicle matches “{query.trim()}”</RcMono>
            </div>
          ) : (
            <React.Fragment>
              {shown.map((v, i) => (
                <SelectRow key={v.id} selected={false} onClick={() => { onSelect(v.id); setQuery(''); }}
                  last={i === shown.length - 1 && more === 0}
                  title={`${v.year} ${v.make} ${v.model}`} sub={<VehSub v={v} />} />
              ))}
              {more > 0 && (
                <div style={{ padding: '9px 13px', borderTop: `1px solid ${P.slate}` }}>
                  <RcMono size={8} color={P.mute} tracking="0.1em">{more} MORE · KEEP TYPING TO NARROW</RcMono>
                </div>
              )}
            </React.Fragment>
          )}
        </div>
      ) : (
        <div style={{ marginTop: 8 }}>
          <RcMono size={8} color={P.slate} tracking="0.12em">{pool.length} VEHICLES · START TYPING TO FIND ONE · OR LEAVE UNASSIGNED</RcMono>
        </div>
      )}
    </div>
  );
}

// ── tag-style people input ──────────────────────────────────────────────
function PeopleInput({ people, setPeople, placeholder }) {
  const [draft, setDraft] = useStory('');
  const add = () => { const n = draft.trim(); if (!n) return; setPeople(p => [...p, n]); setDraft(''); };
  return (
    <React.Fragment>
      {people.length > 0 && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 10 }}>
          {people.map((p, i) => (
            <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '5px 9px', background: P.graphite, border: `1px solid ${P.gold}` }}>
              <span style={{ fontFamily: T.body, fontSize: 12.5, color: P.paper }}>{p}</span>
              <button onClick={() => setPeople(list => list.filter((_, j) => j !== i))} aria-label={`Remove ${p}`} style={{ background: 'none', border: 'none', color: P.mute, cursor: 'pointer', padding: 0, display: 'flex' }}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" /></svg>
              </button>
            </span>
          ))}
        </div>
      )}
      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        <input value={draft} onChange={e => setDraft(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); add(); } }}
          placeholder={placeholder || 'Add a name…'} style={storyInputStyle(draft.trim())} />
        <button onClick={add} style={{ flexShrink: 0, width: 30, height: 30, background: 'transparent', border: `1px solid ${P.slate}`, color: P.gold, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="add" size={15} color={P.gold} strokeWidth={2} />
        </button>
      </div>
    </React.Fragment>
  );
}

// ── attachment row — a compact add control per media type ───────────────
const ATTACH_SAMPLES = {
  photo: ['IMG_2204.HEIC', 'SCAN_07.JPG', 'CONCOURS_FIELD.JPG', 'DETAIL_03.HEIC'],
  video: ['FIRST_START.MOV', 'INTERVIEW.MP4', 'DRIVE_BY.MP4'],
  audio: ['RECOLLECTION.M4A', 'VOICE_MEMO.M4A', 'OWNER_CALL.M4A'],
  doc:   ['LETTER_1973.PDF', 'PERIOD_ARTICLE.PDF', 'BUILD_SHEET.PDF'],
};
const ATTACH_META = {
  photo: { icon: 'gallery',  label: 'Photos',    hint: 'JPG · HEIC · PNG' },
  video: { icon: 'Video',    label: 'Video',     hint: 'MP4 · MOV' },
  audio: { icon: 'Mic',      label: 'Audio',     hint: 'A recollection · an interview' },
  doc:   { icon: 'FileText', label: 'Documents', hint: 'Letters · articles · notes' },
};

function AttachTile({ type, items, onAdd, onRemove }) {
  const m = ATTACH_META[type];
  const has = items.length > 0;
  return (
    <div style={{ background: P.graphite, border: `1px solid ${has ? P.gold : P.slate}`, padding: '12px 13px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: T.display, fontSize: 14, fontWeight: 600, color: P.paper, lineHeight: 1.1 }}>{m.label}</div>
          <RcMono size={8} color={P.mute} tracking="0.12em" style={{ marginTop: 3, display: 'block' }}>{has ? `${items.length} ATTACHED` : m.hint}</RcMono>
        </div>
        <button onClick={onAdd} aria-label={`Add ${m.label}`} style={{ width: 30, height: 30, flexShrink: 0, background: 'transparent', border: `1px solid ${P.slate}`, color: P.gold, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="add" size={15} color={P.gold} strokeWidth={2} />
        </button>
      </div>
      {has && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 11 }}>
          {items.map((it, i) => (
            <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 6px 4px 8px', background: P.ink, border: `1px solid ${P.slate}` }}>
              <RcMono size={7.5} color={P.bone} tracking="0.08em">{it}</RcMono>
              <button onClick={() => onRemove(i)} aria-label={`Remove ${it}`} style={{ background: 'none', border: 'none', color: P.mute, cursor: 'pointer', padding: 0, display: 'flex' }}>
                <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round"><line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" /></svg>
              </button>
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════
// LANDING — five ways to start a story
// ═════════════════════════════════════════════════════════════════════
const ENTRIES = [
  { mode: 'video', icon: 'Video',    title: 'Upload Video',
    desc: 'Someone telling the story on camera. We can transcribe it.' },
  { mode: 'photo', icon: 'gallery',  title: 'Upload Photo',
    desc: 'An old photo of the car. Note who, where, and when.' },
  { mode: 'audio', icon: 'Mic',      title: 'Upload Audio',
    desc: 'A recollection or interview, preserved and transcribable.' },
  { mode: 'doc',   icon: 'FileText', title: 'Add a Document',
    desc: 'A letter, article, build sheet, or note — preserved as-is.' },
  { mode: 'write', icon: 'Feather',  title: 'Write Story',
    desc: 'Just start writing. Attach media whenever you have it.' },
];

function StoryStart({ onPick, onBack }) {
  return (
    <React.Fragment>
      <StoryBar eyebrow="PRESERVE A MEMORY" onBack={onBack} />
      <div className="proto-scroll" style={{ flex: 1, overflow: 'auto', background: P.ink }} data-screen-label="mgr-story-start">
        <div className="story-fade">
          <div style={{ padding: '22px 22px 8px' }}>
            <div style={{ fontFamily: T.display, fontWeight: 700, fontSize: 30, lineHeight: 0.92, letterSpacing: '-0.02em', color: P.paper }}>EVERY CAR<br />HAS A STORY</div>
            <div style={{ fontFamily: T.body, fontSize: 13, color: P.mute, marginTop: 11, lineHeight: 1.55, maxWidth: 330 }}>
              Start your story however you like. You can add to the story later as more details become available.
            </div>
          </div>

          <div style={{ padding: '14px 22px 6px', display: 'grid', gap: 10 }}>
            {ENTRIES.map(e => (
              <button key={e.mode} onClick={() => onPick(e.mode)} style={{
                textAlign: 'left', cursor: 'pointer', background: P.graphite, border: `1px solid ${P.slate}`,
                padding: '16px 16px', display: 'flex', alignItems: 'center', gap: 14, transition: 'border-color .15s',
              }}
                onMouseEnter={ev => ev.currentTarget.style.borderColor = P.gold}
                onMouseLeave={ev => ev.currentTarget.style.borderColor = P.slate}>
                <span style={{ width: 54, height: 54, flexShrink: 0, border: `1px solid ${P.slate}`, background: P.ink, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name={e.icon} size={24} color={P.gold} strokeWidth={1.5} />
                </span>
                <span style={{ flex: 1, minWidth: 0 }}>
                  <span style={{ display: 'block', fontFamily: T.display, fontSize: 17, fontWeight: 700, color: P.paper, lineHeight: 1.05 }}>{e.title}</span>
                  <span style={{ fontFamily: T.body, fontSize: 12, color: P.mute, marginTop: 3, lineHeight: 1.28, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{e.desc}</span>
                </span>
                <Icon name="arrow" size={17} color={P.gold} strokeWidth={1.8} style={{ flexShrink: 0 }} />
              </button>
            ))}
          </div>

          {/* principle line */}
          <div style={{ padding: '18px 22px 26px', display: 'flex', alignItems: 'flex-start', gap: 10 }}>
            <span style={{ width: 5, height: 5, background: P.gold, flexShrink: 0, marginTop: 4 }} />
            <RcMono size={8.5} color={P.mute} tracking="0.13em" style={{ lineHeight: 1.7 }}>
              Capture what you have now · add context later.
            </RcMono>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

// ═════════════════════════════════════════════════════════════════════
// MEDIA HERO — the seed media shown at the top of the editor
// ═════════════════════════════════════════════════════════════════════
function VideoHero({ name }) {
  return (
    <div style={{ position: 'relative', background: P.graphite, border: `1px solid ${P.slate}`, height: 188, overflow: 'hidden' }}>
      <PhotoSlot dirId="concours" height={188} tone="dark" />
      <span style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <span style={{ width: 54, height: 54, borderRadius: 999, background: 'rgba(10,10,11,0.55)', border: `1px solid ${P.gold}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill={P.gold} stroke="none"><path d="M8 5v14l11-7z" /></svg>
        </span>
      </span>
      <span style={{ position: 'absolute', left: 10, bottom: 10, display: 'inline-flex', alignItems: 'center', padding: '4px 8px', background: 'rgba(10,10,11,0.7)', border: `1px solid ${P.slate}` }}>
        <RcMono size={8} color={P.bone} tracking="0.08em">{name}</RcMono>
      </span>
    </div>
  );
}

function AudioHero({ name }) {
  // a quiet waveform stand-in — bars of varied height, play affordance, filename
  const bars = [10, 22, 14, 34, 26, 44, 30, 52, 38, 60, 44, 54, 32, 46, 24, 38, 18, 30, 12, 22, 14, 26, 10, 18];
  return (
    <div style={{ position: 'relative', background: P.graphite, border: `1px solid ${P.slate}`, height: 132, overflow: 'hidden', display: 'flex', alignItems: 'center', gap: 14, padding: '0 16px' }}>
      <span style={{ width: 48, height: 48, flexShrink: 0, borderRadius: 999, background: 'rgba(184,144,85,0.1)', border: `1px solid ${P.gold}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill={P.gold} stroke="none"><path d="M8 5v14l11-7z" /></svg>
      </span>
      <span style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 3, height: 64 }}>
        {bars.map((h, i) => (
          <span key={i} style={{ flex: 1, height: h, background: i < 8 ? P.gold : P.slate, borderRadius: 1 }} />
        ))}
      </span>
      <span style={{ position: 'absolute', left: 10, bottom: 10, display: 'inline-flex', alignItems: 'center', padding: '4px 8px', background: 'rgba(10,10,11,0.7)', border: `1px solid ${P.slate}` }}>
        <RcMono size={8} color={P.bone} tracking="0.08em">{name}</RcMono>
      </span>
    </div>
  );
}

function PhotoHero({ name }) {
  return (
    <div style={{ position: 'relative', height: 210 }}>
      <PhotoSlot dirId="concours" height={210} tone="dark" label="PHOTOGRAPH" sub="drag image to replace" />
      <span style={{ position: 'absolute', left: 10, bottom: 10, display: 'inline-flex', alignItems: 'center', padding: '4px 8px', background: 'rgba(10,10,11,0.7)', border: `1px solid ${P.slate}` }}>
        <RcMono size={8} color={P.bone} tracking="0.08em">{name}</RcMono>
      </span>
    </div>
  );
}

const SAMPLE_TRANSCRIPT = "My father bought this car new in the spring of 1973. He drove it down from the dealership in Stuttgart himself — wouldn't let anyone else behind the wheel. I still remember the sound of it pulling into the driveway. He kept every receipt, every note. He used to say a car like this one doesn't belong to you, you're just looking after it for the next person.";

// ═════════════════════════════════════════════════════════════════════
// EDITOR — one flexible screen, adapts to how the story started
// ═════════════════════════════════════════════════════════════════════
function StoryEditor({ mode, vehicles, initialVehicleId, onBack, onSave }) {
  const active = vehicles.filter(v => v.status !== 'Sold' && v.status !== 'Archived');
  const isVideo = mode === 'video';
  const isPhoto = mode === 'photo';
  const isAudio = mode === 'audio';
  const isRecording = isVideo || isAudio;   // a spoken recording — transcript + speaker

  const [title, setTitle] = useStory('');
  const [body, setBody] = useStory('');
  const [vehId, setVehId] = useStory(initialVehicleId || null);
  const [narrator, setNarrator] = useStory('');           // video only — "person telling the story"
  const [people, setPeople] = useStory([]);
  const [approx, setApprox] = useStory(false);
  const [dateExact, setDateExact] = useStory('');
  const [year, setYear] = useStory('');
  const [season, setSeason] = useStory('—');
  const [place, setPlace] = useStory('');
  const [transcribed, setTranscribed] = useStory(false);
  const seed = {
    photo: ['PHOTOGRAPH.HEIC'], video: ['INTERVIEW.MP4'],
    audio: ['RECOLLECTION.M4A'], doc: ['DOCUMENT.PDF'],
  };
  const [media, setMedia] = useStory({
    photo: isPhoto ? seed.photo : [],
    video: isVideo ? seed.video : [],
    audio: mode === 'audio' ? seed.audio : [],
    doc: mode === 'doc' ? seed.doc : [],
  });

  const addMedia = (type) => {
    const s = ATTACH_SAMPLES[type];
    setMedia(m => ({ ...m, [type]: [...m[type], s[m[type].length % s.length]] }));
  };
  const removeMedia = (type, i) => setMedia(m => ({ ...m, [type]: m[type].filter((_, j) => j !== i) }));

  const eyebrow = isVideo ? 'VIDEO STORY' : isPhoto ? 'PHOTO STORY'
    : mode === 'audio' ? 'AUDIO STORY' : mode === 'doc' ? 'DOCUMENT STORY' : 'WRITTEN STORY';

  // people field adapts its label to context
  const peopleLabel = isRecording ? 'PEOPLE MENTIONED OR PRESENT' : isPhoto ? 'PEOPLE IN THE PHOTO' : 'PEOPLE';
  const bodyLabel = isPhoto ? 'NOTES ABOUT THE PHOTO' : 'THE STORY';
  const mediaWord = isVideo ? 'Video' : 'Audio';
  // Searchable collection pool — real cars + roster standing in for a large
  // collection, so the picker works whether it's 1 vehicle or 300.
  const pool = (typeof vehiclePool === 'function') ? vehiclePool(active) : active;
  const veh = pool.find(v => v.id === vehId);

  const mediaTotal = Object.values(media).reduce((a, b) => a + b.length, 0);
  const hasSomething = title.trim() || body.trim() || mediaTotal > 0 || narrator.trim() || people.length;

  const transcribe = () => { setBody(SAMPLE_TRANSCRIPT); setTranscribed(true); };

  return (
    <React.Fragment>
      <StoryBar eyebrow={eyebrow} onBack={onBack} />
      <div className="proto-scroll" style={{ flex: 1, overflow: 'auto', background: P.ink }} data-screen-label={`mgr-story-edit-${mode}`}>
        <div className="story-fade">

          {/* media hero */}
          {(isRecording || isPhoto) && (
            <div style={{ padding: '16px 22px 4px' }}>
              {isVideo ? <VideoHero name={media.video[0] || 'INTERVIEW.MP4'} />
                : isAudio ? <AudioHero name={media.audio[0] || 'RECOLLECTION.M4A'} />
                : <PhotoHero name={media.photo[0] || 'PHOTOGRAPH.HEIC'} />}
            </div>
          )}

          {/* title — always first, always optional */}
          <div style={{ padding: '6px 22px 0' }}>
            <Field icon="Feather" label="TITLE" optional>
              <input value={title} onChange={e => setTitle(e.target.value)}
                placeholder={isPhoto ? 'The day it came home' : isRecording ? 'In his own words' : 'Give the story a title'}
                style={{ ...storyInputStyle(title.trim()), fontFamily: T.display, fontSize: 18, fontWeight: 600 }} />
            </Field>
          </div>

          {/* RECORDING: transcript with a transcribe affordance */}
          {isRecording && (
            <div style={{ padding: '0 22px' }}>
              <Field icon="FileText" label="TRANSCRIPT">
                {!body && !transcribed ? (
                  <div style={{ background: P.graphite, border: `1px dashed ${P.slate}`, padding: '16px 14px', textAlign: 'center' }}>
                    <RcMono size={8.5} color={P.mute} tracking="0.12em" style={{ display: 'block', lineHeight: 1.6, marginBottom: 12 }}>
                      Generate a transcript from the recording,<br />then edit anything that needs a correction.
                    </RcMono>
                    <button onClick={transcribe} style={{
                      display: 'inline-flex', alignItems: 'center', gap: 8, height: 38, padding: '0 18px',
                      background: 'transparent', border: `1px solid ${P.gold}`, color: P.gold, cursor: 'pointer',
                      fontFamily: T.mono, fontSize: 9.5, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase',
                    }}>
                      <Icon name="spark" size={14} color={P.gold} strokeWidth={1.8} />Transcribe {mediaWord}
                    </button>
                  </div>
                ) : (
                  <React.Fragment>
                    {transcribed && (
                      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 9, padding: '3px 8px', border: `1px solid ${P.gold}`, background: 'rgba(184,144,85,0.1)' }}>
                        <Icon name="spark" size={11} color={P.gold} strokeWidth={1.8} />
                        <RcMono size={7.5} color={P.gold} tracking="0.12em">TRANSCRIBED · EDIT FREELY</RcMono>
                      </div>
                    )}
                    <textarea value={body} onChange={e => setBody(e.target.value)} rows={8}
                      style={{ width: '100%', boxSizing: 'border-box', background: P.graphite, border: `1px solid ${P.slate}`, outline: 'none', color: P.paper, fontFamily: T.body, fontSize: 14.5, lineHeight: 1.65, padding: '13px 13px', resize: 'vertical', minHeight: 130 }}
                      onFocus={e => e.target.style.borderColor = P.gold}
                      onBlur={e => e.target.style.borderColor = P.slate} />
                  </React.Fragment>
                )}
              </Field>

              <Field icon="Mic" label="PERSON TELLING THE STORY" optional>
                <input value={narrator} onChange={e => setNarrator(e.target.value)} placeholder={isVideo ? 'Who’s speaking in the video?' : 'Who’s speaking in the recording?'}
                  style={storyInputStyle(narrator.trim())} />
              </Field>
            </div>
          )}

          {/* PHOTO + WRITE + DOC: the narrative / notes area */}
          {!isRecording && (
            <div style={{ padding: '0 22px' }}>
              <Field icon="Feather" label={bodyLabel} optional={isPhoto}>
                <textarea value={body} onChange={e => setBody(e.target.value)} rows={isPhoto ? 5 : 9}
                  placeholder={isPhoto ? 'What do you know about this photo?' : 'Begin here…'}
                  style={{ width: '100%', boxSizing: 'border-box', background: P.graphite, border: `1px solid ${P.slate}`, outline: 'none', color: P.paper, fontFamily: T.body, fontSize: 15, lineHeight: 1.68, padding: '14px 14px', resize: 'vertical', minHeight: isPhoto ? 96 : 170 }}
                  onFocus={e => e.target.style.borderColor = P.gold}
                  onBlur={e => e.target.style.borderColor = P.slate} />
              </Field>
            </div>
          )}

          {/* PEOPLE — label adapts to context */}
          <div style={{ padding: '0 22px' }}>
            <Field icon="Users" label={peopleLabel} optional>
              <PeopleInput people={people} setPeople={setPeople}
                placeholder={isPhoto ? 'Who’s in the photo?' : 'Add a name…'} />
            </Field>
          </div>

          {/* RELATED VEHICLE — inline search; list appears as you type */}
          <div style={{ padding: '0 22px' }}>
            <Field icon="car" label="RELATED VEHICLE" optional>
              <VehicleSearchField pool={pool} selectedId={vehId} onSelect={setVehId} />
            </Field>
          </div>

          {/* DATE */}
          <div style={{ padding: '0 22px' }}>
            <Field icon="Calendar" label="DATE OR APPROXIMATE DATE" optional>
              <div style={{ display: 'inline-flex', border: `1px solid ${P.slate}`, marginBottom: 11 }}>
                {[['Exact', false], ['Approximate', true]].map(([lbl, val], i) => {
                  const on = approx === val;
                  return (
                    <button key={lbl} onClick={() => setApprox(val)} style={{
                      padding: '7px 14px', background: on ? P.paper : 'transparent', color: on ? P.ink : P.bone,
                      border: 'none', borderLeft: i > 0 ? `1px solid ${P.slate}` : 'none',
                      fontFamily: T.mono, fontSize: 8.5, fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase', cursor: 'pointer',
                    }}>{lbl}</button>
                  );
                })}
              </div>
              {!approx ? (
                <input value={dateExact} onChange={e => setDateExact(e.target.value)} placeholder="April 14, 1973"
                  style={storyInputStyle(dateExact.trim())} />
              ) : (
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
                  <div style={{ display: 'inline-flex', flexWrap: 'wrap', border: `1px solid ${P.slate}` }}>
                    {['—', 'Spring', 'Summer', 'Fall', 'Winter'].map((s, i) => {
                      const on = season === s;
                      return (
                        <button key={s} onClick={() => setSeason(s)} style={{
                          padding: '7px 11px', background: on ? P.gold : 'transparent', color: on ? P.ink : P.bone,
                          border: 'none', borderLeft: i > 0 ? `1px solid ${P.slate}` : 'none',
                          fontFamily: T.mono, fontSize: 8, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', cursor: 'pointer',
                        }}>{s}</button>
                      );
                    })}
                  </div>
                  <input value={year} onChange={e => setYear(e.target.value.replace(/[^0-9]/g, '').slice(0, 4))} placeholder="Year"
                    style={{ ...storyInputStyle(year.trim()), width: 90, fontFamily: T.mono, fontSize: 14 }} />
                </div>
              )}
            </Field>
          </div>

          {/* LOCATION */}
          <div style={{ padding: '0 22px' }}>
            <Field icon="MapPin" label="LOCATION" optional>
              <input value={place} onChange={e => setPlace(e.target.value)} placeholder="Stuttgart, Germany"
                style={storyInputStyle(place.trim())} />
            </Field>
          </div>

          {/* ATTACHMENTS */}
          <div style={{ padding: '4px 22px 0' }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, padding: '14px 0 12px' }}>
              <RcMono size={8} color={P.mute} tracking="0.16em">ATTACHMENTS</RcMono>
              <RcMono size={7.5} color={P.slate} tracking="0.12em">ADD ANYTIME</RcMono>
            </div>
            <div style={{ display: 'grid', gap: 8 }}>
              {['photo', 'video', 'audio', 'doc'].map(type => (
                <AttachTile key={type} type={type} items={media[type]}
                  onAdd={() => addMedia(type)} onRemove={(i) => removeMedia(type, i)} />
              ))}
            </div>
          </div>

          <div style={{ padding: '16px 22px 26px', display: 'flex', alignItems: 'flex-start', gap: 10 }}>
            <span style={{ width: 5, height: 5, background: P.gold, flexShrink: 0, marginTop: 4 }} />
            <RcMono size={8.5} color={P.mute} tracking="0.13em" style={{ lineHeight: 1.7 }}>
              Nothing here is required. Originals are preserved with the story — never discarded.
            </RcMono>
          </div>
        </div>
      </div>

      {/* action bar — Save Draft · Add to Archive */}
      <div style={{ flex: '0 0 auto', background: P.ink, borderTop: `1px solid ${P.graphite}`, padding: '12px 22px', display: 'flex', gap: 10, alignItems: 'center' }}>
        <button onClick={() => hasSomething && onSave('draft', { title, veh })} disabled={!hasSomething} style={{
          flexShrink: 0, height: 50, padding: '0 18px', background: 'transparent',
          border: `1px solid ${hasSomething ? P.slate : P.graphite}`, color: hasSomething ? P.bone : P.mute,
          cursor: hasSomething ? 'pointer' : 'not-allowed',
          fontFamily: T.mono, fontSize: 10, fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase',
        }}>Save Draft</button>
        <button onClick={() => hasSomething && onSave('archived', { title, veh })} disabled={!hasSomething} style={{
          flex: 1, height: 50, background: hasSomething ? P.gold : 'transparent', border: `1px solid ${hasSomething ? P.gold : P.slate}`,
          color: hasSomething ? P.ink : P.mute, cursor: hasSomething ? 'pointer' : 'not-allowed',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9,
          fontFamily: T.mono, fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase',
        }}>
          <Icon name="BookOpen" size={15} color={hasSomething ? P.ink : P.mute} strokeWidth={2} />Add to Archive
        </button>
      </div>
    </React.Fragment>
  );
}

// ═════════════════════════════════════════════════════════════════════
// DONE — light confirmation for both draft + archived
// ═════════════════════════════════════════════════════════════════════
function StoryDone({ result, title, veh, onClose }) {
  const archived = result === 'archived';
  const vehLabel = veh ? `${veh.year} ${veh.make} ${veh.model}` : 'this collection';
  return (
    <React.Fragment>
      <div className="proto-scroll story-fade" style={{ flex: 1, overflow: 'auto', background: P.ink, display: 'flex', flexDirection: 'column' }} data-screen-label="mgr-story-done">
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: '40px 30px' }}>
          <span style={{ width: 60, height: 60, borderRadius: 999, border: `1px solid ${P.gold}`, background: 'rgba(184,144,85,0.1)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name={archived ? 'BookOpen' : 'Bookmark'} size={26} color={P.gold} strokeWidth={1.4} />
          </span>
          <RcMono size={9} color={P.gold} tracking="0.18em" style={{ marginTop: 22, display: 'block' }}>{archived ? 'ADDED TO THE ARCHIVE' : 'SAVED AS DRAFT'}</RcMono>
          <div style={{ fontFamily: T.display, fontWeight: 700, fontSize: 28, lineHeight: 0.98, letterSpacing: '-0.02em', color: P.paper, marginTop: 12, textWrap: 'balance' }}>{title || 'Your story'}</div>
          <div style={{ fontFamily: T.body, fontSize: 13, color: P.mute, marginTop: 14, lineHeight: 1.6, maxWidth: 300 }}>
            {archived
              ? <React.Fragment>This story now lives with <span style={{ color: P.bone }}>{vehLabel}</span> — beside its ownership, restoration, and financial history.</React.Fragment>
              : <React.Fragment>Saved. Come back and add names, dates, or attachments whenever you know more.</React.Fragment>}
          </div>
          <button onClick={onClose} style={{
            marginTop: 30, height: 50, padding: '0 40px', background: P.gold, border: `1px solid ${P.gold}`, color: P.ink, cursor: 'pointer',
            fontFamily: T.mono, fontSize: 11, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase',
          }}>Done</button>
        </div>
      </div>
      <style>{`@keyframes storyFade { from { transform: translateY(7px); } to { transform: none; } } @media (prefers-reduced-motion: no-preference) { .story-fade { animation: storyFade .4s ease; } }`}</style>
    </React.Fragment>
  );
}

// ═════════════════════════════════════════════════════════════════════
// STORY FLOW — orchestrates landing → editor → done
// ═════════════════════════════════════════════════════════════════════
function StoryFlow({ vehicles = [], onBack, onClose, initialVehicleId = null }) {
  const [stage, setStage] = useStory('start');   // 'start' | 'edit' | 'done'
  const [mode, setMode] = useStory(null);
  const [result, setResult] = useStory(null);    // 'draft' | 'archived'
  const [summary, setSummary] = useStory({ title: '', veh: null });

  const pick = (m) => { setMode(m); setStage('edit'); };
  const save = (kind, data) => { setResult(kind); setSummary(data); setStage('done'); };

  return (
    <React.Fragment>
      {stage === 'start' && (
        <StoryStart onPick={pick} onBack={onBack} />
      )}
      {stage === 'edit' && (
        <StoryEditor key={mode} mode={mode} vehicles={vehicles} initialVehicleId={initialVehicleId}
          onBack={() => setStage('start')} onSave={save} />
      )}
      {stage === 'done' && (
        <StoryDone result={result} title={summary.title} veh={summary.veh} onClose={onClose} />
      )}
      <style>{`@keyframes storyFade { from { transform: translateY(7px); } to { transform: none; } } @media (prefers-reduced-motion: no-preference) { .story-fade { animation: storyFade .35s ease; } }`}</style>
    </React.Fragment>
  );
}

Object.assign(window, { StoryFlow });
