// screens-cal.jsx — Calendar / Upcoming view (next 30 days)

function CalendarScreen({ store }) {
  const { state, totalIncome } = store;
  const today = new Date(); today.setHours(0,0,0,0);
  const horizon = new Date(today); horizon.setDate(today.getDate() + 30);

  // Build list of upcoming charges in next 30 days (some subs may charge twice)
  const charges = [];
  state.subscriptions.filter(s => s.active).forEach(s => {
    const first = nextBillingDate(s.billingDay, today);
    if (first <= horizon) charges.push({ id: s.id + '-1', name: s.name, amount: s.amount, date: first });
    // possible second charge in window
    const second = nextBillingDate(s.billingDay, new Date(first.getTime() + 86400000));
    if (second <= horizon) charges.push({ id: s.id + '-2', name: s.name, amount: s.amount, date: second });
  });
  charges.sort((a,b) => a.date - b.date);
  const total = charges.reduce((a,b) => a + b.amount, 0);
  const pctOfIncome = totalIncome > 0 ? (total / totalIncome) * 100 : 0;

  // Group by week-of-charge
  const groups = {};
  charges.forEach(c => {
    const days = daysBetween(today, c.date);
    const wk = Math.floor(days / 7);
    if (!groups[wk]) groups[wk] = [];
    groups[wk].push({ ...c, days });
  });

  return (
    <div className="page-in" style={{ paddingBottom: 110 }}>
      <ScreenHeader eyebrow="Next 30 days" title="Calendar"/>

      <div style={{ padding: '4px 18px 14px' }}>
        <Card delay={60}>
          <div style={{
            fontFamily: tokens.sans, fontSize: 12, fontWeight: 500, letterSpacing: 0.6,
            textTransform: 'uppercase', color: tokens.ink3, marginBottom: 4,
          }}>Upcoming charges</div>
          <div style={{
            display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
          }}>
            <div style={{
              fontFamily: tokens.serif, fontSize: 40, color: tokens.ink,
              letterSpacing: -0.6, lineHeight: 1, fontVariantNumeric: 'tabular-nums',
              whiteSpace: 'nowrap', flexShrink: 0,
            }}>{fmtEUR(total)}</div>
            <div style={{ fontFamily: tokens.sans, fontSize: 13, color: tokens.ink3, textAlign: 'right', minWidth: 0 }}>
              {charges.length} {charges.length === 1 ? 'charge' : 'charges'} · {fmtPct(pctOfIncome, 1)} of income
            </div>
          </div>
        </Card>
      </div>

      {/* Mini 30-day strip */}
      <div style={{ padding: '4px 18px 18px' }}>
        <DayStrip today={today} charges={charges}/>
      </div>

      {charges.length === 0 ? (
        <div style={{ padding: '0 18px' }}>
          <Card style={{ textAlign: 'center', padding: '28px 22px' }} delay={180}>
            <div style={{ fontFamily: tokens.serif, fontSize: 20, color: tokens.ink }}>
              Nothing scheduled
            </div>
            <div style={{ fontFamily: tokens.sans, fontSize: 14, color: tokens.ink3, marginTop: 6 }}>
              No active subscriptions are charging in the next 30 days.
            </div>
          </Card>
        </div>
      ) : (
        Object.entries(groups).map(([wk, items], gi) => (
          <div key={wk} style={{ padding: '4px 18px 14px' }}>
            <div style={{
              padding: '4px 4px 10px',
              fontFamily: tokens.sans, fontSize: 12, fontWeight: 500, letterSpacing: 0.6,
              textTransform: 'uppercase', color: tokens.ink3,
            }}>
              {weekLabel(parseInt(wk, 10))}
            </div>
            <Card padding={0} delay={180 + gi * 80}>
              {items.map((c, i) => (
                <div key={c.id} className="rise-in" style={{
                  display: 'flex', alignItems: 'center', gap: 14,
                  padding: '14px 18px',
                  borderBottom: i < items.length - 1 ? `1px solid ${tokens.hairline}` : 'none',
                  animationDelay: (220 + gi * 80 + i * 50) + 'ms',
                }}>
                  <div style={{
                    width: 44, textAlign: 'center', flexShrink: 0,
                  }}>
                    <div style={{
                      fontFamily: tokens.sans, fontSize: 10, fontWeight: 500, letterSpacing: 0.4,
                      textTransform: 'uppercase', color: tokens.ink3,
                    }}>{DOW_SHORT[c.date.getDay()]}</div>
                    <div style={{
                      fontFamily: tokens.serif, fontSize: 22, color: tokens.ink,
                      lineHeight: 1, marginTop: 2, fontVariantNumeric: 'tabular-nums',
                    }}>{c.date.getDate()}</div>
                  </div>
                  <div style={{ width: 1, height: 32, background: tokens.divider }}/>
                  <SubAvatar name={c.name} size={32}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontFamily: tokens.sans, fontSize: 15, fontWeight: 500, color: tokens.ink,
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                    }}>{c.name}</div>
                    <div style={{
                      fontFamily: tokens.sans, fontSize: 12, color: c.days <= 3 ? tokens.bad : tokens.ink3,
                      marginTop: 2, fontWeight: c.days <= 3 ? 600 : 400,
                    }}>
                      {c.days === 0 ? 'today' : c.days === 1 ? 'tomorrow' : `in ${c.days} days`}
                    </div>
                  </div>
                  <div style={{
                    fontFamily: tokens.serif, fontSize: 18, color: tokens.ink,
                    fontVariantNumeric: 'tabular-nums',
                  }}>{fmtEUR(c.amount, { decimals: 2 })}</div>
                </div>
              ))}
            </Card>
          </div>
        ))
      )}
    </div>
  );
}

function weekLabel(wk) {
  if (wk === 0) return 'This week';
  if (wk === 1) return 'Next week';
  return `In ${wk + 1} weeks`;
}

function DayStrip({ today, charges }) {
  const days = [];
  for (let i = 0; i < 30; i++) {
    const d = new Date(today); d.setDate(today.getDate() + i);
    const matches = charges.filter(c => c.date.toDateString() === d.toDateString());
    days.push({ date: d, charges: matches });
  }
  const max = Math.max(1, ...days.map(d => d.charges.reduce((a,b)=>a+b.amount,0)));

  return (
    <div style={{
      background: tokens.card, borderRadius: tokens.r.xl, padding: '14px 12px 12px',
      border: `1px solid ${tokens.divider}`,
    }}>
      <div style={{
        fontFamily: tokens.sans, fontSize: 11, fontWeight: 500, letterSpacing: 0.6,
        textTransform: 'uppercase', color: tokens.ink3, marginBottom: 10, paddingLeft: 4,
      }}>Daily intensity</div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 2.5, height: 56 }}>
        {days.map((d, i) => {
          const sum = d.charges.reduce((a,b)=>a+b.amount,0);
          const h = sum > 0 ? Math.max(8, (sum / max) * 50) : 3;
          const isToday = i === 0;
          const isMonday = d.date.getDay() === 1;
          return (
            <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
              <div style={{
                width: '100%', height: h, borderRadius: 2,
                background: sum > 0 ? tokens.sage : tokens.divider,
                opacity: sum > 0 ? 1 : 0.4,
                transformOrigin: 'bottom',
                animation: `rise-in 620ms cubic-bezier(0.34, 1.20, 0.64, 1) both`,
                animationDelay: (120 + i * 14) + 'ms',
                transition: 'height 320ms cubic-bezier(0.22,1,0.36,1), background-color 320ms cubic-bezier(0.22,1,0.36,1)',
              }}/>
              {isMonday && !isToday && (
                <div style={{ fontFamily: tokens.sans, fontSize: 9, color: tokens.ink3, fontWeight: 500 }}>
                  {d.date.getDate()}
                </div>
              )}
              {isToday && (
                <div style={{ fontFamily: tokens.sans, fontSize: 9, color: tokens.ink, fontWeight: 700 }}>
                  Today
                </div>
              )}
              {!isToday && !isMonday && <div style={{ height: 11 }}/>}
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { CalendarScreen, DayStrip, weekLabel });
