const { useState, useEffect } = React;

function timeAgo(date) {
  const d = new Date(date), now = new Date();
  const diff = Math.floor((now - d) / 1000);
  if (diff < 60) return 'just now';
  if (diff < 3600) return Math.floor(diff / 60) + 'm ago';
  if (diff < 86400) return Math.floor(diff / 3600) + 'h ago';
  if (diff < 604800) return Math.floor(diff / 86400) + 'd ago';
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

function HomePage({ config, pages, user, onNavigate, onEdit }) {
  const pinned = (config.pinnedPages || [])
    .map(slug => pages.find(p => p.slug === slug))
    .filter(Boolean);

  const recent = [...pages]
    .filter(p => p.slug !== 'home')
    .sort((a, b) => new Date(b.modified) - new Date(a.modified))
    .slice(0, 8);

  const allTags = [...new Set(pages.flatMap(p => p.tags || []))].sort();

  const groups = [...new Set(pages.map(p => p.slug.split('/')[0]))]
    .filter(g => pages.some(p => p.slug.includes('/') && p.slug.startsWith(g + '/')))
    .sort();

  const worldInitial = (config.worldName || 'W')[0].toUpperCase();
  const isEmpty = pages.filter(p => p.slug !== 'home').length === 0;

  return (
    <div className="homepage">
      {/* Hero */}
      <div className="home-hero">
        <div className="home-hero-text">
          <div className="home-world-label">World Wiki</div>
          <h1 className="home-world-name">
            {config.worldName || (
              <span style={{ color: 'var(--text-muted)', fontStyle: 'italic' }}>
                {user?.role === 'admin' ? 'Set your world name in Settings' : 'My World'}
              </span>
            )}
          </h1>
          {config.tagline && <p className="home-tagline">{config.tagline}</p>}
          <div className="home-hero-actions">
            <button className="btn btn-primary" onClick={() => onNavigate('#/wiki/home')}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
              Browse the Wiki
            </button>
            {user?.role === 'admin' && (
              <button className="btn btn-ghost" onClick={() => onNavigate('#/edit')}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                New page
              </button>
            )}
          </div>
        </div>

        <div style={{ display: 'flex', gap: '12px', flexShrink: 0 }}>
          <div style={{ textAlign: 'center', padding: '16px 24px', background: 'var(--bg)', borderRadius: 'var(--radius-lg)', border: '1px solid var(--border)' }}>
            <div style={{ fontSize: '2rem', fontWeight: 700, color: 'var(--text)', lineHeight: 1 }}>{pages.filter(p => p.slug !== 'home').length}</div>
            <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginTop: 4 }}>Pages</div>
          </div>
          {allTags.length > 0 && (
            <div style={{ textAlign: 'center', padding: '16px 24px', background: 'var(--bg)', borderRadius: 'var(--radius-lg)', border: '1px solid var(--border)' }}>
              <div style={{ fontSize: '2rem', fontWeight: 700, color: 'var(--text)', lineHeight: 1 }}>{allTags.length}</div>
              <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginTop: 4 }}>Tags</div>
            </div>
          )}
        </div>
      </div>

      <div className="home-body">
        {isEmpty && (
          <div className="empty-state" style={{ minHeight: '30vh' }}>
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
            <div className="empty-state-title">Your world is blank</div>
            <div className="empty-state-desc">
              {user?.role === 'admin'
                ? 'Start by creating your first page. Use [[backlinks]] to connect pages together.'
                : 'No pages have been created yet.'}
            </div>
            {user?.role === 'admin' && (
              <button className="btn btn-primary" style={{ marginTop: 8 }} onClick={() => onNavigate('#/edit')}>
                Create first page
              </button>
            )}
          </div>
        )}

        {pinned.length > 0 && (
          <div className="home-section">
            <div className="home-section-header">
              <div className="home-section-title">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ display: 'inline', marginRight: 7, verticalAlign: 'middle' }}><line x1="12" y1="17" x2="12" y2="22"/><path d="M5 17H19V13C19 11 17 9 15 9L13 3H11L9 9C7 9 5 11 5 13Z"/></svg>
                Pinned
              </div>
            </div>
            <div className="page-cards">
              {pinned.map(p => (
                <a key={p.slug} className="page-card" href={'#/wiki/' + p.slug}
                  onClick={e => { e.preventDefault(); onNavigate('#/wiki/' + p.slug); }}>
                  <div className="page-card-title">{p.title}</div>
                  <div className="page-card-meta">{p.slug}</div>
                  {p.tags?.length > 0 && (
                    <div className="page-card-tags">
                      {p.tags.slice(0, 3).map(t => <span key={t} className="tag">{t}</span>)}
                    </div>
                  )}
                </a>
              ))}
            </div>
          </div>
        )}

        {recent.length > 0 && (
          <div className="home-section">
            <div className="home-section-header">
              <div className="home-section-title">Recently updated</div>
            </div>
            <div className="recent-list">
              {recent.map(p => (
                <a key={p.slug} className="recent-item" href={'#/wiki/' + p.slug}
                  onClick={e => { e.preventDefault(); onNavigate('#/wiki/' + p.slug); }}>
                  <div className="recent-item-icon">
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                  </div>
                  <div>
                    <div className="recent-item-title">{p.title}</div>
                    <div className="recent-item-meta">{p.slug}</div>
                  </div>
                  <div className="recent-item-time">{timeAgo(p.modified)}</div>
                </a>
              ))}
            </div>
          </div>
        )}

        {(groups.length > 0 || allTags.length > 0) && (
          <div className="home-section">
            <div className="home-section-header">
              <div className="home-section-title">Browse</div>
            </div>
            {groups.length > 0 && (
              <div style={{ marginBottom: allTags.length > 0 ? 16 : 0 }}>
                <div style={{ fontSize: '12px', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--text-muted)', marginBottom: 10 }}>Sections</div>
                <div className="category-pills">
                  {groups.map(g => (
                    <a key={g} className="category-pill" href={'#/section/' + g}
                      onClick={e => { e.preventDefault(); onNavigate('#/section/' + g); }}>
                      {g.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase())}
                    </a>
                  ))}
                </div>
              </div>
            )}
            {allTags.length > 0 && (
              <div style={{ marginTop: groups.length > 0 ? 20 : 0 }}>
                <div style={{ fontSize: '12px', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--text-muted)', marginBottom: 10 }}>Tags</div>
                <div className="category-pills">
                  {allTags.map(t => (
                    <span key={t} className="category-pill" style={{ cursor: 'default' }}>{t}</span>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { HomePage });
