// ui_kits/website/Podcast.jsx — homepage podcast section
//
// Shows:
//   • Brand intro on the left (eyebrow, headline, body, CTAs)
//   • Latest episode card on the right — real cover art + episode metadata
//   • A horizontal row of 3 "most listened" episodes below
//
// Episode data: prefers live Buzzsprout feed (window.BUZZSPROUT_EPISODES);
// falls back to the curated PODCAST_EPISODES list defined in PodcastPage.jsx.

const SPOTIFY_SHOW = 'https://open.spotify.com/show/6RQBHMo4fI9xEveJQCUhGm';
const APPLE_SHOW   = 'https://podcasts.apple.com/us/podcast/top-natural-tips/id1830300712';

// Episode numbers we hand-pick as the "most listened" trio on the homepage.
// These are evergreen, broad-appeal topics that pull steady weekly downloads.
const POPULAR_EP_NUMBERS = [84, 77, 76];

const podStyles = {
  section: {
    background: 'var(--brand-leaf-deep)', color: '#fff',
    padding: '96px 0 88px', position: 'relative', overflow: 'hidden',
  },
  decor: {
    position: 'absolute', right: -160, top: -160,
    width: 520, height: 520, borderRadius: '50%',
    background: 'radial-gradient(circle, rgba(143,207,174,0.20), transparent 65%)',
    pointerEvents: 'none',
  },
  inner: {
    position: 'relative',
    maxWidth: 1200, margin: '0 auto', padding: '0 32px',
  },
  top: {
    display: 'grid', gridTemplateColumns: '1fr 1.05fr', gap: 56,
    alignItems: 'center',
  },

  // ---- Left intro column ----
  eyebrow: {
    fontFamily: 'var(--font-sans)', fontWeight: 700,
    fontSize: 12, letterSpacing: '0.28em', textTransform: 'uppercase',
    color: 'var(--brand-mint)',
  },
  title: {
    fontFamily: 'var(--font-serif)', fontWeight: 700,
    fontSize: 44, lineHeight: 1.12, letterSpacing: '-0.01em',
    color: '#fff', margin: '14px 0 18px',
    textWrap: 'balance',
  },
  body: {
    fontFamily: 'var(--font-sans)', fontSize: 17, lineHeight: 1.7,
    color: 'rgba(255,255,255,0.86)', margin: 0,
    maxWidth: '46ch',
    textWrap: 'pretty',
  },
  ctaRow: { display: 'flex', gap: 12, marginTop: 28, flexWrap: 'wrap' },
  ctaPrimary: {
    display: 'inline-flex', alignItems: 'center', gap: 10,
    background: 'var(--brand-coral)', color: '#fff',
    border: 'none',
    padding: '14px 22px', borderRadius: 999,
    fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 700,
    letterSpacing: '0.04em',
    cursor: 'pointer', textDecoration: 'none',
  },
  ctaGhost: {
    display: 'inline-flex', alignItems: 'center', gap: 10,
    background: 'transparent', color: '#fff',
    border: '1.5px solid rgba(255,255,255,0.4)',
    padding: '14px 22px', borderRadius: 999,
    fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 700,
    letterSpacing: '0.04em',
    cursor: 'pointer', textDecoration: 'none',
  },

  // ---- Right featured episode card ----
  card: {
    position: 'relative',
    background: 'rgba(255,255,255,0.05)',
    border: '1px solid rgba(255,255,255,0.12)',
    borderRadius: 22,
    padding: 20,
    display: 'grid', gridTemplateColumns: '180px 1fr', gap: 22,
    alignItems: 'center',
    backdropFilter: 'blur(8px)',
    WebkitBackdropFilter: 'blur(8px)',
  },
  coverWrap: {
    position: 'relative',
    width: 180, height: 180, borderRadius: 14, overflow: 'hidden',
    boxShadow: '0 18px 40px rgba(0,0,0,0.35)',
    flexShrink: 0,
  },
  coverImg: { width: '100%', height: '100%', objectFit: 'cover', display: 'block' },
  badge: {
    position: 'absolute', top: 10, left: 10,
    display: 'inline-flex', alignItems: 'center', gap: 6,
    background: 'rgba(0,0,0,0.55)',
    color: '#fff',
    fontFamily: 'var(--font-sans)', fontSize: 9, fontWeight: 700,
    letterSpacing: '0.18em', textTransform: 'uppercase',
    padding: '5px 9px', borderRadius: 999,
    backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
  },
  badgeDot: { width: 5, height: 5, borderRadius: '50%', background: '#FF4D4D' },
  meta: { minWidth: 0 },
  episodeLine: {
    fontFamily: 'var(--font-sans)', fontSize: 10.5, fontWeight: 700,
    letterSpacing: '0.22em', textTransform: 'uppercase',
    color: 'rgba(255,255,255,0.65)',
    marginBottom: 8,
  },
  epTitle: {
    fontFamily: 'var(--font-serif)', fontWeight: 600,
    fontSize: 22, lineHeight: 1.22, letterSpacing: '-0.005em',
    color: '#fff', margin: '0 0 16px',
    textWrap: 'balance',
    display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical', overflow: 'hidden',
  },
  controls: { display: 'flex', alignItems: 'center', gap: 14 },
  playBtn: {
    width: 46, height: 46, borderRadius: '50%',
    background: 'var(--brand-mint)', color: 'var(--brand-leaf-deep)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    cursor: 'pointer', border: 'none',
    flexShrink: 0,
    boxShadow: '0 8px 18px rgba(0,0,0,0.25)',
    transition: 'transform 160ms var(--ease-out)',
  },
  progress: { flex: 1, height: 3, borderRadius: 999, background: 'rgba(255,255,255,0.18)', position: 'relative' },
  progressInner: (pct) => ({
    position: 'absolute', left: 0, top: 0, bottom: 0,
    width: pct + '%', background: 'var(--brand-mint)', borderRadius: 999,
  }),
  time: { fontFamily: 'var(--font-mono)', fontSize: 12, opacity: 0.8, fontVariantNumeric: 'tabular-nums' },

  // ---- Popular row ----
  popularWrap: { marginTop: 56 },
  popularHead: {
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    gap: 16, marginBottom: 22,
  },
  popularEyebrow: {
    fontFamily: 'var(--font-sans)', fontWeight: 700,
    fontSize: 11, letterSpacing: '0.28em', textTransform: 'uppercase',
    color: 'var(--brand-mint)',
    display: 'flex', alignItems: 'center', gap: 14,
  },
  popularRule: { width: 36, height: 1, background: 'rgba(143,207,174,0.5)' },
  viewAllLink: {
    fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
    letterSpacing: '0.04em',
    color: 'rgba(255,255,255,0.78)', textDecoration: 'none',
    display: 'inline-flex', alignItems: 'center', gap: 6,
    cursor: 'pointer',
    background: 'transparent', border: 'none', padding: 0,
  },
  popularGrid: {
    display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14,
  },
  popCard: {
    display: 'grid', gridTemplateColumns: '64px 1fr 32px', gap: 14,
    alignItems: 'center',
    background: 'rgba(255,255,255,0.05)',
    border: '1px solid rgba(255,255,255,0.10)',
    borderRadius: 14, padding: 14,
    textAlign: 'left',
    cursor: 'pointer',
    transition: 'background 200ms var(--ease-out), border-color 200ms var(--ease-out)',
    color: '#fff',
  },
  popCover: {
    width: 64, height: 64, borderRadius: 10, overflow: 'hidden',
    flexShrink: 0,
    background: 'linear-gradient(135deg, #8FCFAE, #2E6F5A)',
    position: 'relative',
  },
  popCoverImg: { width: '100%', height: '100%', objectFit: 'cover', display: 'block' },
  popBody: { minWidth: 0 },
  popEp: {
    fontFamily: 'var(--font-mono)', fontSize: 10.5, fontWeight: 500,
    letterSpacing: '0.16em', textTransform: 'uppercase',
    color: 'rgba(255,255,255,0.55)',
    marginBottom: 4,
  },
  popTitle: {
    fontFamily: 'var(--font-serif)', fontWeight: 600,
    fontSize: 15, lineHeight: 1.3,
    color: '#fff', margin: 0,
    display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
  },
  popPlay: {
    width: 32, height: 32, borderRadius: '50%',
    background: 'rgba(255,255,255,0.08)',
    color: 'var(--brand-mint)',
    border: '1px solid rgba(143,207,174,0.4)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    cursor: 'pointer', flexShrink: 0,
  },
};

function getEpisodes() {
  if (window.BUZZSPROUT_EPISODES && window.BUZZSPROUT_EPISODES.length) {
    return window.BUZZSPROUT_EPISODES;
  }
  if (window.PODCAST_EPISODES && window.PODCAST_EPISODES.length) {
    return window.PODCAST_EPISODES;
  }
  return [];
}

function pickPopular(episodes, featured) {
  if (!episodes || !episodes.length) return [];
  // Try to find the curated set by episode number first
  const byNum = POPULAR_EP_NUMBERS
    .map(n => episodes.find(e => e.n === n))
    .filter(Boolean);
  if (byNum.length === 3) return byNum;
  // Fallback: take the next few episodes after the featured one
  return episodes.filter(e => e !== featured).slice(0, 3);
}

function navigateToPodcastPage(e) {
  if (e) e.preventDefault();
  window.dispatchEvent(new CustomEvent('app:navigate', { detail: { view: 'podcast' } }));
}

function PodcastSection() {
  const tr = useT();
  const lang = React.useContext(LangContext);
  const player = (typeof window.usePodcastPlayer === 'function') ? window.usePodcastPlayer() : null;

  // Subscribe to live feed updates so the section reflects new episodes
  // even if the buzzsprout fetch finishes after this component mounts.
  const [, force] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    const onUpdate = () => force();
    window.addEventListener('buzzsprout-feed-updated', onUpdate);
    return () => window.removeEventListener('buzzsprout-feed-updated', onUpdate);
  }, []);

  const episodes = getEpisodes();
  const featured = episodes[0];
  const popular  = pickPopular(episodes, featured);

  // Featured progress (only meaningful if currently playing)
  const isFeaturedActive = player && featured && player.isActive && player.isActive(featured);
  const isFeaturedPlaying = isFeaturedActive && player.isPlaying;
  const pct = (isFeaturedActive && player.duration > 0)
    ? Math.min(100, (player.currentTime / player.duration) * 100)
    : 0;

  const handleFeaturedPlay = () => {
    if (!featured) { window.open(SPOTIFY_SHOW, '_blank', 'noopener'); return; }
    if (player && featured.audioUrl) {
      player.toggle ? player.toggle(featured) : navigateToPodcastPage();
    } else {
      navigateToPodcastPage();
    }
  };

  const handlePopularPlay = (ep, e) => {
    if (e) e.stopPropagation();
    if (player && ep && ep.audioUrl) {
      player.toggle ? player.toggle(ep) : navigateToPodcastPage();
    } else {
      navigateToPodcastPage();
    }
  };

  const fmtTime = (sec) => {
    if (!sec || !isFinite(sec)) return '0:00';
    const m = Math.floor(sec / 60);
    const s = Math.floor(sec % 60);
    return `${m}:${s.toString().padStart(2, '0')}`;
  };

  const featuredArt = (featured && featured.artworkUrl) || 'podcast-cover.jpg';
  const featuredDuration = featured && featured.durationSec
    ? fmtTime(featured.durationSec)
    : featured ? `${featured.minutes || 0}:00` : '0:00';

  return (
    <section style={podStyles.section}>
      <div style={podStyles.decor}></div>
      <div style={podStyles.inner}>
        <div style={podStyles.top}>
          {/* Left: intro copy */}
          <div>
            <div style={podStyles.eyebrow}>{tr('pod.eyebrow')}</div>
            <h2 style={podStyles.title}>{tr('pod.title')}</h2>
            <p style={podStyles.body}>{tr('pod.body')}</p>
          </div>

          {/* Right: featured (latest) episode */}
          {featured && (
            <div style={podStyles.card}>
              <div style={podStyles.coverWrap}>
                <img src={featuredArt} alt={featured.title} style={podStyles.coverImg}/>
                <span style={podStyles.badge}>
                  <span style={podStyles.badgeDot}></span>
                  {tr('pod.newBadge')}
                </span>
              </div>
              <div style={podStyles.meta}>
                <div style={podStyles.episodeLine}>
                  {tr('pod.episodeLabel')} {featured.n} · {featured.minutes || 0} {tr('pod.minLabel')}
                </div>
                <h3 style={podStyles.epTitle}>{featured.title}</h3>
                <div style={podStyles.controls}>
                  <button
                    style={podStyles.playBtn}
                    onClick={handleFeaturedPlay}
                    aria-label={tr('pod.playEpisode')}
                  >
                    {isFeaturedPlaying
                      ? <PauseIcon size={20}/>
                      : <PlayIcon size={20}/>}
                  </button>
                  <span style={podStyles.time}>
                    {isFeaturedActive ? fmtTime(player.currentTime) : '0:00'}
                  </span>
                  <div style={podStyles.progress}>
                    <div style={podStyles.progressInner(pct)}></div>
                  </div>
                  <span style={podStyles.time}>{featuredDuration}</span>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Most listened row */}
        {popular.length > 0 && (
          <div style={podStyles.popularWrap}>
            <div style={podStyles.popularHead}>
              <div style={podStyles.popularEyebrow}>
                <span style={podStyles.popularRule}></span>
                {tr('pod.popular')}
              </div>
              <button style={podStyles.viewAllLink} onClick={navigateToPodcastPage}>
                {tr('pod.viewAll')} →
              </button>
            </div>
            <div style={podStyles.popularGrid}>
              {popular.map(ep => {
                const art = ep.artworkUrl || 'podcast-cover.jpg';
                const isPlaying = player && player.isActive && player.isActive(ep) && player.isPlaying;
                return (
                  <button
                    key={ep.id || ep.n}
                    style={podStyles.popCard}
                    onClick={() => handlePopularPlay(ep)}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.background = 'rgba(255,255,255,0.09)';
                      e.currentTarget.style.borderColor = 'rgba(143,207,174,0.35)';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.background = 'rgba(255,255,255,0.05)';
                      e.currentTarget.style.borderColor = 'rgba(255,255,255,0.10)';
                    }}
                  >
                    <div style={podStyles.popCover}>
                      <img src={art} alt="" style={podStyles.popCoverImg}/>
                    </div>
                    <div style={podStyles.popBody}>
                      <div style={podStyles.popEp}>
                        {tr('pod.episodeLabel')} {ep.n} · {ep.minutes || 0} {tr('pod.minLabel')}
                      </div>
                      <h4 style={podStyles.popTitle}>{ep.title}</h4>
                    </div>
                    <span style={podStyles.popPlay} aria-label={tr('pod.playEpisode')}>
                      {isPlaying ? <PauseIcon size={14}/> : <PlayIcon size={14}/>}
                    </span>
                  </button>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

window.PodcastSection = PodcastSection;
