// ───────────────────────────────────────────────────────────────────────
// Forever — screen components
// ───────────────────────────────────────────────────────────────────────

const SUBJECTS = {
  dad:   { name: 'Dad',       full: 'Dad (Bill)',     tone: 'wood', sessions: 5, stories: 18, minutes: 40 },
  mom:   { name: 'Mom',       full: 'Mom (Yayesh)',   tone: 'rose', sessions: 8, stories: 32, minutes: 64 },
  uncle: { name: 'Uncle Dan', full: 'Uncle Dan',      tone: 'sage', sessions: 2, stories: 8,  minutes: 16 },
};

// ── ONBOARD ─────────────────────────────────────────────────────────────
function OnboardScreen({ onContinue, copyTone }) {
  const [topic, setTopic] = React.useState('childhood');
  const topics = [
    { id: 'recipes',   icon: '🍲', label: 'Recipes',     desc: 'The dishes that mean home' },
    { id: 'trips',     icon: '✈️', label: 'Family Trips', desc: 'Adventures and misadventures' },
    { id: 'childhood', icon: '🏠', label: 'Childhood',    desc: 'Where the stories begin' },
    { id: 'holidays',  icon: '🎄', label: 'Holidays',     desc: 'Traditions and celebrations' },
    { id: 'career',    icon: '💼', label: 'Career',       desc: 'Work, ambitions, lessons' },
    { id: 'love',      icon: '💕', label: 'Love Story',   desc: 'How they met, how they knew' },
  ];
  const title = copyTone === 'reverent'
    ? 'What memories deserve to be kept?'
    : 'What do you want to remember first?';
  const sub = copyTone === 'reverent'
    ? 'A first conversation. Choose what to honor — the rest will follow.'
    : 'Choose a topic to start your first conversation. You can always explore more later.';
  return (
    <div className="onboard-screen">
      <div className="onboard-mark">
        <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
          <circle cx="22" cy="22" r="21" stroke="var(--gold)" strokeWidth="0.75"/>
          <circle cx="22" cy="22" r="14" stroke="var(--gold)" strokeWidth="0.75"/>
          <path d="M22 8v28M8 22h28" stroke="var(--gold)" strokeWidth="0.75" opacity="0.4"/>
          <circle cx="22" cy="22" r="2.5" fill="var(--gold)"/>
        </svg>
      </div>
      <div className="onboard-tagline">8 minutes a day. Remembered forever.</div>
      <div className="onboard-title">{title}</div>
      <div className="onboard-sub">{sub}</div>
      <div className="topic-grid">
        {topics.map(t => (
          <div key={t.id} className={`topic-btn ${topic === t.id ? 'selected' : ''}`} onClick={() => setTopic(t.id)}>
            <div className="topic-btn-icon">{t.icon}</div>
            <div className="topic-btn-label">{t.label}</div>
            <div className="topic-btn-desc">{t.desc}</div>
          </div>
        ))}
      </div>
      <button className="surprise-btn" onClick={() => setTopic('surprise')}>
        ✦ Surprise me — just start talking
      </button>
      <button className="onboard-continue" onClick={onContinue}>
        Begin first conversation {Icon.arrow(14, 'currentColor')}
      </button>
      <div className="onboard-foot">Your stories stay private. Always.</div>
    </div>
  );
}

// ── HOME (BOOKSHELF) ────────────────────────────────────────────────────
function HomeScreen({ subject, onRecord, onUpload, onShelfZoom, onMemoir, onShare, onMemory, metaphor, copyTone }) {
  const s = SUBJECTS[subject];
  const greeting = copyTone === 'reverent' ? 'Honoring' : 'Conversations with';
  return (
    <div className="bookshelf-area">
      <div className="shelf-greeting">{greeting}</div>
      <div className="shelf-subject-row">
        <div className="shelf-subject-name">{s.full}</div>
        <button className="shelf-share-btn" onClick={onShare} aria-label="Share">{Icon.invite(16, 'currentColor')}</button>
      </div>
      <div className="shelf-stats">{s.sessions} sessions · {s.stories} stories · {s.minutes} minutes captured</div>

      <div className="streak-card">
        <div className="streak-info">
          <div className="streak-num"><span>5</span><em>day streak</em></div>
          <StreakDots days={[1,1,1,1,1,0,0]} today={4}/>
        </div>
        <div className="streak-flame">{Icon.flame(22, 'var(--gold)')}</div>
      </div>

      {/* Prompt Card */}
      <div className="prompt-card" onClick={onRecord}>
        <div className="prompt-card-label">
          <span className="hairline"/>
          <span>Today's conversation</span>
          <span className="hairline"/>
        </div>
        <PromptItem kind="callback" type="From last time" text="Last session, Dad mentioned a fishing trip he took as a teenager. Ask him who he went with and where they went." />
        <PromptItem kind="callback" type="From last time" text="He started to talk about his first car but changed the subject. Gently revisit it." />
        <PromptItem kind="new" type="New thread" text="Ask Dad about meeting Mom for the first time. Where were they? What did he notice first?" />
        <button className="prompt-start-btn">
          <span className="prompt-dot"/>
          Begin 8-minute session
          {Icon.arrow(14, 'rgba(255,255,255,0.7)')}
        </button>
      </div>

      {/* Upload Memory Card */}
      <div className="upload-card" onClick={onUpload}>
        <div className="upload-card-icon">{Icon.upload(18, 'var(--ink-soft)')}</div>
        <div className="upload-card-text">
          <div className="upload-card-title">Add a memory</div>
          <div className="upload-card-desc">Photo, letter, recipe card, voice note — anything that tells a story</div>
        </div>
        {Icon.arrow(14, 'var(--ink-faint)')}
      </div>

      {/* Bookshelf */}
      <div className="shelf-header">
        <div className="shelf-section-label">{s.name}'s library</div>
        <button className="shelf-zoom-btn" onClick={onShelfZoom}>view all {Icon.arrow(12, 'currentColor')}</button>
      </div>

      {metaphor === 'shelf' ? (
        <>
          <div className="bookshelf">
            <div className="shelf-row">
              <BookSpine title="Childhood"  height={110} tone="wood"  stories={4} onClick={() => onMemory('childhood')}/>
              <BookSpine title="Fishing"    height={95}  tone="sand"  stories={2} onClick={() => onMemory('fishing')}/>
              <BookSpine title="The Army"   height={120} tone="sky"   stories={5} onClick={() => onMemory('army')}/>
              <BookSpine title="Marriage"   height={80}  tone="rose"  stories={1} onClick={() => onMemory('marriage')}/>
              <BookSpine title="Career"     height={105} tone="sage"  stories={3} onClick={() => onMemory('career')}/>
              <OutputBook title={`${s.name}'s\nMemoir`} subtitle="Chapter 2" height={130} onClick={onMemoir}/>
              <GhostBook height={115} onClick={onMemory.bind(null, 'ghost')}/>
              <ShelfPlank/>
            </div>
          </div>
          <div className="bookshelf">
            <div className="shelf-row" style={{ minHeight: 100 }}>
              <BookSpine title="School"    height={75} tone="cream" stories={2} onClick={() => onMemory('school')}/>
              <BookSpine title="First Car" height={90} tone="sky"   stories={1} onClick={() => onMemory('car')}/>
              <BookSpine title="Friends"   height={68} tone="deep"  stories={1} onClick={() => onMemory('friends')}/>
              <ShelfPlank/>
            </div>
          </div>
        </>
      ) : (
        <div className="chapter-grid">
          <BookSpine metaphor="cards" title="Childhood"  tone="wood" stories={4} onClick={() => onMemory('childhood')}/>
          <BookSpine metaphor="cards" title="Fishing"    tone="sand" stories={2} onClick={() => onMemory('fishing')}/>
          <BookSpine metaphor="cards" title="The Army"   tone="sky"  stories={5} onClick={() => onMemory('army')}/>
          <BookSpine metaphor="cards" title="Marriage"   tone="rose" stories={1} onClick={() => onMemory('marriage')}/>
          <BookSpine metaphor="cards" title="Career"     tone="sage" stories={3} onClick={() => onMemory('career')}/>
          <BookSpine metaphor="cards" title="School"     tone="cream" stories={2} onClick={() => onMemory('school')}/>
          <BookSpine metaphor="cards" title="First Car"  tone="sky"  stories={1} onClick={() => onMemory('car')}/>
          <BookSpine metaphor="cards" title="Friends"    tone="deep" stories={1} onClick={() => onMemory('friends')}/>
          <OutputBook metaphor="cards" title={`${s.name}'s Memoir`} subtitle="Chapter 2 ready" onClick={onMemoir}/>
          <GhostBook metaphor="cards" onClick={() => onMemory('ghost')}/>
        </div>
      )}

      <div style={{ height: 60 }}/>
    </div>
  );
}

// ── RECORD (light, airy) ────────────────────────────────────────────────
function RecordScreen({ subject, onStop, copyTone }) {
  const s = SUBJECTS[subject];
  const [seconds, setSeconds] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  React.useEffect(() => {
    if (paused) return;
    const id = setInterval(() => setSeconds(x => x + 1), 1000);
    return () => clearInterval(id);
  }, [paused]);
  const m = Math.floor(seconds / 60), sec = seconds % 60;
  const progress = Math.min(seconds / 480, 1);
  const heading = copyTone === 'reverent' ? 'A conversation with' : 'Talking with';

  return (
    <div className="record-screen">
      <div className="record-subject">
        <div className="record-subject-label">{heading}</div>
        <div className="record-subject-name">{s.full}</div>
      </div>

      {/* live transcript glimpse */}
      <div className="record-prompt-card">
        <div className="record-prompt-label">Current thread</div>
        <div className="record-prompt-text">"Ask {s.name} about meeting Mom for the first time. Where were they? What did he notice first?"</div>
      </div>

      <div className="record-waveform">
        {Array.from({ length: 36 }).map((_, i) => (
          <div key={i} className={`wave-bar ${paused ? 'paused' : ''}`} style={{
            animationDelay: `${(i % 8) * 0.08}s`,
            animationDuration: `${1.0 + (i % 5) * 0.15}s`,
          }}/>
        ))}
      </div>

      <div className="record-time">
        <span className="record-time-num">{m}:{sec < 10 ? '0' : ''}{sec}</span>
        <span className="record-time-of">of 8 minutes</span>
      </div>

      <div className="record-progress">
        <div className="record-progress-fill" style={{ width: `${progress * 100}%` }}/>
        <div className="record-progress-marks">
          {[0.25, 0.5, 0.75].map(p => <div key={p} className="record-progress-mark" style={{ left: `${p * 100}%` }}/>)}
        </div>
      </div>

      <div className="record-controls">
        <button className="record-ctrl-secondary" aria-label="Skip">
          {Icon.callback(18, 'var(--ink-soft)')}
          <span>New thread</span>
        </button>
        <button className="record-stop" onClick={onStop} aria-label="Stop">
          <div className="record-stop-inner"/>
        </button>
        <button className="record-ctrl-secondary" onClick={() => setPaused(p => !p)} aria-label="Pause">
          {paused ? Icon.play(16, 'var(--ink-soft)') : Icon.pause(16, 'var(--ink-soft)')}
          <span>{paused ? 'Resume' : 'Pause'}</span>
        </button>
      </div>

      <div className="record-foot">Tap to end · or wait for the 8-minute chime</div>
    </div>
  );
}

// ── POST-SESSION ────────────────────────────────────────────────────────
function PostScreen({ subject, onDone, onPhoto, onMemory, copyTone }) {
  const s = SUBJECTS[subject];
  const headline = copyTone === 'reverent' ? 'A conversation kept' : 'Beautiful conversation';
  return (
    <div className="post-screen">
      <div className="post-header">
        <div className="post-check">{Icon.check(28, 'var(--gold)')}</div>
        <div className="post-title">{headline}</div>
        <div className="post-sub">8 minutes 14 seconds · 3 new stories captured</div>
      </div>

      <div className="post-section-label">Key moments</div>
      <div className="post-moments">
        <div className="moment-item" onClick={() => onMemory('moment-1')}>
          <div className="moment-time">1:24</div>
          <div className="moment-divider"/>
          <div className="moment-text">"The fishing trip was up at Lake Arrowhead. His uncle drove them in an old Ford pickup with no radio."</div>
        </div>
        <div className="moment-item" onClick={() => onMemory('moment-2')}>
          <div className="moment-time">4:08</div>
          <div className="moment-divider"/>
          <div className="moment-text">"His first car was a 1968 Mustang. He bought it for $400 from a neighbor and it barely ran."</div>
        </div>
        <div className="moment-item" onClick={() => onMemory('moment-3')}>
          <div className="moment-time">6:45</div>
          <div className="moment-divider"/>
          <div className="moment-text">"He met Mom at a friend's barbecue. She was wearing a yellow sundress and he forgot his own name."</div>
        </div>
      </div>

      <div className="post-photo-prompt" onClick={onPhoto}>
        <div className="post-photo-icon">{Icon.photo(20, 'var(--ink)')}</div>
        <div className="post-photo-text">
          <div className="post-photo-title">{s.name} mentioned the 1968 Mustang.</div>
          <div className="post-photo-sub">Do you have any photos from that time?</div>
        </div>
        {Icon.arrow(14, 'var(--ink-faint)')}
      </div>

      <div className="post-section-label">Added to the library</div>
      <div className="post-shelf-preview">
        <div className="post-spine-row">
          <BookSpine title="First Car" height={88} tone="sky" stories={1}/>
          <div className="post-spine-arrow">{Icon.arrow(16, 'var(--gold)')}</div>
          <div className="post-spine-info">
            <div className="post-spine-info-label">New chapter</div>
            <div className="post-spine-info-name">"First Car"</div>
            <div className="post-spine-info-meta">Now on {s.name}'s shelf</div>
          </div>
        </div>
      </div>

      <button className="post-done-btn" onClick={onDone}>
        Back to the library {Icon.arrow(14, 'currentColor')}
      </button>
      <button className="post-share-btn">
        {Icon.share(14, 'var(--ink-soft)')}
        Share with family
      </button>
    </div>
  );
}

// ── MEMORY DETAIL (a single story, transcript-forward) ──────────────────
function MemoryScreen({ subject, memoryId, onBack, onPlay }) {
  const s = SUBJECTS[subject];
  const [playing, setPlaying] = React.useState(false);
  return (
    <div className="memory-screen">
      <div className="memory-back-row">
        <button className="memory-back" onClick={onBack}>{Icon.back(18, 'var(--ink)')}</button>
        <button className="memory-back" aria-label="More">{Icon.more(18, 'var(--ink)')}</button>
      </div>
      <div className="memory-meta">
        <div className="memory-chapter">First Car · Chapter 7</div>
        <div className="memory-title">The 1968 Mustang</div>
        <div className="memory-byline">{s.full} · captured March 14, 2026 · 2:41</div>
      </div>

      <div className="memory-player">
        <button className="memory-play" onClick={() => setPlaying(p => !p)}>
          {playing ? Icon.pause(20, 'var(--cream)') : Icon.play(20, 'var(--cream)')}
        </button>
        <div className="memory-player-mid">
          <div className="memory-scrubber">
            <div className="memory-scrubber-fill" style={{ width: '38%' }}/>
            <div className="memory-scrubber-thumb" style={{ left: '38%' }}/>
          </div>
          <div className="memory-times"><span>1:01</span><span>2:41</span></div>
        </div>
      </div>

      <div className="memory-transcript">
        <p>"It was a <em>nineteen sixty-eight</em> Mustang. Beautiful car — once. By the time I got it, the paint was gone, the radio was gone, and it had this terrible cough on cold mornings."</p>
        <p className="active">"I bought it for four hundred dollars from old Mr. Henderson down the street. He said, <em>Bill, this car will outlive me.</em> And I'll be damned if it didn't."</p>
        <p>"First date I took your mother on, the engine quit on the corner of Fifth and Maple. Just stopped. We pushed it home. I thought she'd never speak to me again."</p>
        <p className="dim">"But there she was the next Friday, knocking on the door asking if the car was running yet…"</p>
      </div>

      <div className="memory-attached">
        <div className="memory-attached-label">Attached</div>
        <div className="memory-attached-row">
          <div className="memory-photo">{Icon.photo(20, 'var(--ink-faint)')}<span>1968 Mustang</span></div>
          <div className="memory-photo memory-photo-add">{Icon.plus(18, 'var(--ink-faint)')}<span>Add photo</span></div>
        </div>
      </div>
    </div>
  );
}

// ── BOOK READER (memoir chapter preview) ────────────────────────────────
function MemoirScreen({ subject, onBack }) {
  const s = SUBJECTS[subject];
  return (
    <div className="memoir-screen">
      <div className="memoir-back-row">
        <button className="memory-back" onClick={onBack}>{Icon.back(18, 'var(--ink)')}</button>
        <div className="memoir-progress-text">Ch. 2 of 8</div>
        <button className="memory-back" aria-label="More">{Icon.more(18, 'var(--ink)')}</button>
      </div>

      <div className="memoir-page">
        <div className="memoir-tag">{Icon.sparkle(11, 'var(--gold)')} AI-drafted from 5 conversations</div>
        <div className="memoir-chapter-no">Chapter Two</div>
        <h1 className="memoir-h1">A car that wouldn't quit</h1>
        <div className="memoir-byline">From the conversations of {s.full}</div>
        <div className="memoir-rule"/>
        <p className="memoir-dropcap">
          <span className="dropcap">B</span>ill bought his first car the summer he turned seventeen. It was a 1968 Mustang, the color of old pennies, and Mr. Henderson down the street sold it to him for four hundred dollars cash. <em>This car will outlive me</em>, the old man said, and as Bill remembers it now, almost sixty years later, he was right.
        </p>
        <p>The radio didn't work. The paint had given up around the wheel wells. On cold mornings the engine made a sound Bill describes as <em>a man clearing his throat at the back of a long room</em>. But it ran — most of the time — and that summer it carried him everywhere he wanted to go.</p>
        <p>He took Yayesh on their first date in that car. They didn't make it past Fifth and Maple before the engine quit. They pushed the Mustang home together in the August heat, laughing the whole way…</p>

        <div className="memoir-foot">
          <button className="memoir-cta">
            {Icon.bookOpen(14, 'currentColor')} Read the full chapter
          </button>
          <button className="memoir-cta secondary">
            {Icon.share(14, 'currentColor')} Share with family
          </button>
        </div>
      </div>
    </div>
  );
}

// ── SHELF ZOOM (full library, sortable) ─────────────────────────────────
function ShelfZoomScreen({ subject, onBack, onMemory }) {
  const s = SUBJECTS[subject];
  const chapters = [
    { id: 'childhood', title: 'Childhood',  tone: 'wood',  stories: 4, height: 110 },
    { id: 'fishing',   title: 'Fishing',    tone: 'sand',  stories: 2, height: 95 },
    { id: 'army',      title: 'The Army',   tone: 'sky',   stories: 5, height: 120 },
    { id: 'marriage',  title: 'Marriage',   tone: 'rose',  stories: 1, height: 80 },
    { id: 'career',    title: 'Career',     tone: 'sage',  stories: 3, height: 105 },
    { id: 'school',    title: 'School',     tone: 'cream', stories: 2, height: 75 },
    { id: 'car',       title: 'First Car',  tone: 'sky',   stories: 1, height: 90 },
    { id: 'friends',   title: 'Friends',    tone: 'deep',  stories: 1, height: 68 },
    { id: 'holidays',  title: 'Holidays',   tone: 'rose',  stories: 2, height: 100 },
    { id: 'cooking',   title: 'Cooking',    tone: 'cream', stories: 2, height: 88 },
    { id: 'hobbies',   title: 'Hobbies',    tone: 'sage',  stories: 1, height: 72 },
    { id: 'losses',    title: 'Losses',     tone: 'deep',  stories: 1, height: 95 },
  ];
  const rows = [chapters.slice(0, 4), chapters.slice(4, 8), chapters.slice(8, 12)];
  return (
    <div className="zoom-screen">
      <div className="zoom-header">
        <button className="memory-back" onClick={onBack}>{Icon.back(18, 'var(--ink)')}</button>
        <div className="zoom-title">{s.name}'s library</div>
        <button className="memory-back" aria-label="Sort">{Icon.more(18, 'var(--ink)')}</button>
      </div>
      <div className="zoom-stats">
        <div><span className="zoom-stat-num">{s.stories}</span><em>stories</em></div>
        <div><span className="zoom-stat-num">{s.sessions}</span><em>sessions</em></div>
        <div><span className="zoom-stat-num">{chapters.length}</span><em>chapters</em></div>
      </div>
      <div className="zoom-shelves">
        {rows.map((row, i) => (
          <div key={i} className="bookshelf">
            <div className="shelf-row">
              {row.map(c => (
                <BookSpine key={c.id} title={c.title} height={c.height} tone={c.tone} stories={c.stories} onClick={() => onMemory(c.id)}/>
              ))}
              <ShelfPlank/>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── SETTINGS / SUBJECT MANAGEMENT ───────────────────────────────────────
function SettingsScreen({ subject, onBack, onSwitchSubject }) {
  return (
    <div className="settings-screen">
      <div className="settings-header">
        <button className="memory-back" onClick={onBack}>{Icon.back(18, 'var(--ink)')}</button>
        <div className="settings-title">Conversations</div>
        <div style={{ width: 36 }}/>
      </div>
      <div className="settings-group-label">Your people</div>
      <div className="settings-group">
        {Object.entries(SUBJECTS).map(([id, s]) => (
          <div key={id} className={`settings-pair ${id === subject ? 'active' : ''}`} onClick={() => onSwitchSubject(id)}>
            <Avatar name={s.name} tone={s.tone} size={44} border={false}/>
            <div className="settings-pair-info">
              <div className="settings-pair-name">{s.full}</div>
              <div className="settings-pair-meta">{s.sessions} sessions · {s.stories} stories</div>
            </div>
            {id === subject && <div className="settings-active-dot"/>}
          </div>
        ))}
        <div className="settings-add">
          <div className="settings-add-icon">{Icon.plus(18, 'var(--ink-faint)')}</div>
          <span>Add someone new</span>
        </div>
      </div>
      <div className="settings-group-label">App</div>
      <div className="settings-group">
        <div className="settings-row">{Icon.flame(16, 'var(--gold)')}<span>Daily reminder</span><em>9:30 AM</em></div>
        <div className="settings-row">{Icon.invite(16, 'var(--ink-soft)')}<span>Invite family</span></div>
        <div className="settings-row">{Icon.upload(16, 'var(--ink-soft)')}<span>Export library</span></div>
        <div className="settings-row">{Icon.settings(16, 'var(--ink-soft)')}<span>Privacy & data</span></div>
      </div>
      <div className="settings-foot">Forever · v1.0 · Made with care</div>
    </div>
  );
}

// ── SHARE SHEET ─────────────────────────────────────────────────────────
function ShareScreen({ subject, onBack }) {
  const s = SUBJECTS[subject];
  const family = [
    { name: 'Sarah',  rel: 'Sister',   tone: 'rose', invited: true },
    { name: 'Mark',   rel: 'Brother',  tone: 'sky',  invited: true },
    { name: 'Lily',   rel: 'Daughter', tone: 'sage', invited: false },
    { name: 'Jamie',  rel: 'Cousin',   tone: 'wood', invited: false },
  ];
  return (
    <div className="share-screen">
      <div className="share-header">
        <button className="memory-back" onClick={onBack}>{Icon.back(18, 'var(--ink)')}</button>
        <div className="settings-title">Family circle</div>
        <div style={{ width: 36 }}/>
      </div>
      <div className="share-hero">
        <div className="share-hero-mark">{Icon.invite(28, 'var(--gold)')}</div>
        <div className="share-hero-title">{s.name}'s circle</div>
        <div className="share-hero-sub">2 of 4 family members listening in. They can hear new stories the moment you capture them.</div>
      </div>
      <div className="settings-group-label">Members</div>
      <div className="settings-group">
        {family.map((f, i) => (
          <div key={i} className="settings-pair">
            <Avatar name={f.name} tone={f.tone} size={42} border={false}/>
            <div className="settings-pair-info">
              <div className="settings-pair-name">{f.name}</div>
              <div className="settings-pair-meta">{f.rel}</div>
            </div>
            {f.invited
              ? <span className="share-tag">listening</span>
              : <button className="share-invite-btn">Invite</button>}
          </div>
        ))}
      </div>
      <button className="share-cta">
        {Icon.share(14, 'currentColor')} Send invite link
      </button>
    </div>
  );
}

Object.assign(window, {
  SUBJECTS, OnboardScreen, HomeScreen, RecordScreen, PostScreen,
  MemoryScreen, MemoirScreen, ShelfZoomScreen, SettingsScreen, ShareScreen,
});
