// app/screens-plan.jsx — full reading plan, grouped by month. Shared via window.
const { useState: useStateP, useMemo: useMemoP, useEffect: useEffectP, useRef: useRefP } = React;

const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
const DOW = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];

// A single day row: swipe sideways to toggle complete, tap to open the reading.
function SwipeDayRow({ t, accent, font, d, i, isToday, isDone, state, todayRef, onOpen, onToggle }) {
  const [dx, setDx] = useStateP(0);
  const dxRef = useRefP(0); dxRef.current = dx;
  const g = useRefP(null);
  const THRESH = 66, MAX = 92;
  const dt = window.parseYMD(d.date);

  function down(e) { g.current = { x: e.clientX, y: e.clientY, decided: null }; }
  function move(e) {
    const s = g.current; if (!s) return;
    const ddx = e.clientX - s.x, ddy = e.clientY - s.y;
    if (!s.decided) {
      if (Math.abs(ddx) > 8 && Math.abs(ddx) > Math.abs(ddy)) s.decided = 'h';
      else if (Math.abs(ddy) > 8) s.decided = 'v';
    }
    if (s.decided === 'h') {
      let v = ddx;
      if (v > 0) v = Math.min(MAX, v); else v = Math.max(-MAX, v);
      // gentle resistance past threshold
      setDx(v);
    }
  }
  function up() {
    const s = g.current; g.current = null; if (!s) return;
    if (s.decided === 'h') { if (Math.abs(dxRef.current) >= THRESH) onToggle(d.date); setDx(0); }
    else if (!s.decided) onOpen(d.idx);
  }
  function cancel() { g.current = null; setDx(0); }

  const armed = Math.abs(dx) >= THRESH;
  const revealRight = dx > 0; // sliding right reveals action on the left edge
  const actionLabel = isDone ? 'Undo' : 'Complete';

  return (
    <div style={{ position: 'relative', borderTop: i ? `1px solid ${t.hairline}` : 'none', overflow: 'hidden' }}>
      {/* action layer behind */}
      <div style={{ position: 'absolute', inset: 0, background: isDone ? t.sunken : accent.base,
        display: 'flex', alignItems: 'center', justifyContent: revealRight ? 'flex-start' : 'flex-end',
        padding: '0 22px', color: isDone ? t.ink2 : accent.ink }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, transform: `scale(${armed ? 1 : 0.82})`, opacity: Math.min(1, Math.abs(dx) / THRESH), transition: 'transform 0.12s' }}>
          <Icon name={isDone ? 'close' : 'check'} size={20} stroke={2.4} />
          <span style={{ fontSize: 13.5, fontWeight: 800, letterSpacing: '0.02em' }}>{actionLabel}</span>
        </div>
      </div>
      {/* foreground row */}
      <div ref={isToday ? todayRef : null}
        onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={cancel} onPointerLeave={(e) => { if (g.current && g.current.decided === 'h') { up(); } }}
        style={{ position: 'relative', zIndex: 1, display: 'flex', alignItems: 'center', gap: 13, padding: '12px 14px',
          cursor: 'pointer', background: t.surface, touchAction: 'pan-y',
          transform: `translateX(${dx}px)`, transition: g.current ? 'none' : 'transform 0.22s cubic-bezier(.3,.7,.4,1)' }}>
        {/* today tint (kept opaque-enough; rides with the row) */}
        {isToday && <div style={{ position: 'absolute', inset: 0, background: accent.soft, pointerEvents: 'none' }} />}
        {/* date badge */}
        <div style={{ position: 'relative', width: 38, textAlign: 'center', flexShrink: 0 }}>
          <div style={{ fontSize: 10, color: isToday ? accent.base : t.ink3, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{DOW[dt.getDay()]}</div>
          <div style={{ fontFamily: font, fontSize: 20, color: isToday ? accent.base : t.ink, fontWeight: 700, lineHeight: 1.1 }}>{dt.getDate()}</div>
        </div>
        <div style={{ position: 'relative', width: 1, alignSelf: 'stretch', background: t.hairline, margin: '2px 0' }} />
        {/* ref */}
        <div style={{ position: 'relative', flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: font, fontSize: 16.5, color: t.ink, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.ref}</div>
          <div style={{ fontSize: 12, color: t.ink3, fontWeight: 500, marginTop: 1 }}>
            {d.rest ? 'Rest day' : `${d.verses} verses · ${d.chapters} ${d.chapters === 1 ? 'ch' : 'chs'}`}
          </div>
        </div>
        {/* status dot */}
        <div style={{ position: 'relative', flexShrink: 0, display: 'flex' }}>
          <DayDot size={26} state={state} accent={accent} t={t} />
        </div>
      </div>
    </div>
  );
}

function PlanScreen({ t, accent, font, plan, completed, stats, onOpen, onToggle }) {
  const todayDate = window.ymd(window.today());
  const todayRef = useRefP(null);
  const scrollRef = useRefP(null);

  // group days by year-month
  const groups = useMemoP(() => {
    const m = [];
    let cur = null;
    plan.days.forEach((d, idx) => {
      const dt = window.parseYMD(d.date);
      const key = `${dt.getFullYear()}-${dt.getMonth()}`;
      if (!cur || cur.key !== key) { cur = { key, label: MONTHS[dt.getMonth()], year: dt.getFullYear(), days: [] }; m.push(cur); }
      cur.days.push({ ...d, idx });
    });
    return m;
  }, [plan]);

  // jump to today's month on first render
  useEffectP(() => {
    const id = setTimeout(() => {
      if (todayRef.current && scrollRef.current) {
        scrollRef.current.scrollTo({ top: Math.max(0, todayRef.current.offsetTop - 120), behavior: 'auto' });
      }
    }, 80);
    return () => clearTimeout(id);
  }, []);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* header */}
      <div style={{ padding: '52px 20px 14px', background: t.bg, borderBottom: `1px solid ${t.hairline}` }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
          <div>
            <div style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: accent.base, fontWeight: 700 }}>The plan</div>
            <div style={{ fontFamily: font, fontSize: 26, color: t.ink, fontWeight: 600, marginTop: 2 }}>{plan.days.length} days to finish</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontFamily: font, fontSize: 26, color: accent.base, fontWeight: 700, lineHeight: 1 }}>{stats.pct}%</div>
            <div style={{ fontSize: 11, color: t.ink3, fontWeight: 600, marginTop: 2 }}>{stats.done}/{stats.total}</div>
          </div>
        </div>
        <div style={{ marginTop: 12 }}>
          <Bar pct={stats.pct} color={accent.base} track={t.sunken} height={6} />
        </div>
        <div style={{ marginTop: 9, fontSize: 11.5, color: t.ink3, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6 }}>
          <Icon name="check-circle" size={14} stroke={1.9} style={{ color: accent.base }} />
          Swipe a day to mark complete · tap to read
        </div>
      </div>

      <div ref={scrollRef} className="bom-scroll" style={{ flex: 1, overflowY: 'auto', padding: '6px 16px 120px' }}>
        {groups.map(g => {
          const monthDone = g.days.filter(d => completed[d.date]).length;
          return (
            <div key={g.key} style={{ marginTop: 18 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', padding: '0 6px 10px' }}>
                <span style={{ fontFamily: font, fontSize: 19, color: t.ink, fontWeight: 600 }}>{g.label} <span style={{ color: t.ink3, fontSize: 14 }}>{g.year}</span></span>
                <span style={{ fontSize: 11.5, color: t.ink3, fontWeight: 600 }}>{monthDone}/{g.days.length}</span>
              </div>
              <div style={{ background: t.surface, borderRadius: 18, border: `1px solid ${t.line}`, overflow: 'hidden' }}>
                {g.days.map((d, i) => {
                  const isToday = d.date === todayDate;
                  const isDone = completed[d.date];
                  const isPast = d.date < todayDate;
                  const state = isDone ? 'read' : isToday ? 'today-pending' : isPast ? 'miss' : 'future';
                  return (
                    <SwipeDayRow key={d.date} t={t} accent={accent} font={font} d={d} i={i}
                      isToday={isToday} isDone={isDone} state={state}
                      todayRef={isToday ? todayRef : null} onOpen={onOpen} onToggle={onToggle} />
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { PlanScreen });
