// Frontend — Home page.
//
// The home page is itself a channel (type='home', id='ch-home'). When that
// channel has an admin-authored block list, we render it via BlockRenderer
// so edits in Admin → Skin/Channel Management take effect instantly. If the
// channel is missing or empty, we fall back to the legacy hardcoded hero
// so the site never blanks out during migrations.

const FrontHome = ({ lang, theme, goTo, signedIn, onSignUp }) => {
  const T = k => t(k, lang);
  const [homeChannel, setHomeChannel] = React.useState(null);
  const [allChannels, setAllChannels] = React.useState([]);
  const [courses, setCourses] = React.useState([]);
  const [cats, setCats] = React.useState([]);
  const [loaded, setLoaded] = React.useState(false);

  React.useEffect(() => {
    let cancel = false;
    const q = '?locale=' + encodeURIComponent(lang || 'en');
    Promise.all([
      fetch('/api/channels' + q,   { credentials: 'same-origin' }).then(r => r.ok ? r.json() : { channels: [] }),
      fetch('/api/courses' + q,    { credentials: 'same-origin' }).then(r => r.ok ? r.json() : { courses: [] }),
      fetch('/api/categories' + q, { credentials: 'same-origin' }).then(r => r.ok ? r.json() : { categories: [] }),
    ]).then(([cj, crj, caj]) => {
      if (cancel) return;
      const chs = (cj && cj.channels) || [];
      setAllChannels(chs);
      setHomeChannel(chs.find(c => c.type === 'home' || c.id === 'ch-home' || c.slug === 'home') || null);
      setCourses((crj && crj.courses) || []);
      setCats((caj && caj.categories) || []);
      setLoaded(true);
    }).catch(() => { if (!cancel) setLoaded(true); });
    return () => { cancel = true; };
  }, []);

  const blocks = homeChannel && homeChannel.templateOverrides
    && Array.isArray(homeChannel.templateOverrides.blocks)
    ? homeChannel.templateOverrides.blocks : [];

  // While we're still loading the home channel, show ONLY the nav so the
  // first-screen area doesn't flash the legacy hero and then swap to a
  // different block-authored hero once data arrives. Home almost always has
  // blocks, so blanking the hero area for ~100ms is far less jarring than
  // rendering one hero and replacing it with another.
  if (!loaded) {
    return (
      <div className="fade-in">
        <PrimaryNav lang={lang} goTo={goTo} signedIn={signedIn} onSignUp={onSignUp} />
        <div style={{ minHeight: '60vh' }} />
      </div>
    );
  }

  // If the home channel has admin-authored blocks, render them. Otherwise
  // fall through to the legacy built-in layout below.
  if (blocks.length > 0 && typeof BlockRenderer !== 'undefined') {
    return (
      <div className="fade-in">
        <PrimaryNav lang={lang} goTo={goTo} signedIn={signedIn} onSignUp={onSignUp} />
        <BlockRenderer blocks={blocks} lang={lang} goTo={goTo}
                       courses={courses} cats={cats} channels={allChannels} />
        <FooterBar lang={lang} />
      </div>
    );
  }

  return (
    <div className="fade-in">

      {/* Primary nav */}
      <PrimaryNav lang={lang} goTo={goTo} signedIn={signedIn} onSignUp={onSignUp} />

      {/* Hero */}
      <section style={{
        maxWidth: 1240, margin:'0 auto', padding:'72px 32px 56px',
        display:'grid', gridTemplateColumns:'0.85fr 1.15fr', gap: 56,
        alignItems:'center',
      }} className="hero-grid">
        <div>
          <div style={{
            display:'inline-flex', alignItems:'center', gap: 8,
            padding:'5px 12px', borderRadius: 999,
            background:'var(--accent-soft)', color:'var(--accent)',
            fontSize: 12, letterSpacing:'0.08em', textTransform:'uppercase',
            marginBottom: 24, fontWeight: 500,
          }}>
            <span style={{ width:6, height:6, borderRadius:'50%', background:'var(--accent)'}} />
            {T('hero.tag')}
          </div>
          <h1 style={{
            fontFamily:'var(--font-serif)', fontSize:'clamp(38px, 5.5vw, 68px)',
            fontWeight:600, lineHeight: 1.05, letterSpacing:'-0.015em',
            margin:'0 0 20px', color:'var(--ink)', whiteSpace:'pre-line',
          }}>
            {T('hero.title')}
          </h1>
          <p style={{
            fontSize: 17, lineHeight: 1.55, color:'var(--ink-2)',
            maxWidth: 520, margin:'0 0 32px',
          }}>
            {T('hero.sub')}
          </p>
          <div style={{ display:'flex', gap: 12, flexWrap:'wrap' }}>
            <button className="btn btn-accent" onClick={() => goTo('pricing')}>
              {T('hero.cta')} <Icon name="arrowR" size={16} />
            </button>
            <button className="btn btn-ghost" onClick={() => goTo('channel')}>
              {T('hero.cta2')}
            </button>
          </div>

          {/* Social proof */}
          <div style={{ marginTop: 48, display:'flex', gap: 32, flexWrap:'wrap' }}>
            {[
              { v: T('home.proof1Num'), l: T('home.proof1Lbl') },
              { v: T('home.proof2Num'), l: T('home.proof2Lbl') },
              { v: T('home.proof3Num'), l: T('home.proof3Lbl') },
            ].map((s,i) => (
              <div key={i}>
                <div style={{ fontFamily:'var(--font-serif)', fontSize: 26, fontWeight:700, color:'var(--ink)' }}>{s.v}</div>
                <div style={{ fontSize: 12, color:'var(--ink-3)', marginTop:2 }}>{s.l}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Hero visual — big-image carousel of flagship courses */}
        <div style={{ position:'relative', minHeight: 560 }}>
          {typeof ChannelCoverCarousel !== 'undefined' ? (
            <ChannelCoverCarousel
              courses={(COURSES || []).slice(0, 6).map(c => {
                const ch = (CHANNELS || []).find(x => x.id === c.channel);
                return Object.assign({}, c, {
                  channelName: ch ? (t('ch.'+ch.id, lang) !== 'ch.'+ch.id ? t('ch.'+ch.id, lang) : ch.name) : ((c.instructor||{}).name || '')
                });
              })}
              tint={'#8B5A3C'}
              lang={lang}
            />
          ) : (
            <HeroStack goTo={goTo} lang={lang} />
          )}
        </div>
      </section>

      {/* Channels */}
      <section style={{ maxWidth: 1240, margin:'0 auto', padding:'40px 32px 32px' }}>
        <SectionHead
          title={T('home.channelsTitle')}
          sub={T('home.channelsSub')}
        />
        <div style={{
          display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(220px, 1fr))',
          gap: 16,
        }}>
          {CHANNELS.map(c => (
            <button key={c.id} onClick={() => goTo('channel', { channel: c.id })}
              className="card"
              style={{
                padding: 24, textAlign:'left', cursor:'pointer',
                display:'flex', flexDirection:'column', gap: 14,
                transition:'all 0.2s', minHeight: 190, position:'relative', overflow:'hidden',
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = c.color; e.currentTarget.style.transform = 'translateY(-3px)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.transform = 'none'; }}
            >
              <div style={{
                width: 40, height: 40, borderRadius: 8,
                background: c.color, color:'#fff',
                display:'flex', alignItems:'center', justifyContent:'center',
              }}>
                <Icon name={c.icon} size={20} />
              </div>
              <div>
                <div style={{ fontFamily:'var(--font-serif)', fontSize: 20, fontWeight: 600, color:'var(--ink)' }}>{c.name}</div>
                <div style={{ fontSize: 12, color:'var(--ink-3)', marginTop: 2, letterSpacing:'0.05em', textTransform:'uppercase' }}>{t('ch.'+c.id+'.tag', lang) !== 'ch.'+c.id+'.tag' ? t('ch.'+c.id+'.tag', lang) : c.tag}</div>
              </div>
              <div style={{ fontSize: 13, color:'var(--ink-2)', lineHeight:1.5, flex: 1 }}>{t('ch.'+c.id+'.tagline', lang) !== 'ch.'+c.id+'.tagline' ? t('ch.'+c.id+'.tagline', lang) : c.tagline}</div>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop: 'auto', paddingTop: 6 }}>
                <span style={{ fontSize: 12, color:'var(--ink-3)' }}>{c.courseCount} {T('home.coursesTag')}</span>
                <Icon name="arrowR" size={14} style={{ color:'var(--ink-2)'}}/>
              </div>
            </button>
          ))}
        </div>
      </section>

      {/* Featured flagship courses — horizontal carousel so the legacy
           homepage matches the channel pages' recommended strip one-to-one. */}
      <section style={{ maxWidth: 1240, margin:'0 auto', padding:'56px 32px 40px' }}>
        <SectionHead
          title={T('home.newTitle')}
          sub={T('home.newSub')}
          action={<button className="btn btn-ghost btn-sm" onClick={() => goTo('channel')}>
            {T('home.seeAll')} <Icon name="arrowR" size={14} />
          </button>}
        />
        {typeof FeaturedCarousel !== 'undefined' ? (
          <FeaturedCarousel courses={COURSES} goTo={goTo} lang={lang} />
        ) : (
          <div style={{
            display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(280px, 1fr))', gap: 20,
          }}>
            {COURSES.map(c => (
              <CourseCard key={c.id} course={c} onClick={() => goTo('course', { course: c.id })} />
            ))}
          </div>
        )}
      </section>

      {/* Why YYLearn — split */}
      <section style={{
        maxWidth: 1240, margin:'0 auto', padding:'56px 32px',
        display:'grid', gridTemplateColumns:'1fr 1fr', gap: 48,
      }} className="why-grid">
        <div>
          <div style={{
            fontSize: 12, letterSpacing:'0.1em', textTransform:'uppercase',
            color:'var(--ink-3)', marginBottom: 16,
          }}>{T('home.whyTag')}</div>
          <h2 style={{
            fontFamily:'var(--font-serif)', fontSize: 42, fontWeight:600,
            margin:'0 0 20px', lineHeight:1.15, color:'var(--ink)',
            letterSpacing:'-0.01em',
          }}>
            {T('home.whyTitle')}
          </h2>
          <p style={{ fontSize: 16, color:'var(--ink-2)', lineHeight:1.6, maxWidth: 460 }}>
            {T('home.whyBody')}
          </p>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap: 14 }}>
          {[
            { tt: T('home.why1Title'), d: T('home.why1Body') },
            { tt: T('home.why2Title'), d: T('home.why2Body') },
            { tt: T('home.why3Title'), d: T('home.why3Body') },
            { tt: T('home.why4Title'), d: T('home.why4Body') },
          ].map((f,i) => (
            <div key={i} className="card" style={{ padding: 20, display:'flex', gap: 16 }}>
              <div style={{
                width: 36, height: 36, borderRadius:'50%', flexShrink:0,
                background:'var(--accent-soft)', color:'var(--accent)',
                display:'flex', alignItems:'center', justifyContent:'center',
                fontFamily:'var(--font-serif)', fontSize: 18, fontWeight: 700,
              }}>{i+1}</div>
              <div>
                <div style={{ fontFamily:'var(--font-serif)', fontSize: 17, fontWeight: 600, color:'var(--ink)', marginBottom: 4 }}>{f.tt}</div>
                <div style={{ fontSize: 14, color:'var(--ink-3)', lineHeight:1.5 }}>{f.d}</div>
              </div>
            </div>
          ))}
        </div>
      </section>

      <FooterBar lang={lang} />

      <style>{`
        @media (max-width: 900px) {
          .hero-grid, .why-grid { grid-template-columns: 1fr !important; }
          .hero-grid > div:last-child { display: none; }
        }
      `}</style>
    </div>
  );
};

const HeroStack = ({ goTo, lang }) => (
  <div style={{ position:'relative', width:'100%', height:'100%' }}>
    {[COURSES[0], COURSES[2], COURSES[4]].map((c, i) => {
      const positions = [
        { top: 0,   left: 40,  rot: -4, z: 3, w: 260 },
        { top: 110, left: 180, rot: 3,  z: 2, w: 240 },
        { top: 230, left: 20,  rot: -2, z: 1, w: 250 },
      ][i];
      return (
        <div key={c.id} onClick={() => goTo('course', { course: c.id })}
          style={{
            position:'absolute', top: positions.top, left: positions.left,
            width: positions.w, zIndex: positions.z,
            transform: `rotate(${positions.rot}deg)`,
            transition:'transform 0.3s, z-index 0s',
            cursor:'pointer',
          }}
          onMouseEnter={e => { e.currentTarget.style.transform = `rotate(0deg) translateY(-6px) scale(1.03)`; e.currentTarget.style.zIndex = 10; }}
          onMouseLeave={e => { e.currentTarget.style.transform = `rotate(${positions.rot}deg)`; e.currentTarget.style.zIndex = positions.z; }}
        >
          <div className="card" style={{ overflow:'hidden', boxShadow:'0 18px 40px rgba(0,0,0,0.08)'}}>
            <CourseCover course={c} height={140} />
            <div style={{ padding: 14 }}>
              <div style={{ fontFamily:'var(--font-serif)', fontSize: 15, fontWeight: 600, color:'var(--ink)', lineHeight:1.3 }}>
                {c.title}
              </div>
              <div style={{ fontSize: 11, color:'var(--ink-3)', marginTop: 4 }}>
                {c.hours}{t('home.heroHours', lang)} · {c.lessons} {t('home.heroLessons', lang)}
              </div>
            </div>
          </div>
        </div>
      );
    })}
  </div>
);

// PrimaryNav is dynamic: it fetches the channel list from /api/channels and
// renders one button per channel (home excluded — that's the logo). System
// channels with well-known systemKey values shortcut to existing feature
// pages (pricing / user-center); everything else goes to /channel/<slug>.
const PrimaryNav = ({ lang, goTo, signedIn, onSignUp }) => {
  const T = k => t(k, lang);
  const [channels, setChannels] = React.useState([]);
  React.useEffect(() => {
    let cancel = false;
    fetch('/api/channels', { credentials: 'same-origin' })
      .then(r => r.ok ? r.json() : { channels: [] })
      .then(j => { if (!cancel) setChannels((j && j.channels) || []); })
      .catch(() => { if (!cancel) setChannels([]); });
    return () => { cancel = true; };
  }, []);

  function navLabel(ch) {
    const i18n = ch.nameI18n || {};
    return i18n[lang] || i18n[(lang || 'en').split('-')[0]] || i18n.en || ch.name || ch.slug || ch.id;
  }

  function onNavClick(ch) {
    const sys = ch.templateOverrides && ch.templateOverrides.systemKey;
    if (ch.type === 'system' && sys === 'my-learning') return goTo('user');
    if (ch.type === 'system' && sys === 'membership')  return goTo('pricing');
    location.href = '/channel/' + encodeURIComponent(ch.slug || ch.id);
  }

  const visible = channels.filter(c => c.type !== 'home' && c.slug !== 'home');

  // Split the visible list into contiguous groups in first-occurrence order.
  // A blank groupKey is its own bucket (but rendered without a divider).
  const groups = [];
  const byGroup = {};
  visible.forEach(ch => {
    const g = ch.groupKey || '';
    if (!(g in byGroup)) { byGroup[g] = []; groups.push(g); }
    byGroup[g].push(ch);
  });

  return (
    <nav style={{
      display:'flex', alignItems:'center', justifyContent:'space-between',
      padding:'14px 32px', borderBottom:'1px solid var(--line)',
      background:'var(--bg)', gap: 16,
    }}>
      <div style={{ display:'flex', alignItems:'center', gap: 40, minWidth: 0, flex:'1 1 0' }}>
        <button onClick={() => goTo('home')} style={{ flexShrink: 0 }}><Logo /></button>
        <div style={{ display:'flex', gap: 16, fontSize: 14, alignItems:'center' }} className="nav-links">
          {visible.length === 0 ? (
            <>
              <button onClick={() => goTo('channel')} style={{ color:'var(--ink-2)' }}>{T('nav.browse')}</button>
              <button onClick={() => goTo('pricing')} style={{ color:'var(--ink-2)' }}>{T('nav.pricing')}</button>
              <button onClick={() => goTo('user')} style={{ color:'var(--ink-2)' }}>{T('nav.mylearning')}</button>
            </>
          ) : groups.map((g, gi) => (
            <React.Fragment key={g || '__blank__' + gi}>
              {gi > 0 && (
                <span aria-hidden="true" style={{
                  width: 1, height: 16, background:'var(--line)',
                  display:'inline-block', margin:'0 2px', opacity: 0.8, flexShrink: 0,
                }}/>
              )}
              <div style={{ display:'flex', gap: 18, alignItems:'center' }}
                   data-nav-group={g || 'default'}>
                {byGroup[g].map(ch => (
                  <button key={ch.id} onClick={() => onNavClick(ch)}
                    style={{ color:'var(--ink-2)', display:'inline-flex', alignItems:'center', gap: 6 }}>
                    {ch.icon && typeof Icon !== 'undefined' && <Icon name={ch.icon} size={13} />}
                    {navLabel(ch)}
                  </button>
                ))}
              </div>
            </React.Fragment>
          ))}
        </div>
      </div>
      <div className="nav-right" style={{ display:'flex', alignItems:'center', gap: 12 }}>
        {typeof HeaderSearch !== 'undefined' ? (
          <HeaderSearch lang={lang} />
        ) : null}
        {typeof LangThemeMenu !== 'undefined' && (
          <LangThemeMenu signedIn={signedIn} />
        )}
        {signedIn ? (
          <button onClick={() => goTo('user')} style={{ display:'inline-flex', alignItems:'center', gap: 8 }}>
            <Avatar initials={DEMO_USER.avatar} size={32} bg="var(--accent)" color="#fff"/>
          </button>
        ) : (
          <>
            <button className="btn btn-ghost btn-sm" onClick={() => goTo('auth', { authMode:'signin' })}>{T('nav.signin')}</button>
            <button className="btn btn-primary btn-sm" onClick={() => goTo('auth', { authMode:'signup' })}>{T('nav.signup')}</button>
          </>
        )}
      </div>
    </nav>
  );
};

const FooterBar = ({ lang }) => {
  const T = k => t(k, lang);
  const cols = [
    { tt: T('footer.colLearn'),   links: [T('footer.linkAllChannels'), T('footer.linkClassics'), T('footer.linkEmotions'), T('footer.linkAi'), T('footer.linkBusiness'), T('footer.linkWellness')] },
    { tt: T('footer.colCompany'), links: [T('footer.linkAbout'), T('footer.linkTeachers'), T('footer.linkPress'), T('footer.linkCareers'), T('footer.linkContact')] },
    { tt: T('footer.colLegal'),   links: [T('footer.linkTerms'), T('footer.linkPrivacy'), T('footer.linkRefunds'), T('footer.linkCookies')] },
  ];
  return (
    <footer style={{
      marginTop: 80, padding:'48px 32px 32px',
      borderTop:'1px solid var(--line)', background:'var(--bg-alt)',
    }}>
      <div style={{
        maxWidth: 1240, margin:'0 auto',
        display:'grid', gridTemplateColumns:'2fr 1fr 1fr 1fr', gap: 40,
      }}>
        <div>
          <Logo size={20} showTag />
          <p style={{ fontSize: 13, color:'var(--ink-3)', marginTop: 14, maxWidth: 320, lineHeight: 1.6 }}>
            {T('footer.tagline')}
          </p>
        </div>
        {cols.map(col => (
          <div key={col.tt}>
            <div style={{ fontSize: 12, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--ink-3)', marginBottom: 12 }}>{col.tt}</div>
            <div style={{ display:'flex', flexDirection:'column', gap: 8 }}>
              {col.links.map(l => (
                <a key={l} href="#" style={{ fontSize: 13, color:'var(--ink-2)' }}>{l}</a>
              ))}
            </div>
          </div>
        ))}
      </div>
      <div style={{
        maxWidth: 1240, margin:'40px auto 0', paddingTop: 24,
        borderTop:'1px solid var(--line)', fontSize: 12, color:'var(--ink-4)',
        display:'flex', justifyContent:'space-between', flexWrap:'wrap', gap: 12,
      }}>
        <div>{T('footer.copyright')}</div>
        <div className="mono">{T('footer.tag10')}</div>
      </div>
    </footer>
  );
};

Object.assign(window, { FrontHome, PrimaryNav, FooterBar });
