/* ===========================================================
   راویار — Story screen (immersive reader + player)
   =========================================================== */
function AdBreak({ cat, go }) {
  const cc = OMID.catOf(cat);
  const [sec, setSec] = React.useState(5);
  React.useEffect(() => { if (sec <= 0) return; const t = setTimeout(() => setSec(sec - 1), 1000); return () => clearTimeout(t); }, [sec]);
  return (
    <div className="gold-frame" style={{ position: 'relative', height: 70, borderRadius: 'var(--r-md)', overflow: 'hidden', marginBottom: 14 }}>
      <PosterArt grad={['#0e1c3a', cc.hue, '#e7c673']} seed={6} dim={0.1} />
      <div className="row between" style={{ position: 'absolute', inset: 0, padding: '0 18px', gap: 12 }}>
        <div className="row gap-2" style={{ minWidth: 0 }}>
          <span className="chip" style={{ fontSize: 10.5, background: 'rgba(7,13,34,.5)', flexShrink: 0 }}>{L('آگهی', 'Ad')} · {OMID.TX(cc)}</span>
          <b style={{ fontSize: 14.5, whiteSpace: 'nowrap' }}>{OMID.TX(OMID.AD_SAMPLE, 'brand')}</b>
          <span className="muted" style={{ fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{L('آگهیِ متناسب با موضوعِ این داستان', 'An ad matched to this story’s theme')}</span>
        </div>
        <div className="row gap-2" style={{ flexShrink: 0 }}>
          <button onClick={() => go('pricing')} className="chip" style={{ whiteSpace: 'nowrap' }}><CoinGlyph size={13} /> {L('بدون تبلیغ شو', 'Go ad-free')}</button>
          <span className="chip fa-num" style={{ fontSize: 11.5, whiteSpace: 'nowrap' }}>{sec > 0 ? L('رد آگهی ' + OMID.numFa(sec), 'Skip ad ' + sec) : L('رد آگهی ✓', 'Skip ad ✓')}</span>
        </div>
      </div>
    </div>
  );
}

function StoryScreen({ story, openStory, go, coins, earn }) {
  const poet = OMID.poetOf(story.poet);
  const cat = OMID.catOf(story.cat);
  const [claimed, setClaimed] = React.useState(false);
  const play = () => { if (!claimed && earn) { earn(5, L('تماشای داستان', 'watching a story')); setClaimed(true); } };
  const related = OMID.STORIES.filter(s => s.id !== story.id && (s.cat === story.cat || s.poet === story.poet)).slice(0, 4);
  const chars = [{ fa: story.hero, en: story.heroEn }, ...OMID.HEROES.filter(h => h.fa !== story.hero)].slice(0, 4);

  return (
    <div>
      {/* Cinematic player */}
      <section style={{ maxWidth: 'var(--maxw)', margin: '8px auto 0', padding: '0 22px' }}>
        <AdBreak cat={story.cat} go={go} />
        <div className="gold-frame" style={{ position: 'relative', height: 480, borderRadius: 'var(--r-xl)', overflow: 'hidden', boxShadow: 'var(--shadow-pop)' }}>
          <PosterArt grad={story.grad} seed={4} dim={0.18} />
          <div className="row between" style={{ position: 'absolute', top: 18, insetInline: 18 }}>
            <span className="badge-ai"><Icon name="sparkle" size={12} /> AI</span>
            <span className="chip" style={{ background: 'rgba(7,13,34,.5)' }}>1080p</span>
          </div>
          {/* play button */}
          <button onClick={play} style={{ position: 'absolute', inset: 0, margin: 'auto', width: 92, height: 92, borderRadius: 999,
            background: 'linear-gradient(135deg,var(--gold-400),var(--gold-600))', display: 'grid', placeItems: 'center',
            boxShadow: '0 18px 50px -12px var(--gold-glow)', color: '#2a1d05' }}>
            <Icon name="play" size={34} />
          </button>
          <div style={{ position: 'absolute', insetInline: 0, bottom: 0, padding: '0 40px 30px' }}>
            <div style={{ fontFamily: 'var(--verse)', fontSize: 27, textAlign: 'center', color: 'var(--gold-200)', textShadow: '0 2px 14px rgba(0,0,0,.7)' }}>{OMID.TX(story, 'verse').split('/')[0]}</div>
            {/* scrubber */}
            <div style={{ marginTop: 22, height: 5, borderRadius: 999, background: 'rgba(231,222,201,.2)' }}>
              <div style={{ width: '34%', height: '100%', borderRadius: 999, background: 'linear-gradient(90deg,var(--turq-400),var(--gold-400))' }} />
            </div>
            <div className="row between fa-num" style={{ marginTop: 8, fontSize: 12.5, color: 'var(--muted)' }}>
              <span>{OMID.num('۰۷:۱۲')}</span><span>{OMID.num(story.mins)}:00</span>
            </div>
          </div>
        </div>
      </section>

      {/* Title + meta + body */}
      <section style={{ maxWidth: 'var(--maxw)', margin: '0 auto', padding: '30px 22px', display: 'grid', gridTemplateColumns: '1fr 320px', gap: 36 }}>
        <div>
          <div className="row gap-2" style={{ marginBottom: 14 }}>
            <span className="chip is-active" style={{ background: `${cat.hue}`, color: '#1a0f04' }}>{OMID.TX(cat)}</span>
            <span className="chip">{OMID.TX(story, 'era')}</span>
            <Stars value={story.rating} size={15} />
          </div>
          <h1 style={{ fontSize: 46, fontFamily: 'var(--display)', fontWeight: 400, letterSpacing: 1 }}>{OMID.TX(story)}</h1>
          <div className="turq" style={{ fontFamily: 'var(--verse)', fontSize: 20, marginTop: 4 }}>{OMID.getLang() === 'en' ? OMID.TX(poet) : (story.en + ' · ' + poet.fa)}</div>

          {/* verse card */}
          <div className="panel gold-frame" style={{ padding: '26px 30px', marginTop: 24, textAlign: 'center' }}>
            <Shamseh size={26} />
            <div style={{ fontFamily: 'var(--verse)', fontSize: 24, lineHeight: 2.2, color: 'var(--gold-200)', marginTop: 12 }}>
              {OMID.TX(story, 'verse').split('/').map((h, i) => <div key={i}>{h.trim()}</div>)}
            </div>
          </div>

          <p style={{ fontSize: 18, lineHeight: 2.3, color: 'var(--cream-2)', marginTop: 26 }}>{OMID.TX(story, 'body')}</p>
          <p style={{ fontSize: 18, lineHeight: 2.3, color: 'var(--cream-2)', marginTop: 14 }}>
            {L('این روایت با تصویرگری هوش مصنوعی و الهام از نگارگری و مینیاتور ایرانی، با تکیه بر نور، معماری و خوشنویسی بازآفرینی شده تا زیبایی بصری در خدمت روایتِ کهن قرار گیرد.', 'This retelling is reimagined with AI illustration inspired by Persian miniature and illumination — leaning on light, architecture and calligraphy so that visual beauty serves the ancient narrative.')}
          </p>

          {/* characters */}
          <h3 style={{ fontSize: 22, marginTop: 34, marginBottom: 16 }}>{L('شخصیت‌ها', 'Characters')}</h3>
          <div className="row gap-3 wrap">
            {chars.map((h, i) => (
              <div key={i} className="row gap-2" style={{ alignItems: 'center' }}>
                <div className="gold-frame" style={{ width: 54, height: 54, borderRadius: 999, position: 'relative', overflow: 'hidden' }}>
                  <PosterArt grad={story.grad} seed={i + 3} />
                  <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', fontFamily: 'var(--display)', fontSize: 22 }}>{OMID.TX(h)[0]}</div>
                </div>
                <div className="col"><b style={{ fontSize: 15 }}>{OMID.TX(h)}</b><span className="muted" style={{ fontSize: 12 }}>{L('شخصیت داستان', 'Character')}</span></div>
              </div>
            ))}
          </div>
        </div>

        {/* Sidebar */}
        <aside className="col gap-3">
          <button onClick={play} className="btn btn-gold" style={{ justifyContent: 'center', padding: '14px' }}><Icon name="play" size={16} /> {claimed ? L('در حال پخش · ۵+ سکه', 'Playing · 5+ coins') : L('پخش روایت', 'Play story')}</button>
          <div className="row gap-2">
            <button className="btn btn-ghost grow" style={{ justifyContent: 'center', padding: '11px' }}><Icon name="plus" size={15} /> {L('لیست من', 'My list')}</button>
            <ShareButton story={story} />
          </div>
          <div className="panel" style={{ padding: 20 }}>
            <div className="col gap-3">
              {[[L('شاعر/راوی', 'Poet / narrator'), OMID.TX(poet)], [L('دورهٔ تاریخی', 'Historical era'), OMID.TX(story, 'era')], [L('موضوع', 'Theme'), OMID.TX(cat)], [L('قهرمان', 'Hero'), OMID.TX(story, 'hero')], [L('مدت', 'Duration'), OMID.num(story.mins) + L(' دقیقه', ' min')], [L('زبان', 'Language'), L('فارسی', 'Persian')]].map(([k, v], i) => (
                <div key={i} className="row between" style={{ borderBottom: i < 5 ? '1px solid var(--hairline)' : 'none', paddingBottom: 10 }}>
                  <span className="muted" style={{ fontSize: 13.5 }}>{k}</span>
                  <b style={{ fontSize: 14.5 }}>{v}</b>
                </div>
              ))}
            </div>
          </div>
          <div className="panel" style={{ padding: 20 }}>
            <div className="row gap-2" style={{ marginBottom: 12 }}><Icon name="sparkle" size={16} style={{ color: 'var(--turq-400)' }} /><b>{L('پرامپت تصویر', 'Image prompt')}</b></div>
            <p className="muted" style={{ fontSize: 13, lineHeight: 1.9 }}>{L('«' + OMID.TX(story) + ' — معماری ایرانی، نور فیروزه‌ای، خوشنویسی نستعلیق، سبک مینیاتور و نگارگری»', '“' + OMID.TX(story) + ' — Persian architecture, turquoise light, Nastaliq calligraphy, miniature & illumination style”')}</p>
            <button className="chip" style={{ marginTop: 12 }}><Icon name="pen" size={13} /> {L('بازتولید با AI', 'Regenerate with AI')}</button>
          </div>
        </aside>
      </section>

      {/* Related */}
      <section style={{ maxWidth: 'var(--maxw)', margin: '0 auto', padding: '0 22px 10px' }}>
        <Rail title={L('داستان‌های مرتبط', 'Related stories')} sub={L('در همین مسیر', 'Along the same path')}>
          {related.map(s => <StoryCard key={s.id} story={s} onOpen={openStory} />)}
        </Rail>
      </section>
    </div>
  );
}
window.StoryScreen = StoryScreen;
