// screen-home.jsx — Today (bilingual, lens-aware, Houston clay direction)
function HomeScreen({ content, events, progress, streak, go, profile, lens, openSettings }) {
  const c = useTheme();
  const U = window.ASFUtil;
  const now = new Date();
  const hr = now.getHours();
  const greet = c.t(hr < 12 ? 'greet_morning' : hr < 17 ? 'greet_afternoon' : 'greet_evening');
  const sub = c.t(lens === 'jy' ? 'sub_jy' : lens === 'youth' ? 'sub_youth' : 'sub_adult');
  const mode = c.dark ? 'dusk' : 'day';
  const serif = "'Spectral', Georgia, serif";

  const upcoming = [...events].map(e => ({ ...e, _d: new Date(e.start) }))
    .filter(e => e._d >= new Date(now.getTime() - 2 * 3600 * 1000))
    .sort((a, b) => a._d - b._d);
  const next = lens === 'jy' ? (upcoming.find(e => e.id === 'e1') || upcoming.find(e => e.type === 'jy') || upcoming[0]) : upcoming[0];

  const prefRuhi = lens === 'adult';
  function jyResume() {
    for (const b of content.jyBooks) {
      if (!b.available) continue;
      const done = progress.reading[b.id] || {};
      const lesson = b.lessons.find(l => !done[l.id]);
      if (lesson) return { kind: 'jy', book: b, lesson };
    }
    return null;
  }
  function ruhiResume() {
    const done = progress.reading.ruhi1 || {};
    const u = content.ruhiBook1.units.find(x => !done[x.id]);
    return u ? { kind: 'ruhi', book: content.ruhiBook1, lesson: u } : null;
  }
  const resume = prefRuhi ? (ruhiResume() || jyResume()) : (jyResume() || ruhiResume());

  const wellspring = content.jyBooks.find(b => b.id === 'wellspring');
  const wellspringQuoteLessons = (wellspring?.lessons || [])
    .filter(l => l.quoteId)
    .map(l => ({ lesson: l, quote: content.quotes.find(q => q.id === l.quoteId) }))
    .filter(x => x.quote);
  const completedWellspring = progress.reading.wellspring || {};
  const completedQuote = [...wellspringQuoteLessons]
    .filter(x => completedWellspring[x.lesson.id])
    .sort((a, b) => (b.lesson.n || 0) - (a.lesson.n || 0))[0];
  const fallbackQuote = [...wellspringQuoteLessons].sort((a, b) => (b.lesson.n || 0) - (a.lesson.n || 0))[0];
  const fq = (completedQuote || fallbackQuote)?.quote || content.quotes.find(q => q.wellspring) || content.quotes[0];
  const memorizeQuotes = content.quotes.filter(q => q.wellspring);
  const mastered = memorizeQuotes.filter(q => (progress.mastery[q.id] || 0) >= 5).length;

  const UpNext = () => (<>
    <SectionLabel>{c.t('up_next')}</SectionLabel>
    {next ? (
      <button onClick={() => go({ name: 'calendar', focus: next.id })} style={asfCardBtn(c)}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
          <div style={{
            width: 50, height: 50, borderRadius: 16, background: c.soft2 || c.accentSoft,
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0, color: c.accent2 || c.accent,
            boxShadow: c.dark ? 'inset 0 1px 0 rgba(255,255,255,0.12)' : 'inset 0 2px 0 rgba(255,255,255,0.6)',
          }}>
            <div style={{ fontFamily: c.headingStack, fontSize: 19, fontWeight: 800, lineHeight: 1 }}>{next._d.getDate()}</div>
            <div style={{ fontSize: 9.5, fontWeight: 800, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{U.day(c.lang, next._d.getDay())}</div>
          </div>
          <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 800, color: c.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.L(next.title)}</div>
            <div style={{ fontSize: 12.5, color: c.textMuted, marginTop: 3, display: 'inline-flex', alignItems: 'center', gap: 5, maxWidth: '100%', whiteSpace: 'nowrap' }}><Icon name="clock" size={13} />{U.dayLabel(next._d, c.lang, now)} · {U.fmtTime(next.start)}</div>
          </div>
          <div style={{ color: c.textMuted, flexShrink: 0 }}><Icon name="right" size={18} /></div>
        </div>
      </button>
    ) : <Empty>{c.t('no_events')}</Empty>}
  </>);

  const KeepGoing = () => resume ? (<>
    <SectionLabel style={{ marginTop: 22 }}>{c.t('keep_going')}</SectionLabel>
    <button onClick={() => go({ name: 'book', kind: resume.kind, bookId: resume.book.id })} style={asfCardBtn(c)}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <BookCover seed={resume.book.id} src={resume.book.coverSrc} label={resume.kind === 'ruhi' ? c.t('book1') : c.L(resume.book.title)} w={54} h={72} />
        <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
          <div style={{ fontSize: 11.5, color: c.accent, fontWeight: 800, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{resume.kind === 'ruhi' ? c.L(content.ruhiBook1.label) : c.L(resume.book.title)}</div>
          <div style={{ fontSize: 15.5, fontWeight: 800, color: c.text, marginTop: 2, lineHeight: 1.2 }}>{resume.kind === 'ruhi' ? `${c.t('unit')} ${resume.lesson.n}: ${c.L(resume.lesson.title)}` : c.L(resume.lesson.title)}</div>
          <div style={{ marginTop: 7, height: 6, borderRadius: 99, background: c.dark ? 'rgba(255,255,255,0.10)' : 'rgba(33,51,26,0.10)', overflow: 'hidden' }}>
            <div style={{ width: '35%', height: '100%', background: c.accent2 || c.accent, borderRadius: 99 }} />
          </div>
          <div style={{ fontSize: 12, color: c.textMuted, marginTop: 5 }}>{c.t('continue_label')} · {resume.lesson.minutes} {c.t('min')}</div>
        </div>
      </div>
    </button>
  </>) : null;

  const Quote = () => (<>
    <SectionLabel style={{ marginTop: 22 }}>{c.t('quote_to_carry')}</SectionLabel>
    <div style={{ ...asfCard(c), padding: 0, overflow: 'hidden' }}>
      <div style={{ padding: '20px 20px 16px', position: 'relative' }}>
        <div style={{ position: 'absolute', top: 12, left: 14, color: c.accentSoft }}><Icon name="quote" size={34} fill /></div>
        <p style={{ position: 'relative', margin: '12px 0 0', fontFamily: serif, fontSize: 21, lineHeight: 1.42, color: c.text, fontWeight: 500 }}>{c.L(fq.text)}</p>
        <div style={{ marginTop: 11, fontSize: 13, color: c.textMuted, fontStyle: 'italic' }}>— {fq.source}</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '13px 18px', borderTop: `1px solid ${c.border}`, background: c.footer || c.surfaceAlt }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0, color: streak.count > 0 ? c.accent : c.textMuted }}>
          <Icon name="flame" size={18} fill={streak.count > 0} />
          <span style={{ fontSize: 14, fontWeight: 800, color: c.text, whiteSpace: 'nowrap' }}>{streak.count} {c.t('streak_day')}</span>
          <span style={{ fontSize: 13, color: c.textMuted, whiteSpace: 'nowrap' }}>· {mastered}/{memorizeQuotes.length || content.quotes.length} {c.t('learned')}</span>
        </div>
        <button onClick={() => go({ name: 'practice', quoteId: fq.id })} style={asfPrimaryBtn(c)}>{c.t('practice')}</button>
      </div>
    </div>
  </>);

  const order = lens === 'jy' ? [Quote, KeepGoing, UpNext] : [UpNext, KeepGoing, Quote];

  return (
    <div style={{ position: 'relative', minHeight: '100%', paddingBottom: 120, background: c.bg }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 250, borderBottomLeftRadius: 30, borderBottomRightRadius: 30, overflow: 'hidden' }}>
        <Landscape mode={mode} />
      </div>

      <div style={{ position: 'relative', padding: '58px 18px 0' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, padding: '0 4px' }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: '0.12em', textTransform: 'uppercase', color: c.accent }}>Ashford · Santa Fe</div>
            <h1 style={{ margin: '7px 0 0', fontFamily: c.headingStack, fontWeight: 800, fontSize: 30, lineHeight: 1.05, letterSpacing: 0, color: c.skyInk || c.text }}>{greet},<br />{profile.name || 'Ashford'}.</h1>
            <div style={{ marginTop: 7, fontSize: 13.5, color: c.skyInk || c.text, opacity: 0.72 }}>{sub}</div>
          </div>
          <button onClick={openSettings} aria-label={c.t('settings')} style={{
            border: 'none', cursor: 'pointer', width: 46, height: 46, borderRadius: 17,
            background: c.dark ? 'linear-gradient(180deg,#2C3759,#1E2742)' : 'linear-gradient(180deg,#FFFFFF,#F4EFE4)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: c.accent,
            fontFamily: c.headingStack, fontWeight: 800, fontSize: 18, flexShrink: 0,
            boxShadow: c.dark ? '0 8px 16px rgba(0,0,0,0.4), inset 0 1px 0 rgba(255,255,255,0.12)' : '0 8px 16px rgba(40,50,20,0.18), inset 0 2px 0 rgba(255,255,255,0.9)',
          }}>{profile.initial}</button>
        </div>

        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 7, marginTop: 12,
          padding: '7px 14px', borderRadius: 999, background: c.chip || c.surface,
          backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
          fontSize: 13, fontWeight: 700, color: c.skyInk || c.text,
          boxShadow: c.dark ? '0 5px 12px rgba(0,0,0,0.3), inset 0 1px 0 rgba(255,255,255,0.18)' : '0 5px 12px rgba(40,50,20,0.14), inset 0 1px 0 rgba(255,255,255,0.8)',
        }}>
          <Icon name="cal" size={14} />
          <span>{(s => s.charAt(0).toUpperCase() + s.slice(1))(U.gregFull(now, c.lang))}</span>
        </div>

        <div style={{ marginTop: 64, display: 'flex', flexDirection: 'column', gap: 0 }}>
          {order.map((Block, i) => <Block key={i} />)}
        </div>
      </div>
    </div>
  );
}

function SectionLabel({ children, style }) {
  const c = useTheme();
  return <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: '0.14em', textTransform: 'uppercase', color: c.textMuted, margin: '0 2px 11px', ...style }}>{children}</div>;
}
function Empty({ children }) {
  const c = useTheme();
  return <div style={{ ...asfCard(c), color: c.textMuted, fontSize: 14.5, textAlign: 'center', padding: '22px' }}>{children}</div>;
}
function asfCard(c) {
  return {
    background: c.surface,
    border: c.dark ? `1px solid ${c.border}` : 'none',
    borderRadius: c.cardRadius || 18,
    padding: 16,
    boxShadow: c.cardShadow || (c.dark ? `inset 0 0 0 1px ${c.border}` : `0 2px 10px rgba(44,32,23,0.05), inset 0 0 0 1px ${c.border}`),
  };
}
function asfCardBtn(c) {
  return { ...asfCard(c), width: '100%', border: c.dark ? `1px solid ${c.border}` : 'none', cursor: 'pointer', fontFamily: 'inherit', display: 'block', textAlign: 'left' };
}
function asfPrimaryBtn(c) {
  return {
    border: 'none', cursor: 'pointer', background: c.btn || c.accent, color: c.btnInk || c.accentInk,
    fontFamily: 'inherit', fontWeight: 800, fontSize: 14, padding: '10px 20px', borderRadius: 999,
    boxShadow: c.btnShadow || 'none', flexShrink: 0,
  };
}
Object.assign(window, { HomeScreen, SectionLabel, Empty, asfCard, asfCardBtn, asfPrimaryBtn });
