// screens-subs.jsx — Subscriptions list + Add/Edit + Calendar

function SubsScreen({ store, flashId, onAdd, onEdit, onBack }) {
  const { state, totalIncome, totalSubs, subsPct, toggleSub, deleteSub } = store;
  const { thresholds } = state;

  const subs = [...state.subscriptions]
    .map(s => ({ ...s, days: daysUntilBilling(s.billingDay), next: nextBillingDate(s.billingDay) }))
    .sort((a, b) => {
      // active first, then by days until charge
      if (a.active !== b.active) return a.active ? -1 : 1;
      return a.days - b.days;
    });

  return (
    <div className="page-in" style={{ paddingBottom: 130 }}>
      <ScreenHeader
        eyebrow={onBack
          ? <button onClick={onBack} style={{
              background: 'none', border: 'none', cursor: 'pointer',
              color: tokens.ink3, fontFamily: tokens.sans, fontSize: 12, fontWeight: 500,
              letterSpacing: 0.4, textTransform: 'uppercase', padding: 0,
            }}>← Settings</button>
          : 'Active recurring'}
        title="Subscriptions"
        right={
          <IconButton onClick={onAdd}>{Ico.plus(20, tokens.ink)}</IconButton>
        }
      />

      {/* Burden hero */}
      <div style={{ padding: '4px 18px 14px' }}>
        <Card padding={20} delay={60}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontFamily: tokens.sans, fontSize: 12, fontWeight: 500, letterSpacing: 0.6,
                textTransform: 'uppercase', color: tokens.ink3, marginBottom: 4,
              }}>Monthly cost</div>
              <div style={{
                fontFamily: tokens.serif, fontSize: 36, color: tokens.ink,
                letterSpacing: -0.6, lineHeight: 1, fontVariantNumeric: 'tabular-nums',
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              }}>
                <CountNumber value={totalSubs} format={(v) => fmtEUR(v)} />
              </div>
            </div>
            <div style={{
              display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6, paddingTop: 6,
              flexShrink: 0,
            }}>
              <BurdenDot pct={subsPct} thresholds={thresholds} size={10} pulse/>
              <span style={{
                fontFamily: tokens.sans, fontSize: 13, fontWeight: 600, color: burdenColor(subsPct, thresholds),
                fontVariantNumeric: 'tabular-nums',
              }}>{fmtPct(subsPct, 1)}</span>
              <span style={{ fontFamily: tokens.sans, fontSize: 11, color: tokens.ink3 }}>
                of income · {burdenLabel(subsPct, thresholds)}
              </span>
            </div>
          </div>
          {/* burden bar */}
          <div style={{ marginTop: 16 }}>
            <div style={{
              height: 4, borderRadius: 2, background: tokens.inset, overflow: 'hidden', position: 'relative',
            }}>
              <div style={{
                height: '100%', width: `${Math.min(100, subsPct * 4)}%`,
                background: burdenColor(subsPct, thresholds),
                transition: 'width 760ms cubic-bezier(0.22,1,0.36,1), background-color 320ms cubic-bezier(0.22,1,0.36,1)',
              }}/>
              {/* threshold ticks */}
              <div style={{ position: 'absolute', top: -2, left: `${thresholds.low * 4}%`, width: 1, height: 8, background: tokens.divider }}/>
              <div style={{ position: 'absolute', top: -2, left: `${thresholds.high * 4}%`, width: 1, height: 8, background: tokens.divider }}/>
            </div>
            <div style={{
              display: 'flex', justifyContent: 'space-between', marginTop: 6,
              fontFamily: tokens.sans, fontSize: 11, color: tokens.ink3,
            }}>
              <span>0%</span>
              <span style={{ marginLeft: `${thresholds.low * 4 - 4}%` }}>{thresholds.low}%</span>
              <span style={{ marginRight: `${100 - thresholds.high * 4 - 6}%` }}>{thresholds.high}%</span>
              <span>25%+</span>
            </div>
          </div>
        </Card>
      </div>

      {/* Sub list */}
      <div style={{ padding: '4px 18px 0' }}>
        <div style={{
          padding: '4px 4px 10px',
          fontFamily: tokens.sans, fontSize: 12, fontWeight: 500, letterSpacing: 0.6,
          textTransform: 'uppercase', color: tokens.ink3,
        }}>All subscriptions</div>
        {subs.length === 0 ? (
          <Card style={{ textAlign: 'center', padding: '32px 22px' }} delay={120}>
            <div className="breathe" style={{ marginBottom: 14 }}>
              <svg width="44" height="44" 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: 6 }}>
              Nothing recurring yet
            </div>
            <PillButton kind="sage" onClick={onAdd}>{Ico.plus(16, '#FAF7F1')} Add subscription</PillButton>
          </Card>
        ) : (
          <Card padding={0} delay={120}>
            {subs.map((s, i) => {
              const pct = totalIncome > 0 ? (s.amount / totalIncome) * 100 : 0;
              const soon = s.active && s.days <= 7;
              return (
                <div key={s.id} className={`rise-in${flashId === s.id ? ' sage-flash' : ''}`} style={{ animationDelay: (180 + i * 50) + 'ms', borderRadius: 16 }}>
                <SwipeRow onDelete={() => deleteSub(s.id)}>
                  <div onClick={() => onEdit(s)}
                    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 < subs.length - 1 ? `1px solid ${tokens.hairline}` : 'none',
                    background: tokens.card,
                    opacity: s.active ? 1 : 0.55,
                    transition: 'background-color 200ms cubic-bezier(0.22,1,0.36,1), opacity 320ms cubic-bezier(0.22,1,0.36,1)',
                  }}>
                    <SubAvatar name={s.name} paused={!s.active}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{
                        display: 'flex', alignItems: 'center', gap: 8,
                        fontFamily: tokens.sans, fontSize: 16, color: tokens.ink, fontWeight: 500,
                      }}>
                        <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                          {s.name}
                        </span>
                        {!s.active && (
                          <span style={{
                            fontSize: 10, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase',
                            color: tokens.ink3, background: tokens.inset, padding: '2px 6px', borderRadius: 4,
                          }}>Paused</span>
                        )}
                      </div>
                      <div style={{
                        display: 'flex', alignItems: 'center', gap: 8,
                        fontFamily: tokens.sans, fontSize: 12, color: tokens.ink3, marginTop: 2,
                      }}>
                        <span>Day {s.billingDay}</span>
                        <span>·</span>
                        <span>{fmtPct(pct, 1)} of income</span>
                        {s.active && (
                          <>
                            <span>·</span>
                            <span style={{ color: soon ? tokens.bad : tokens.ink3, fontWeight: soon ? 600 : 400 }}>
                              {s.days === 0 ? 'today' : s.days === 1 ? 'tomorrow' : `in ${s.days}d`}
                            </span>
                          </>
                        )}
                      </div>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div style={{
                        fontFamily: tokens.serif, fontSize: 18, color: tokens.ink,
                        fontVariantNumeric: 'tabular-nums', letterSpacing: -0.3,
                      }}>{fmtEUR(s.amount, { decimals: 2 })}</div>
                      {s.active && soon && (
                        <div style={{ marginTop: 3 }}><BurdenDot pct={20} thresholds={{low:99,high:99}} size={6}/></div>
                      )}
                    </div>
                  </div>
                </SwipeRow>
                </div>
              );
            })}
          </Card>
        )}

        {subs.length > 0 && (
          <>
            <div style={{ height: 14 }}/>
            <PillButton kind="ghost" onClick={onAdd} style={{ width: '100%' }}>
              {Ico.plus(16, tokens.ink)} New subscription
            </PillButton>
          </>
        )}
      </div>
    </div>
  );
}

// ── Add/Edit Income sheet ──────────────────────────────────────────────────
function AddIncomeSheet({ open, initial, onClose, onSave, globalSplit }) {
  const [name, setName] = React.useState('');
  const [amount, setAmount] = React.useState('');
  const [date, setDate] = React.useState(todayISO());

  React.useEffect(() => {
    if (open) {
      setName(initial?.name || '');
      setAmount(initial?.amount != null ? String(initial.amount) : '');
      setDate(initial?.date || todayISO());
    }
  }, [open, initial]);

  const valid = name.trim() && parseFloat(amount) > 0;
  const isEdit = !!initial?.id;
  const amountNum = parseFloat(amount) || 0;
  const investAmt = amountNum * ((globalSplit?.investments ?? 50) / 100);
  const saveAmt   = amountNum * ((globalSplit?.savings     ?? 50) / 100);

  return (
    <Sheet open={open} onClose={onClose} title={isEdit ? 'Edit income' : 'Add income'}>
      <div style={{ padding: '4px 22px 28px' }}>
        <Field label="Name">
          <TextInput value={name} onChange={setName} placeholder="e.g. Salary, Side income, Bonus"/>
        </Field>
        <Field label="Amount" hint="In EUR">
          <TextInput value={amount} onChange={setAmount} placeholder="0,00" suffix="€" inputMode="decimal"/>
        </Field>
        <Field label="Date">
          <TextInput type="date" value={date} onChange={setDate}/>
        </Field>

        {/* Live preview by global split */}
        {amountNum > 0 && (
          <div style={{
            background: tokens.card, padding: '14px 16px', borderRadius: 14,
            border: `1px solid ${tokens.divider}`, marginBottom: 14,
          }}>
            <div style={{
              fontFamily: tokens.sans, fontSize: 11, fontWeight: 500, letterSpacing: 0.6,
              textTransform: 'uppercase', color: tokens.ink3, marginBottom: 10,
            }}>From this entry</div>
            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14,
            }}>
              <PreviewLine dot={tokens.sage}     label={`Invest · ${globalSplit?.investments ?? 50}%`} value={investAmt}/>
              <PreviewLine dot={tokens.sageDeep} label={`Save · ${globalSplit?.savings ?? 50}%`}     value={saveAmt}/>
            </div>
          </div>
        )}

        <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
          <PillButton kind="ghost" size="lg" onClick={onClose} style={{ flex: 1 }}>Cancel</PillButton>
          <PillButton kind="primary" size="lg" disabled={!valid} onClick={() => {
            const entry = { name: name.trim(), amount: parseFloat(amount), date };
            onSave(isEdit ? { ...entry, id: initial.id } : entry);
          }} style={{ flex: 1 }}>
            {isEdit ? 'Save' : 'Add income'}
          </PillButton>
        </div>
      </div>
    </Sheet>
  );
}

// ── Add/Edit Subscription sheet ────────────────────────────────────────────
function AddSubSheet({ open, initial, onClose, onSave, onDelete }) {
  const [name, setName] = React.useState('');
  const [amount, setAmount] = React.useState('');
  const [billingDay, setBillingDay] = React.useState(1);
  const [startDate, setStartDate] = React.useState(todayISO());
  const [active, setActive] = React.useState(true);

  React.useEffect(() => {
    if (open) {
      setName(initial?.name || '');
      setAmount(initial?.amount != null ? String(initial.amount) : '');
      setBillingDay(initial?.billingDay || 1);
      setStartDate(initial?.startDate || todayISO());
      setActive(initial?.active != null ? initial.active : true);
    }
  }, [open, initial]);

  const valid = name.trim() && parseFloat(amount) > 0 && billingDay >= 1 && billingDay <= 31;
  const isEdit = !!initial?.id;

  return (
    <Sheet open={open} onClose={onClose} title={isEdit ? 'Edit subscription' : 'Add subscription'}>
      <div style={{ padding: '4px 22px 28px' }}>
        <Field label="Name">
          <TextInput value={name} onChange={setName} placeholder="e.g. Netflix, Spotify, ChatGPT"/>
        </Field>
        <Field label="Amount">
          <TextInput value={amount} onChange={setAmount} placeholder="0,00" suffix="€" inputMode="decimal"/>
        </Field>
        <Field label="Billing day" hint="Day of the month (1–31)">
          <DayStepper value={billingDay} onChange={setBillingDay}/>
        </Field>
        <Field label="Start date">
          <TextInput type="date" value={startDate} onChange={setStartDate}/>
        </Field>

        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          background: tokens.card, padding: '14px 16px', borderRadius: 14,
          border: `1px solid ${tokens.divider}`, marginBottom: 14,
        }}>
          <div>
            <div style={{ fontFamily: tokens.sans, fontSize: 15, color: tokens.ink, fontWeight: 500 }}>
              Active
            </div>
            <div style={{ fontFamily: tokens.sans, fontSize: 12, color: tokens.ink3, marginTop: 2 }}>
              Counts toward monthly subs total
            </div>
          </div>
          <Switch on={active} onChange={setActive}/>
        </div>

        <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
          <PillButton kind="ghost" size="lg" onClick={onClose} style={{ flex: 1 }}>Cancel</PillButton>
          <PillButton kind="primary" size="lg" disabled={!valid} onClick={() => {
            const entry = {
              name: name.trim(), amount: parseFloat(amount),
              billingDay: parseInt(billingDay, 10), startDate, active,
            };
            onSave(isEdit ? { ...entry, id: initial.id } : entry);
          }} style={{ flex: 1 }}>
            {isEdit ? 'Save' : 'Add'}
          </PillButton>
        </div>

        {isEdit && (
          <div style={{ display: 'flex', justifyContent: 'center', marginTop: 18 }}>
            <button onClick={() => onDelete(initial.id)} style={{
              background: 'none', border: 'none', cursor: 'pointer',
              fontFamily: tokens.sans, fontSize: 14, color: tokens.bad, fontWeight: 500,
              padding: '10px 18px',
            }}>Delete subscription</button>
          </div>
        )}
      </div>
    </Sheet>
  );
}

function DayStepper({ value, onChange }) {
  const dec = () => onChange(Math.max(1, value - 1));
  const inc = () => onChange(Math.min(31, value + 1));
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      background: tokens.card, borderRadius: 14, padding: '0 8px', height: 50,
      border: `1px solid ${tokens.divider}`,
    }}>
      <button onClick={dec} style={stepperBtn}>–</button>
      <div style={{
        flex: 1, textAlign: 'center', fontFamily: tokens.serif, fontSize: 26, color: tokens.ink,
        letterSpacing: -0.3, fontVariantNumeric: 'tabular-nums',
      }}>{value}</div>
      <button onClick={inc} style={stepperBtn}>+</button>
    </div>
  );
}
const stepperBtn = {
  width: 36, height: 36, borderRadius: 999, border: 'none', cursor: 'pointer',
  background: tokens.inset, color: tokens.ink, fontSize: 18, fontWeight: 500,
  fontFamily: 'system-ui',
};

function Switch({ on, onChange }) {
  return <IOSToggle value={on} onChange={onChange}/>;
}

function PreviewLine({ dot, label, value }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span style={{ width: 8, height: 8, borderRadius: 4, background: dot }}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: tokens.sans, fontSize: 11, color: tokens.ink3,
          letterSpacing: 0.3, textTransform: 'uppercase',
        }}>{label}</div>
        <div style={{
          fontFamily: tokens.serif, fontSize: 20, color: tokens.ink,
          fontVariantNumeric: 'tabular-nums', letterSpacing: -0.4, marginTop: 2,
        }}>{fmtEUR(value, { decimals: 0 })}</div>
      </div>
    </div>
  );
}

Object.assign(window, {
  SubsScreen, AddIncomeSheet, AddSubSheet, DayStepper, Switch, PreviewLine,
});
