/* Homepage app — diversified, TED-style layout */
const { useMemo: hUseMemo, useState: hUseState } = React;

function FormatTags({ talk }) {
  const { t } = window.SK_I18N.useLang();
  const hasVideo = talk.kind !== 'audio';
  return (
    <div className="fmts">
      {hasVideo && <span className="fmt is-accent"><Icon name="video" size={13} /> {t('fmt_video')}</span>}
      <span className="fmt"><Icon name="headphones" size={13} /> {t('fmt_audio')}</span>
      <span className="fmt"><Icon name="book" size={13} /> {t('fmt_text')}</span>
    </div>
  );
}

function SearchStrip() {
  const D = window.SK_DATA;
  const { t } = window.SK_I18N.useLang();
  const [q, setQ] = hUseState('');
  const [cat, setCat] = hUseState('Tümü');
  const goSearch = (term) => { window.location.href = 'search.html' + (term && term.trim() ? ('?q=' + encodeURIComponent(term.trim())) : ''); };
  const results = hUseMemo(() => {
    if (!q.trim()) return [];
    const n = q.toLocaleLowerCase('tr');
    return [D.featured, ...D.talks].filter(t =>
      (cat === 'Tümü' || t.category === cat) &&
      (t.title.toLocaleLowerCase('tr').includes(n) || t.speaker.name.toLocaleLowerCase('tr').includes(n) || t.category.toLocaleLowerCase('tr').includes(n))
    ).slice(0, 6);
  }, [q, cat]);

  return (
    <div className="section tight" id="ara">
      <div className="wrap">
        <div className="searchbar">
          <Icon name="search" size={22} style={{ color: 'var(--ink-3)' }} />
          <input value={q} onChange={e => setQ(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') goSearch(q); }}
            placeholder={t('search_big_ph')} aria-label={t('search_btn')} />
          <button className="btn btn-primary" style={{ height: 46 }} onClick={() => goSearch(q)}>{t('search_btn')} <Icon name="arrow" size={16} /></button>
        </div>
        <div className="search-cats">
          {D.categories.map(c => (
            <button key={c} className={'chip' + (cat === c ? ' active' : '')} onClick={() => setCat(c)}>{c === 'Tümü' ? t('all') : c}</button>
          ))}
          <a className="chip chip-detail" href="search.html">
            <Icon name="sliders" size={14} /> {t('detailed')}
          </a>
        </div>
        {q.trim() && (
          <div className="search-results">
            <div className="sr-count">{results.length ? `“${q}” ${t('res_for')} ${results.length}+` : `“${q}” ${t('res_for')} ${t('no_res')}`}</div>
            <div className="grid-3">{results.map(t => <TalkCard key={t.slug} talk={t} />)}</div>
          </div>
        )}
      </div>
    </div>
  );
}

function Hero() {
  const D = window.SK_DATA;
  const { t } = window.SK_I18N.useLang();
  const f = D.featured;
  return (
    <section className="hero">
      <div className="wrap hero-grid">
        <div className="hero-copy">
          <div className="hero-kicker kicker accent"><span className="pulse"></span> {t('hero_kicker')}</div>
          <h1>{t('hero_t1')}<br /><span className="em">{t('hero_t2')}</span> {t('hero_t3')}</h1>
          <p className="hero-lead">{t('hero_lead')}</p>
          <div className="hero-cta">
            <a className="btn btn-primary" href={`watch.html?v=${f.slug}`} style={{ height: 50, paddingInline: 24 }}><Icon name="play" size={16} /> {t('hero_cta1')}</a>
            <a className="btn btn-ghost" href="#kategoriler" style={{ height: 50, paddingInline: 22 }}><Icon name="grid" size={17} /> {t('hero_cta2')}</a>
          </div>
          <div className="hero-stats">
            <div className="hero-stat"><b>3.400+</b><span>{t('stat1')}</span></div>
            <div className="hero-stat"><b>%100</b><span>{t('stat2')}</span></div>
            <div className="hero-stat"><b>14</b><span>{t('stat3')}</span></div>
          </div>
        </div>
        <a className="hero-feature" href={`watch.html?v=${f.slug}`}>
          <span className="hf-badge card-kind"><Icon name="sparkle" size={13} /> {t('discover')}</span>
          <div className="hf-art" data-cat={f.category}></div>
          <span className="hf-play"><Icon name="play" size={28} /></span>
          <div className="hf-info">
            <span className="tag">{f.category}</span>
            <h3>{f.title}</h3>
            <div className="hf-meta"><span>{f.speaker.short}</span><span className="dot">·</span><span>{f.durLabel}</span><span className="dot">·</span><span>{f.greg}</span></div>
          </div>
        </a>
      </div>
    </section>
  );
}

/* ---- Spotlight: editor feature + ranked "most listened" list ---- */
function Spotlight() {
  const D = window.SK_DATA;
  const { t } = window.SK_I18N.useLang();
  const f = D.featured;
  const trending = hUseMemo(() => [...D.talks].sort((a, b) => b.views - a.views).slice(0, 5), []);
  return (
    <section className="section" id="spot">
      <div className="wrap">
        <div className="sec-head">
          <div>
            <div className="kicker accent" style={{ marginBottom: 8, display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="sparkle" size={14} /> {t('spot_kicker')}</div>
            <h2>{t('spot_h')}</h2>
            <p>{t('spot_sub')}</p>
          </div>
          <a className="sec-more" href="search.html">{t('view_all')} <Icon name="arrow" size={16} /></a>
        </div>
        <div className="spotlight">
          <a className="spot-feature" href={`watch.html?v=${f.slug}`}>
            <div className="spot-art sk-art-bg" data-cat={f.category}>
              <span className="spot-badge"><Icon name="sparkle" size={12} /> {t('spot_kicker')}</span>
              <span className="spot-play"><Icon name="play" size={24} /></span>
              <span className="spot-dur">{f.durLabel}</span>
            </div>
            <div className="spot-info">
              <span className="tag">{f.category}</span>
              <h3>{f.title}</h3>
              <p>{f.summary}</p>
              <FormatTags talk={f} />
              <div className="card-meta"><span>{f.speaker.short}</span><span className="dot">·</span><span>{f.greg}</span></div>
            </div>
          </a>
          <div className="rank">
            <div className="rank-head"><span className="rank-live"></span><h3>{t('spot_listen')}</h3></div>
            <div className="rank-list">
              {trending.map((tk, i) => (
                <a className="rank-item" key={tk.slug} href={`watch.html?v=${tk.slug}`}>
                  <span className="rank-num">{String(i + 1).padStart(2, '0')}</span>
                  <span className="rank-main">
                    <span className="rank-cat">{tk.category}</span>
                    <b>{tk.title}</b>
                    <span className="rank-meta">
                      <span className="rank-spk">{tk.speaker.short}</span>
                      <span className="rank-sep">·</span>
                      <span className="rank-views">{D.fmtCount(tk.views)} {t('views')}</span>
                    </span>
                  </span>
                  <span className="rank-dur">{tk.durLabel}</span>
                </a>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---- Playlist row: dark collection cover + horizontal cards ---- */
function Row({ row }) {
  const D = window.SK_DATA;
  const { t } = window.SK_I18N.useLang();
  const talks = row.slugs.map(s => D.bySlug[s]).filter(Boolean);
  return (
    <section className="section" id={row.id}>
      <div className="wrap">
        <div className="row-scroll">
          <a className="lead" href="search.html">
            <span className="lead-cat"><Icon name="grid" size={13} /> {t('collection')}</span>
            <h3 className="lead-h">{row.title}</h3>
            <p className="lead-sub">{row.sub}</p>
            <span className="lead-more">{t('explore_all')} <Icon name="arrow" size={16} /></span>
          </a>
          {talks.map(tk => <TalkCard key={tk.slug} talk={tk} />)}
        </div>
      </div>
    </section>
  );
}

/* ---- Listen strip: audio-forward rows with a waveform ---- */
function ListenRow({ talk }) {
  const bars = hUseMemo(() => {
    const out = [];
    for (let i = 0; i < 30; i++) {
      const h = 22 + Math.abs(Math.sin(i * 1.3 + talk.dur * 0.07)) * 64 + (i % 4) * 6;
      out.push(Math.max(14, Math.min(100, Math.round(h))));
    }
    return out;
  }, [talk.slug]);
  return (
    <a className="lrow" href={`watch.html?v=${talk.slug}`}>
      <span className="lrow-play"><Icon name="play" size={17} /></span>
      <span className="lrow-main">
        <b>{talk.title}</b>
        <span className="lrow-meta">{talk.speaker.short} · {talk.category}</span>
      </span>
      <span className="wave" aria-hidden="true">
        {bars.map((b, i) => <i key={i} style={{ height: b + '%', background: i < 10 ? 'var(--accent)' : undefined }} />)}
      </span>
      <span className="lrow-dur">{talk.durLabel}</span>
    </a>
  );
}

function ListenStrip() {
  const D = window.SK_DATA;
  const { t } = window.SK_I18N.useLang();
  const picks = ['islami-edep-ve-allaha-yonelis', 'rizik-ve-zenginlik', 'musab-ibni-umeyr-ra', 'alimlerin-faziletleri', 'peygamberimizin-vefati', 'selamlasmayi-yayginlastirin']
    .map(s => D.bySlug[s]).filter(Boolean);
  return (
    <section className="section">
      <div className="wrap">
        <div className="listen">
          <div className="listen-head">
            <div>
              <div className="kicker accent"><Icon name="headphones" size={14} /> {t('listen_kicker')}</div>
              <h2>{t('listen_h')}</h2>
              <p>{t('listen_sub')}</p>
            </div>
            <a className="btn btn-ghost" href="search.html">{t('listen_all')} <Icon name="arrow" size={15} /></a>
          </div>
          <div className="listen-grid">
            {picks.map(tk => <ListenRow key={tk.slug} talk={tk} />)}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---- Transcript band: pull-quote + faux clickable transcript ---- */
function TranscriptBand() {
  const D = window.SK_DATA;
  const { t } = window.SK_I18N.useLang();
  const f = D.featured;
  const lines = f.transcript.slice(8, 13);
  return (
    <section className="section">
      <div className="wrap">
        <div className="txband">
          <div className="txband-in">
            <div className="kicker txband-kicker"><Icon name="book" size={14} /> {t('txb_kicker')}</div>
            <blockquote>“Biz dinlerken mest olurduk, mum gibi erirdik; herkes erirdi.”</blockquote>
            <div className="txband-cite">— <b>{f.speaker.name}</b> · {f.title}</div>
            <div className="txband-cta">
              <a className="btn btn-primary" href={`watch.html?v=${f.slug}`}><Icon name="book" size={15} /> {t('txb_cta1')}</a>
              <a className="btn txband-ghost" href={`watch.html?v=${f.slug}`}><Icon name="play" size={12} /> {t('txb_cta2')}</a>
            </div>
          </div>
          <div className="txband-lines">
            {lines.map((ln, i) => (
              <div className={'txl' + (ln.text.indexOf('mum gibi') !== -1 ? ' on' : '')} key={i}>
                <span className="txl-t">{D.fmtDur(ln.t)}</span>
                <span className="txl-x">{ln.text}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---- Topic tiles: browse by subject ---- */
function TopicTiles() {
  const D = window.SK_DATA;
  const { t } = window.SK_I18N.useLang();
  const all = [D.featured, ...D.talks];
  const cats = D.categories.filter(c => c !== 'Tümü' && all.some(x => x.category === c));
  return (
    <section className="section" id="kategoriler">
      <div className="wrap">
        <div className="sec-head">
          <div>
            <div className="kicker accent" style={{ marginBottom: 8 }}>{t('topics_kicker')}</div>
            <h2>{t('topics_h')}</h2>
            <p>{t('topics_sub')}</p>
          </div>
          <a className="sec-more" href="search.html">{t('archive_all')} <Icon name="arrow" size={16} /></a>
        </div>
        <div className="topics-grid">
          {cats.map((c, i) => (
            <a className={'topic' + (i === 0 ? ' accent' : '')} key={c} href={'search.html?cat=' + encodeURIComponent(c)}>
              <span className="topic-k">{t('topics_kicker')}</span>
              <div className="topic-foot">
                <h3>{c}</h3>
                <span className="topic-arrow"><Icon name="arrow" size={17} /></span>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

function MemberBand() {
  const [isMember] = useMember();
  const { t } = window.SK_I18N.useLang();
  const feats = [
    { ic: 'sliders', t: 'Detaylı arama', d: 'Kategori, hicrî/milâdî tarih ve süreye göre filtreleyin.' },
    { ic: 'bookmark', t: 'Listelerim', d: 'Sevdiğiniz sohbetleri kaydedin, listeler oluşturun.' },
    { ic: 'clock', t: 'Kaldığınız yerden', d: 'İlerlemeniz her cihazda sizinle gelsin.' },
  ];
  return (
    <section className="section">
      <div className="wrap">
        <div className="member-band">
          <div className="mb-glow" aria-hidden="true"></div>
          <div className="mb-l">
            <div className="kicker" style={{ color: 'color-mix(in srgb, var(--accent) 55%, white)' }}>{t('member_kicker')}</div>
            <h2>{t('member_h')}</h2>
            <p>{t('member_p')}</p>
            <div className="mb-cta">
              {isMember
                ? <span className="mb-isnow"><Icon name="check" size={18} /> {t('member_already')}</span>
                : <button className="btn mb-btn" onClick={() => openModal('join')}><Icon name="star" size={16} /> {t('join')}</button>}
              {!isMember && <span className="mb-fine">{t('member_free')}</span>}
            </div>
          </div>
          <ul className="mb-feats">
            {feats.map(f => (
              <li key={f.t}><span className="mbf-ic"><Icon name={f.ic} size={18} /></span>
                <div><b>{f.t}</b><span>{f.d}</span></div></li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
}

function Speakers() {
  const D = window.SK_DATA;
  const { t, lang } = window.SK_I18N.useLang();
  const blurbOf = (s) => (lang === 'tr' ? s.blurb : (s.blurbEn || s.blurb));
  return (
    <section className="section" id="konusmacilar">
      <div className="wrap">
        <div className="sec-head"><div><h2>{t('speakers')}</h2><p>{t('speakers_sub')}</p></div></div>
        <div className="speakers">
          {D.speakers.map((s, i) => (
            <div key={s.id} className={'spk spk-' + (i + 1)}>
              <Monogram person={s} size={84} />
              <div className="spk-body">
                <h3>{s.name}</h3>
                {s.years && <div className="spk-years">{s.years}</div>}
                {s.role && <div className="spk-role">{s.role}</div>}
                <p>{blurbOf(s)}</p>
                <div className="spk-actions">
                  <a className="btn btn-ghost spk-btn" href={`about.html?p=${s.id}`}><Icon name="user" size={15} /> {t('about_label')}</a>
                  <a className="btn btn-primary spk-btn" href={`search.html?sp=${s.id}`}><Icon name="play" size={13} /> {s.id === 'mnc' ? t('speaker_link_mnc') : t('speaker_link')}</a>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function App() {
  const D = window.SK_DATA;
  const [t, setTweak] = useTweaks(window.SK_TWEAK_DEFAULTS);
  window.applyTweaks(t);
  const rows = D.rows;
  return (
    <>
      <Header active="Keşfet" />
      <main>
        <Hero />
        <SearchStrip />
        <Spotlight />
        {rows[0] && <Row row={rows[0]} />}
        <ListenStrip />
        {rows[1] && <Row row={rows[1]} />}
        <TranscriptBand />
        {rows[2] && <Row row={rows[2]} />}
        <TopicTiles />
        {rows[3] && <Row row={rows[3]} />}
        <MemberBand />
        <Speakers />
      </main>
      <Footer />
      <SKTweaks t={t} setTweak={setTweak} />
      <ModalHost />
    </>
  );
}

(window.SK_READY || Promise.resolve()).then(() =>
  ReactDOM.createRoot(document.getElementById('root')).render(<App />));
