// screens-home.jsx — Home / Current Month
// Hero income figure, two split cards (Investments + Savings), subs summary, income entries list.

function HomeScreen({ store, flashId, onAddIncome, onEditIncome, onOpenSubs, dark, onToggleTheme }) {
  const { state, totalIncome, splitAmounts, freeAfterSubs, totalSubs, subsPct, splitFor, deleteIncome } = store;
  const today = new Date();
  const monthLabel = `${MONTHS[today.getMonth()]} ${today.getFullYear()}`;
  const sortedIncomes = [...state.incomes].sort((a,b) => new Date(b.date) - new Date(a.date));

  // upcoming sub charges
  const upcoming = state.subscriptions
    .filter(s => s.active)
    .map(s => ({ ...s, next: nextBillingDate(s.billingDay), days: daysUntilBilling(s.billingDay) }))
    .sort((a,b) => a.days - b.days)
    .slice(0, 3);

  const isEmpty = sortedIncomes.length === 0;
  return (
    <div className="page-in" style={{
      display: 'flex', flexDirection: 'column',
      minHeight: '100%',
      // Empty state: tight bottom so the card sits flush with the tab bar.
      // With entries: extra room so the FAB doesn't cover the last list row.
      paddingBottom: isEmpty
        ? 'calc(48px + env(safe-area-inset-bottom))'
        : 'calc(124px + env(safe-area-inset-bottom))',
    }}>
      <ScreenHeader
        eyebrow={monthLabel}
        title="Monthly Plan"
        right={
          <IconButton onClick={onToggleTheme} aria-label={dark ? 'Switch to light mode' : 'Switch to dark mode'}>
            <span key={dark ? 'sun' : 'moon'} className="icon-swap" style={{ display: 'inline-flex' }}>
              {dark ? Ico.sun(20, tokens.ink2) : Ico.moon(20, tokens.ink2)}
            </span>
          </IconButton>
        }
      />

      {/* Hero total */}
      <div className="hero-in" style={{ padding: '4px 22px 18px', animationDelay: '60ms' }}>
        <div style={{
          fontFamily: tokens.sans, fontSize: 12, fontWeight: 500, letterSpacing: 0.6,
          textTransform: 'uppercase', color: tokens.ink3, marginBottom: 2,
        }}>Total income</div>
        <div style={{
          fontFamily: tokens.serif, fontSize: 72, fontWeight: 400, color: tokens.ink,
          letterSpacing: -2, lineHeight: 1, fontVariantNumeric: 'tabular-nums',
          display: 'flex', alignItems: 'baseline', gap: 10,
        }}>
          <CountNumber value={totalIncome} format={(v) => fmtEUR(v, { sym: false, decimals: 0 })}/>
          <span style={{ fontSize: 36, color: tokens.ink3, fontFamily: tokens.serif }}>€</span>
        </div>
        <div style={{
          fontFamily: tokens.sans, fontSize: 13, color: tokens.ink3, marginTop: 6,
        }}>
          {state.incomes.length} {state.incomes.length === 1 ? 'entry' : 'entries'} this month
        </div>
      </div>

      {/* Three split cards — Invest, Save, Free (what's left after subs) */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, padding: '0 18px 14px',
      }}>
        <SplitCard label="Invest" amount={splitAmounts.investments} total={totalIncome} accent={tokens.sage}     delay={120} />
        <SplitCard label="Save"   amount={splitAmounts.savings}     total={totalIncome} accent={tokens.sageDeep} delay={180} />
        <SplitCard label="Free"   amount={splitAmounts.free}        total={totalIncome} accent={tokens.ink2}     delay={240} muted />
      </div>

      {/* Subscriptions summary */}
      <div style={{ padding: '4px 18px 14px' }}>
        <Card padding={0} onClick={onOpenSubs} delay={300}>
          <div style={{ padding: '16px 18px 14px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div>
                <div style={{
                  fontFamily: tokens.sans, fontSize: 12, fontWeight: 500, letterSpacing: 0.5,
                  textTransform: 'uppercase', color: tokens.ink3, marginBottom: 4,
                }}>Subscriptions</div>
                <div style={{
                  fontFamily: tokens.serif, fontSize: 32, color: tokens.ink, letterSpacing: -0.6, lineHeight: 1,
                }}>
                  <CountNumber value={totalSubs} format={(v) => fmtEUR(v)} />
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, paddingTop: 10 }}>
                <BurdenDot pct={subsPct} thresholds={state.thresholds} pulse />
                <span style={{ fontFamily: tokens.sans, fontSize: 13, color: tokens.ink2, fontWeight: 500 }}>
                  {fmtPct(subsPct, 0)} of income
                </span>
              </div>
            </div>
            {totalIncome > 0 && (
              <div style={{
                marginTop: 12, paddingTop: 12, borderTop: `1px solid ${tokens.hairline}`,
                display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
                fontFamily: tokens.sans, fontSize: 13,
              }}>
                <span style={{ color: tokens.ink3, whiteSpace: 'nowrap' }}>Free left</span>
                <span style={{
                  fontFamily: tokens.serif, fontSize: 18, letterSpacing: -0.2,
                  whiteSpace: 'nowrap',
                  color: freeAfterSubs < 0 ? '#B85450' : tokens.ink,
                }}>{fmtEUR(freeAfterSubs)}</span>
              </div>
            )}
          </div>
          {upcoming.length > 0 && (
            <div style={{ borderTop: `1px solid ${tokens.hairline}`, padding: '10px 18px 14px' }}>
              <div style={{
                fontFamily: tokens.sans, fontSize: 11, fontWeight: 500, letterSpacing: 0.6,
                textTransform: 'uppercase', color: tokens.ink3, marginBottom: 6,
              }}>Upcoming</div>
              {upcoming.map((s, ui) => (
                <div key={s.id} className="rise-in" style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  padding: '7px 0', fontFamily: tokens.sans, fontSize: 14,
                  gap: 8,
                  animationDelay: (380 + ui * 60) + 'ms',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0, flex: 1 }}>
                    <SubAvatar name={s.name} size={26} />
                    <span style={{ color: tokens.ink, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', minWidth: 0 }}>{s.name}</span>
                  </div>
                  <span style={{ color: tokens.ink3, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap', flexShrink: 0, fontSize: 13 }}>
                    {fmtEUR(s.amount, { decimals: 2 })}
                  </span>
                  <span style={{
                    fontFamily: tokens.sans, fontSize: 12, color: s.days <= 3 ? tokens.bad : tokens.ink3,
                    fontVariantNumeric: 'tabular-nums', fontWeight: s.days <= 3 ? 600 : 400,
                    whiteSpace: 'nowrap', flexShrink: 0, textAlign: 'right',
                  }}>
                    {s.days === 0 ? 'today' : s.days === 1 ? 'tomorrow' : `${s.days}d`}
                  </span>
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>

      {/* Income entries list — pushed to bottom of viewport when empty so the
          page doesn't leave a big blank gap below the empty state card. */}
      <div style={{
        padding: '6px 18px 0',
        marginTop: isEmpty ? 'auto' : 0,
        flexShrink: 0,
      }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          padding: '4px 4px 10px', gap: 12,
        }}>
          <span style={{
            fontFamily: tokens.sans, fontSize: 12, fontWeight: 500, letterSpacing: 0.6,
            textTransform: 'uppercase', color: tokens.ink3, whiteSpace: 'nowrap',
          }}>This month</span>
          <span style={{
            fontFamily: tokens.sans, fontSize: 11, color: tokens.ink3,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>Tap to edit · swipe to delete</span>
        </div>
        {sortedIncomes.length === 0 ? (
          <Card style={{ textAlign: 'center', padding: '22px 22px 14px' }} delay={400}>
            <div className="breathe" style={{ marginBottom: 10 }}>
              <svg width="36" height="36" viewBox="0 0 44 44" fill="none" aria-hidden="true">
                <circle cx="22" cy="22" r="18" stroke={tokens.ink3} strokeOpacity="0.35" strokeWidth="1.2"/>
                <circle cx="22" cy="22" r="4" fill={tokens.sage}/>
              </svg>
            </div>
            <div style={{ fontFamily: tokens.serif, fontSize: 22, color: tokens.ink, marginBottom: 4 }}>
              No income yet
            </div>
            <div style={{ fontFamily: tokens.sans, fontSize: 14, color: tokens.ink3, marginBottom: 14, textWrap: 'pretty' }}>
              Add your first entry to see how much to invest and save this month.
            </div>
            <PillButton kind="sage" size="md" onClick={onAddIncome}>
              {Ico.plus(16, tokens.card)} Add income
            </PillButton>
          </Card>
        ) : (
          <Card padding={0} delay={400}>
            {sortedIncomes.map((inc, i) => {
              const sf = splitFor(inc);
              return (
                <div key={inc.id} className={`rise-in${flashId === inc.id ? ' sage-flash' : ''}`} style={{ animationDelay: (460 + i * 50) + 'ms', borderRadius: 16 }}>
                <SwipeRow onDelete={() => deleteIncome(inc.id)}>
                  <div onClick={() => onEditIncome(inc)}
                    onPointerDown={e => e.currentTarget.style.background = tokens.inset}
                    onPointerUp={e => e.currentTarget.style.background = tokens.card}
                    onPointerLeave={e => e.currentTarget.style.background = tokens.card}
                    style={{
                    display: 'flex', alignItems: 'center', gap: 14,
                    padding: '14px 18px', cursor: 'pointer',
                    borderBottom: i < sortedIncomes.length - 1 ? `1px solid ${tokens.hairline}` : 'none',
                    background: tokens.card,
                    transition: 'background-color 200ms cubic-bezier(0.22,1,0.36,1)',
                  }}>
                    <div style={{
                      width: 6, height: 36, borderRadius: 3, background: tokens.sage,
                      opacity: 0.7,
                    }}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{
                        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12,
                      }}>
                        <span style={{
                          fontFamily: tokens.sans, fontSize: 16, color: tokens.ink, fontWeight: 500,
                          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                        }}>{inc.name}</span>
                        <span style={{
                          fontFamily: tokens.serif, fontSize: 20, color: tokens.ink,
                          fontVariantNumeric: 'tabular-nums', letterSpacing: -0.3, flexShrink: 0,
                          whiteSpace: 'nowrap',
                        }}>+{fmtEUR(inc.amount, { decimals: 0 })}</span>
                      </div>
                      <div style={{
                        fontFamily: tokens.sans, fontSize: 12, color: tokens.ink3, marginTop: 2,
                      }}>{fmtDate(inc.date)}</div>
                      <div style={{
                        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginTop: 10,
                        paddingTop: 10, borderTop: `1px solid ${tokens.hairline}`,
                      }}>
                        <BreakdownChip dot={tokens.sage}     label="Invest" value={sf.investments} />
                        <BreakdownChip dot={tokens.sageDeep} label="Save"   value={sf.savings} />
                        <BreakdownChip dot={tokens.ink3}     label="Free"   value={sf.free} />
                      </div>
                    </div>
                  </div>
                </SwipeRow>
                </div>
              );
            })}
          </Card>
        )}
      </div>
    </div>
  );
}

// Derived pct from amount/total — honors per-income overrides automatically
function SplitCard({ label, amount, total, accent, delay = 0, muted = false }) {
  const pct = total > 0 ? (amount / total) * 100 : 0;
  return (
    <Card padding={0} style={{ overflow: 'hidden', background: muted ? tokens.inset : tokens.card }} delay={delay}>
      <div style={{ padding: '14px 14px 12px' }}>
        <div style={{
          fontFamily: tokens.sans, fontSize: 11, fontWeight: 500, letterSpacing: 0.6,
          textTransform: 'uppercase', color: tokens.ink3, marginBottom: 6,
        }}>{label}</div>
        <div style={{
          fontFamily: tokens.serif, fontSize: 26, color: tokens.ink, lineHeight: 1,
          fontVariantNumeric: 'tabular-nums', letterSpacing: -0.6, marginBottom: 10,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>
          <CountNumber value={amount} format={(v) => fmtEUR(v, { decimals: 0 })} />
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{
            flex: 1, height: 4, borderRadius: 2, background: tokens.inset, overflow: 'hidden',
          }}>
            <div style={{
              height: '100%', width: `${pct}%`, background: accent,
              transition: 'width 420ms cubic-bezier(0.32, 0.72, 0, 1)',
            }}/>
          </div>
          <span style={{
            fontFamily: tokens.sans, fontSize: 11, color: tokens.ink3, fontVariantNumeric: 'tabular-nums', minWidth: 28, textAlign: 'right',
          }}>{Math.round(pct)}%</span>
        </div>
      </div>
    </Card>
  );
}

// Local SwipeRow removed — use global SwipeRow from ui.jsx (richer behavior:
// resistance, full-swipe-to-delete, pointer-capture, locked direction).

// Small chip used in per-income breakdown row
function BreakdownChip({ dot, label, value }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
        <span style={{
          width: 6, height: 6, borderRadius: 3, background: dot, flexShrink: 0,
        }}/>
        <span style={{
          fontFamily: tokens.sans, fontSize: 10, fontWeight: 500, letterSpacing: 0.5,
          textTransform: 'uppercase', color: tokens.ink3,
        }}>{label}</span>
      </div>
      <div style={{
        fontFamily: tokens.serif, fontSize: 15, color: tokens.ink,
        fontVariantNumeric: 'tabular-nums', letterSpacing: -0.2,
        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
      }}>{fmtEUR(value, { decimals: 0 })}</div>
    </div>
  );
}

Object.assign(window, { HomeScreen, SplitCard, BreakdownChip });
