// Ana Sayfa / Home
function HomePage({ setPage, setModule, setNewsSlug }) {
  const data = window.APP_DATA;
  const { user, modules } = data;
  const t = window.t;
  const fresh = user.completed.length === 0;
  const recommended = modules[user.inProgress] || modules[0];
  const next = modules[(user.inProgress || 0) + 1] || modules[1];

  const pct = Math.round((user.completed.length / modules.length) * 100);

  // Son 2 Anthropic haberi
  const [latestNews, setLatestNews] = React.useState(null);
  React.useEffect(() => {
    let cancelled = false;
    window.API.listNews(2)
      .then(r => { if (!cancelled) setLatestNews(r.items || []); })
      .catch(() => { if (!cancelled) setLatestNews([]); });
    return () => { cancelled = true; };
  }, []);

  const fmtNewsDate = (s) => {
    if (!s) return '';
    const d = new Date(s);
    if (isNaN(d.getTime())) return s;
    const isEn = window.LANG === 'en';
    const months = isEn
      ? ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
      : ['Oca','Şub','Mar','Nis','May','Haz','Tem','Ağu','Eyl','Eki','Kas','Ara'];
    return `${d.getUTCDate()} ${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
  };

  // Rozet sayısı: tamamlanan modüllere göre belirleniyor (her 4 modülde 1 ana rozet + sertifika)
  const earnedBadges =
    (user.completed.includes(0) ? 1 : 0) +
    (user.completed.includes(1) ? 1 : 0) +
    (user.completed.includes(2) ? 1 : 0) +
    (user.completed.includes(4) ? 1 : 0) +
    (user.completed.includes(7) ? 1 : 0) +
    (user.completed.length === modules.length ? 1 : 0);

  return (
    <div className="page fade-up">
      {/* HERO */}
      <div style={{
        background: 'linear-gradient(135deg, var(--moss-soft) 0%, var(--sun-soft) 40%, var(--lavender-soft) 100%)',
        borderRadius: 'var(--r-xl)',
        padding: '42px 44px',
        marginBottom: 40,
        position: 'relative',
        overflow: 'hidden',
        border: '1px solid var(--line)',
      }}>
        {/* Decoration */}
        <div style={{ position: 'absolute', top: -30, right: -20, fontSize: 140, transform: 'rotate(12deg)', opacity: 0.9 }}>✨</div>
        <div style={{ position: 'absolute', bottom: -40, right: 160, fontSize: 90, transform: 'rotate(-18deg)', opacity: 0.7 }}>📚</div>

        <div style={{ position: 'relative', zIndex: 1, maxWidth: 640 }}>
          <div className="kicker" style={{ marginBottom: 12 }}>{t('home.hello')} {user.name.split(' ')[0].toUpperCase()} 👋</div>
          <h1 className="page-title" style={{ fontSize: 52 }}>
            {window.LANG === 'en' ? (
              <>Learn Claude <span style={{ color: 'var(--moss-deep)', fontStyle: 'italic' }}>from beginner to expert</span><br/>{fresh ? '— start now.' : '— keep going.'}</>
            ) : (
              <>Claude'u <span style={{ color: 'var(--moss-deep)', fontStyle: 'italic' }}>sıfırdan ustaya</span><br/>{fresh ? 'öğrenmeye başla.' : 'öğrenmeye devam.'}</>
            )}
          </h1>
          <p className="page-sub" style={{ fontSize: 18, marginTop: 16, color: 'var(--ink-2)' }}>
            {fresh ? (
              window.LANG === 'en'
                ? <>A {modules.length}-module journey awaits you. First module: <strong style={{ color: 'var(--ink)' }}>{recommended.title}</strong>.</>
                : <>{modules.length} modüllük yolculuğun seni bekliyor. İlk modül: <strong style={{ color: 'var(--ink)' }}>{recommended.title}</strong>.</>
            ) : (
              window.LANG === 'en'
                ? <>{user.completed.length} modules done, {modules.length - user.completed.length} to go. Up next: <strong style={{ color: 'var(--ink)' }}>{recommended.title}</strong>.</>
                : <>{user.completed.length} modül bitti, {modules.length - user.completed.length} modül kaldı. Sıradaki: <strong style={{ color: 'var(--ink)' }}>{recommended.title}</strong>.</>
            )}
          </p>
          <div className="row" style={{ gap: 10, marginTop: 24 }}>
            <button className="btn btn-accent" onClick={() => { setModule(recommended.id); setPage('module'); }}>
              <Icon name="play" size={15} /> {fresh ? t('home.btn_start') : t('home.btn_continue')}
            </button>
            <button className="btn btn-ghost" onClick={() => setPage('path')}>
              {t('home.btn_all_modules')}
            </button>
          </div>

          {/* Mini stats — sadece anlamlı olanlar */}
          <div className="row" style={{ gap: 20, marginTop: 28, flexWrap: 'wrap' }}>
            <div className="row" style={{ gap: 8 }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--moss)', display: 'grid', placeItems: 'center', color: '#fff' }}>
                <Icon name="check" size={18} />
              </div>
              <div>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{user.completed.length} / {modules.length} {t('home.stat_modules_done')}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{window.LANG === 'en' ? `${pct}% ${t('home.stat_progress')}` : `%${pct} ${t('home.stat_progress')}`}</div>
              </div>
            </div>
            {user.streak > 0 && (
              <div className="row" style={{ gap: 8 }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--coral)', display: 'grid', placeItems: 'center', color: '#fff' }}>
                  <Icon name="flame" size={18} />
                </div>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{user.streak} {t('home.stat_streak')}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{t('home.stat_streak_sub')}</div>
                </div>
              </div>
            )}
            {earnedBadges > 0 && (
              <div className="row" style={{ gap: 8 }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--lavender)', display: 'grid', placeItems: 'center', color: '#fff' }}>
                  <Icon name="star" size={18} />
                </div>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{earnedBadges} {t('home.stat_badges')}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{t('home.stat_badges_sub')}</div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Devam eden / Continuing */}
      <div style={{ marginBottom: 40 }}>
        <div className="row" style={{ justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div className="kicker">{fresh ? t('home.section_starting_kicker') : t('home.section_continuing_kicker')}</div>
            <h2 className="section-title">{fresh ? t('home.section_first_title') : t('home.section_current_title')}</h2>
          </div>
        </div>
        <div style={{
          display: 'grid',
          gridTemplateColumns: '1.2fr 1fr',
          gap: 24,
        }}>
          {/* Current module card */}
          <div style={{
            background: 'var(--bg-elevated)',
            borderRadius: 'var(--r-xl)',
            border: '1px solid var(--line)',
            overflow: 'hidden',
            display: 'grid',
            gridTemplateColumns: '200px 1fr',
          }}>
            <div style={{
              background: `linear-gradient(135deg, var(--lavender-soft), var(--lavender))`,
              display: 'grid',
              placeItems: 'center',
              position: 'relative',
            }}>
              <span style={{ fontSize: 80, transform: 'rotate(-6deg)', filter: 'drop-shadow(0 6px 8px rgba(0,0,0,0.15))' }}>{recommended.emoji}</span>
            </div>
            <div style={{ padding: 24 }}>
              <span className={`chip chip-${recommended.color}`} style={{ marginBottom: 10 }}>{t('common.module')} {String(recommended.id + 1).padStart(2, '0')} · {recommended.level} {t('home.module_chip_level')}</span>
              <h3 style={{ fontSize: 22, marginBottom: 6 }}>{recommended.title}</h3>
              <p style={{ color: 'var(--ink-2)', fontSize: 14, marginBottom: 16 }}>{recommended.subtitle}</p>
              <div className="row" style={{ justifyContent: 'space-between', fontSize: 12, color: 'var(--ink-3)', marginBottom: 16, fontFamily: 'var(--font-mono)' }}>
                <span>{recommended.lessons} {t('home.lessons_caps')}</span>
                <span>≈ {recommended.duration.toUpperCase()} {t('home.total_caps_after')}</span>
              </div>
              <button className="btn btn-primary btn-sm" onClick={() => { setModule(recommended.id); setPage('module'); }}>
                <Icon name="play" size={13} /> {user.completed.length === 0 ? t('home.btn_start_module') : t('home.btn_continue_module')}
              </button>
            </div>
          </div>

          {/* Next up card */}
          <div style={{
            background: 'var(--bg-elevated)',
            borderRadius: 'var(--r-xl)',
            border: '1px dashed var(--line-strong)',
            padding: 24,
            display: 'flex',
            flexDirection: 'column',
          }}>
            <div className="kicker" style={{ marginBottom: 8 }}>{t('home.next_kicker')} {String(next.id + 1).padStart(2, '0')}</div>
            <h3 style={{ fontSize: 18, marginBottom: 4 }}>{next.title}</h3>
            <p style={{ color: 'var(--ink-3)', fontSize: 13, lineHeight: 1.5 }}>{next.subtitle}</p>
            <div className="row" style={{ gap: 6, marginTop: 12, flexWrap: 'wrap' }}>
              {next.tools.slice(0, 3).map(tn => <span key={tn} className="chip">{tn}</span>)}
            </div>
            <div style={{ flex: 1 }} />
            <div className="row" style={{ gap: 12, marginTop: 16, fontSize: 12, color: 'var(--ink-3)' }}>
              <span className="row" style={{ gap: 4 }}><Icon name="clock" size={12} />{next.duration}</span>
              <span>·</span>
              <span>{next.lessons} {t('common.lessons')}</span>
            </div>
          </div>
        </div>
      </div>

      {/* Quick tools */}
      <div style={{ marginBottom: 40 }}>
        <div className="row" style={{ justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div className="kicker">{t('home.quick_kicker')}</div>
            <h2 className="section-title">{t('home.quick_title')}</h2>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={() => setPage('tools')}>{t('home.quick_all_tools')} <Icon name="arrow" size={14} /></button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
          {[
            { title: t('home.quick_card_1_title'), desc: t('home.quick_card_1_desc'), emoji: '✍️', color: 'lavender', module: 2 },
            { title: t('home.quick_card_2_title'), desc: t('home.quick_card_2_desc'), emoji: '🎨', color: 'sky', module: 4 },
            { title: t('home.quick_card_3_title'), desc: t('home.quick_card_3_desc'), emoji: '📊', color: 'moss', module: 7 },
            { title: t('home.quick_card_4_title'), desc: t('home.quick_card_4_desc'), emoji: '💻', color: 'coral', module: 10 },
          ].map((q, i) => (
            <button
              key={i}
              className="card"
              onClick={() => { setModule(q.module); setPage('module'); }}
              style={{
                padding: 18,
                textAlign: 'left',
                border: `1.5px solid var(--line)`,
                cursor: 'pointer',
                transition: 'all 0.15s',
                display: 'flex',
                flexDirection: 'column',
                gap: 4,
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = `var(--${q.color})`; e.currentTarget.style.transform = 'translateY(-2px)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.transform = 'translateY(0)'; }}
            >
              <span style={{ fontSize: 32, marginBottom: 6 }}>{q.emoji}</span>
              <div style={{ fontWeight: 700, fontSize: 15 }}>{q.title}</div>
              <div style={{ color: 'var(--ink-3)', fontSize: 12 }}>{q.desc}</div>
            </button>
          ))}
        </div>
      </div>

      {/* Tips row */}
      <div style={{
        background: 'var(--ink)',
        color: 'var(--bg)',
        borderRadius: 'var(--r-xl)',
        padding: 32,
        display: 'grid',
        gridTemplateColumns: '1fr auto',
        gap: 32,
        alignItems: 'center',
      }}>
        <div>
          <div className="kicker" style={{ color: 'var(--sun)', marginBottom: 12 }}>{t('home.tip_kicker')}</div>
          <h3 style={{ color: 'var(--bg)', fontSize: 24, marginBottom: 10, maxWidth: 680 }}>
            {window.LANG === 'en'
              ? <>Wrap long documents to Claude inside <span style={{ fontFamily: 'var(--font-mono)', fontSize: 20 }}>&lt;document&gt;</span> tags.</>
              : <>Uzun belgeleri Claude'a <span style={{ fontFamily: 'var(--font-mono)', fontSize: 20 }}>&lt;document&gt;</span> etiketi içinde verin.</>
            }
          </h3>
          <p style={{ color: 'rgba(251,247,238,0.7)', fontSize: 14, maxWidth: 680 }}>
            {t('home.tip_body')} <code style={{ fontFamily: 'var(--font-mono)' }}>&lt;document&gt;...&lt;/document&gt;</code> {window.LANG === 'en' ? 'and' : 've'} <code style={{ fontFamily: 'var(--font-mono)' }}>&lt;example&gt;...&lt;/example&gt;</code> {t('home.tip_body_2')}
          </p>
        </div>
        <button className="btn" style={{ background: 'var(--sun)', color: 'var(--ink)' }} onClick={() => { setModule(2); setPage('module'); }}>
          <Icon name="sparkle" size={14} /> {t('home.tip_btn')}
        </button>
      </div>

      {/* Anthropic'ten son 2 haber */}
      {latestNews && latestNews.length > 0 && (
        <div style={{ marginTop: 48 }}>
          <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
            <div>
              <div className="kicker" style={{ marginBottom: 6 }}>
                {window.LANG === 'en' ? 'CLAUDE NEWS' : 'CLAUDE HABERLERİ'}
              </div>
              <h2 className="section-title" style={{ margin: 0 }}>
                {window.LANG === 'en' ? "What's new at Anthropic" : "Anthropic'ten yenilikler"}
              </h2>
            </div>
            <button
              onClick={() => setPage('news')}
              className="btn btn-ghost btn-sm"
              style={{ fontSize: 13 }}
            >
              {window.LANG === 'en' ? 'See all' : 'Hepsini gör'} <Icon name="arrow" size={13} />
            </button>
          </div>
          <div className="news-grid news-grid--home">
            {latestNews.map(item => {
              const title = item.title_tr || item.title_en;
              const summary = item.summary_tr || item.summary_en;
              const open = () => { if (setNewsSlug) setNewsSlug(item.slug); setPage('news_article'); };
              return (
                <article key={item.id} className="news-card">
                  {item.image_url && (
                    <button type="button" onClick={open} className="news-card__cover" aria-label={title}>
                      <img src={item.image_url} alt="" loading="lazy" />
                    </button>
                  )}
                  <div className="news-card__body">
                    <div className="news-card__meta">
                      <span>Anthropic</span>
                      {item.published_at && <><span>·</span><span>{fmtNewsDate(item.published_at)}</span></>}
                      {item.title_tr && <><span>·</span><span style={{ color: 'var(--moss-deep)', fontWeight: 600 }}>TR</span></>}
                    </div>
                    <h3 className="news-card__title">
                      <button type="button" onClick={open} className="news-card__titlebtn">{title}</button>
                    </h3>
                    {summary && <p className="news-card__summary">{summary}</p>}
                  </div>
                </article>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

window.HomePage = HomePage;
