// app/screens-today.jsx — Today (home). Shared via window.
const { useState: useStateT, useEffect: useEffectT, useMemo: useMemoT } = React;

function greeting() {
  const h = new Date().getHours();
  if (h < 12) return 'Good morning';
  if (h < 18) return 'Good afternoon';
  return 'Good evening';
}

const ENCOURAGE = [
  'Hold to the rod. One day at a time.',
  'Feast upon the words of Christ.',
  'Small and simple things — every single day.',
  'A steady pace finishes the race.',
  'Your daily portion is waiting.',
];

// Hero "today" block — deep navy plate with gilt accents.
function TodayHero({ t, accent, font, day, dayNumber, totalDays, pct, onRead, onListen, done }) {
  return (
    <div style={{
      background: t.hero, borderRadius: 26, padding: '22px 22px 20px', position: 'relative', overflow: 'hidden',
      boxShadow: t.dark ? '0 10px 30px rgba(0,0,0,0.35)' : '0 14px 34px rgba(22,36,63,0.22)',
    }}>
      {/* faint engraved rule frame */}
      <div style={{ position: 'absolute', inset: 10, border: `1px solid ${accent.base}`, opacity: 0.22, borderRadius: 18, pointerEvents: 'none' }} />
      <div style={{ position: 'relative' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 700, color: accent.base }}>
            Day {dayNumber} <span style={{ color: t.heroSub }}>of {totalDays}</span>
          </span>
          {done
            ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 700, color: accent.base, letterSpacing: '0.04em' }}><Icon name="check" size={15} stroke={2.4} /> COMPLETE</span>
            : <span style={{ fontSize: 11.5, fontWeight: 600, color: t.heroSub }}>{day.verses} verses · ~{Math.max(6, Math.round(day.verses * 0.32))} min</span>}
        </div>

        <div style={{ marginTop: 16, fontFamily: font, fontSize: 38, lineHeight: 1.04, color: t.heroInk, fontWeight: 600, letterSpacing: '-0.01em' }}>
          {day.ref}
        </div>
        <div style={{ marginTop: 7, fontSize: 13.5, color: t.heroSub, fontWeight: 500 }}>
          {day.chapters} {day.chapters === 1 ? 'chapter' : 'chapters'} · today’s portion
        </div>

        {/* through-the-year progress */}
        <div style={{ marginTop: 18 }}>
          <div style={{ height: 7, borderRadius: 999, background: 'rgba(255,255,255,0.13)', overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${Math.max(2, pct)}%`, borderRadius: 999, background: `linear-gradient(90deg, ${accent.base}, ${accent.base})`, boxShadow: `0 0 10px ${accent.soft}` }} />
          </div>
          <div style={{ marginTop: 7, display: 'flex', justifyContent: 'space-between', fontSize: 11, color: t.heroSub, fontWeight: 600, letterSpacing: '0.03em' }}>
            <span>{pct}% through the Book of Mormon</span>
            <span>Dec 31</span>
          </div>
        </div>

        {/* actions */}
        <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
          <button onClick={onRead} className="bom-press" style={{
            flex: 1, height: 50, borderRadius: 14, border: 'none', cursor: 'pointer',
            background: accent.base, color: accent.ink, fontWeight: 700, fontSize: 15.5,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            fontFamily: 'inherit', letterSpacing: '0.01em',
          }}>
            <Icon name="book" size={19} stroke={2} /> {done ? 'Read again' : 'Begin reading'}
          </button>
          <button onClick={onListen} className="bom-press" aria-label="Listen" style={{
            width: 50, height: 50, borderRadius: 14, cursor: 'pointer',
            background: 'rgba(255,255,255,0.10)', border: `1px solid ${accent.base}`, color: t.heroInk,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="headphones" size={21} />
          </button>
        </div>
      </div>
    </div>
  );
}

function VerseOfDay({ t, accent, font, verse }) {
  return (
    <Card t={t} style={{ position: 'relative', overflow: 'hidden', background: t.surface2 }}>
      <div style={{ position: 'absolute', top: -8, left: 12, color: accent.base, opacity: 0.20 }}>
        <Icon name="quote" size={54} stroke={1.4} />
      </div>
      <div style={{ position: 'relative' }}>
        <Label t={t} style={{ color: accent.base }}>Verse of the day</Label>
        <div style={{ marginTop: 10, fontFamily: font, fontSize: 19, lineHeight: 1.42, color: t.ink, fontWeight: 500 }}>
          “{verse.text}”
        </div>
        <div style={{ marginTop: 11, fontSize: 12.5, fontWeight: 700, color: t.ink2, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
          {verse.ref}
        </div>
      </div>
    </Card>
  );
}

// 7-day streak strip
function WeekStrip({ t, accent, plan, completed, todayDate }) {
  const tIdx = plan.days.findIndex(d => d.date === todayDate);
  const base = tIdx < 0 ? plan.days.length - 1 : tIdx;
  const start = Math.max(0, Math.min(base - 3, plan.days.length - 7));
  const week = plan.days.slice(start, start + 7);
  const dow = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
  return (
    <Card t={t}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
        <Label t={t}>This week</Label>
        <span style={{ fontSize: 12, color: t.ink2, fontWeight: 600 }}>{week.filter(d => completed[d.date]).length}/7 days</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        {week.map((d) => {
          const isToday = d.date === todayDate;
          const isDone = completed[d.date];
          const isPast = d.date < todayDate;
          const state = isDone ? (isToday ? 'today-read' : 'read') : isToday ? 'today-pending' : isPast ? 'miss' : 'future';
          const dd = window.parseYMD(d.date);
          return (
            <div key={d.date} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7 }}>
              <span style={{ fontSize: 10.5, fontWeight: 700, color: isToday ? accent.base : t.ink3, letterSpacing: '0.04em' }}>{dow[dd.getDay()]}</span>
              <DayDot size={30} state={state} accent={accent} t={t} />
              <span style={{ fontSize: 10.5, fontWeight: 600, color: isToday ? t.ink : t.ink3 }}>{dd.getDate()}</span>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

function TodayScreen({ t, accent, font, plan, completed, stats, onRead, onListen, encourageIdx }) {
  const todayDate = window.ymd(window.today());
  let dayIdx = plan.days.findIndex(d => d.date === todayDate);
  if (dayIdx < 0) dayIdx = Math.min(stats.done, plan.days.length - 1); // before plan starts → first unread
  const day = plan.days[dayIdx] || plan.days[0];
  const done = !!completed[day.date];
  const verse = window.VERSES_OF_DAY[dayIdx % window.VERSES_OF_DAY.length];

  return (
    <ScrollArea style={{ padding: '54px 18px 120px' }}>
      {/* header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', padding: '0 2px 16px' }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, color: t.ink3, fontWeight: 600 }}>{greeting()}</div>
          <div style={{ fontFamily: font, fontSize: 23, color: t.ink, fontWeight: 600, marginTop: 2, whiteSpace: 'nowrap' }}>{window.fmtLong(window.today())}</div>
        </div>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: t.sunken, borderRadius: 999, padding: '7px 13px', marginTop: 4 }}>
          <span style={{ color: accent.base, display: 'flex' }}><Icon name="flame" size={18} stroke={2} /></span>
          <span style={{ fontSize: 15, fontWeight: 800, color: t.ink, fontVariantNumeric: 'tabular-nums' }}>{stats.streak}</span>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <TodayHero t={t} accent={accent} font={font} day={day} dayNumber={dayIdx + 1} totalDays={plan.days.length} pct={stats.pct} onRead={() => onRead(dayIdx)} onListen={() => onListen(dayIdx)} done={done} />
        <VerseOfDay t={t} accent={accent} font={font} verse={verse} />
        <WeekStrip t={t} accent={accent} plan={plan} completed={completed} todayDate={todayDate} />
        <div style={{ textAlign: 'center', padding: '6px 20px 0', fontSize: 13.5, color: t.ink3, fontStyle: 'italic', fontFamily: font }}>
          {ENCOURAGE[encourageIdx % ENCOURAGE.length]}
        </div>
      </div>
    </ScrollArea>
  );
}

Object.assign(window, { TodayScreen });
