/* Nutri — Data cleanup / delete by date range (Calories + Finance).
   Safe by design: only the explicitly-selected data types in the chosen range are deleted.
   Accounts, categories, projects, recipes, local library, schedules, gold, rates are never
   offered here, so they can't be deleted by mistake. Preview counts + confirmation required;
   large deletes require typing DELETE. */

function _clMonthRange() {
  const d = new Date(); const y = d.getFullYear(), mo = d.getMonth();
  const last = new Date(y, mo + 1, 0).getDate();
  const mm = String(mo + 1).padStart(2, '0');
  return [`${y}-${mm}-01`, `${y}-${mm}-${String(last).padStart(2, '0')}`];
}
function _clFmt(iso) { if (!iso) return ''; try { return new Date(iso + 'T00:00:00').toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }); } catch (_) { return iso; } }

function DataCleanupSheet({ mode, onClose, flashToast }) {
  const store = useStore();
  const today = todayISO();
  const [m0, m1] = _clMonthRange();
  const [rangeMode, setRangeMode] = React.useState('month'); // today | month | custom
  const [from, setFrom] = React.useState(m0);
  const [to, setTo] = React.useState(m1);
  const [confirmText, setConfirmText] = React.useState('');
  const [sel, setSel] = React.useState(mode === 'finance'
    ? { expense: true, income: false, transfer: false, fixedPaid: false, all: false }
    : { meals: true, notes: false, weight: false, inbody: false });

  const effFrom = rangeMode === 'today' ? today : rangeMode === 'month' ? m0 : from;
  const effTo = rangeMode === 'today' ? today : rangeMode === 'month' ? m1 : to;
  const inRange = d => (d || '') >= effFrom && (d || '') <= effTo;
  const validRange = effFrom && effTo && effFrom <= effTo;

  // live counts in range
  let counts = {};
  if (mode === 'finance') {
    const r = (store.finance() || []).filter(t => inRange(t.date));
    counts = {
      expense: r.filter(t => (t.kind || 'expense') === 'expense' && t.source !== 'fixed').length,
      income: r.filter(t => t.kind === 'income').length,
      transfer: r.filter(t => t.kind === 'transfer').length,
      fixedPaid: r.filter(t => t.source === 'fixed').length,
      all: r.length,
    };
  } else {
    const s = store.settings() || {};
    counts = {
      meals: (store.meals() || []).filter(m => inRange(m.date)).length,
      notes: Object.keys(s.notes || {}).filter(inRange).length,
      weight: Object.keys(s.weights || {}).filter(inRange).length,
      inbody: (store.inBodyEntries ? store.inBodyEntries() : []).filter(e => inRange(e.date)).length,
    };
  }

  const total = mode === 'finance'
    ? (sel.all ? counts.all : (sel.expense ? counts.expense : 0) + (sel.income ? counts.income : 0) + (sel.transfer ? counts.transfer : 0) + (sel.fixedPaid ? counts.fixedPaid : 0))
    : (sel.meals ? counts.meals : 0) + (sel.notes ? counts.notes : 0) + (sel.weight ? counts.weight : 0) + (sel.inbody ? counts.inbody : 0);
  const requireType = total >= 30;
  const canDelete = validRange && total > 0 && (!requireType || confirmText.trim().toUpperCase() === 'DELETE');

  function toggle(key) {
    setSel(s => {
      if (mode === 'finance' && key === 'all') { const v = !s.all; return { expense: false, income: false, transfer: false, fixedPaid: false, all: v }; }
      const next = { ...s, [key]: !s[key] };
      if (mode === 'finance') next.all = false;
      return next;
    });
  }
  function doDelete() {
    if (!canDelete) return;
    if (!confirm('Delete the selected data in ' + _clFmt(effFrom) + ' → ' + _clFmt(effTo) + '? This cannot be undone.')) return;
    if (mode === 'finance') {
      const removed = store.deleteFinanceInRange(effFrom, effTo, sel);
      flashToast && flashToast('Deleted ' + removed + ' record' + (removed === 1 ? '' : 's'));
    } else {
      let n = 0;
      if (sel.meals) n += store.deleteMealsInRange(effFrom, effTo);
      if (sel.notes) n += store.deleteDayNotesInRange(effFrom, effTo);
      if (sel.weight) n += store.deleteWeightsInRange(effFrom, effTo);
      if (sel.inbody) n += store.deleteInBodyInRange(effFrom, effTo);
      flashToast && flashToast('Deleted ' + n + ' item' + (n === 1 ? '' : 's'));
    }
    onClose();
  }

  const TARGETS = mode === 'finance'
    ? [['expense', 'Expenses', counts.expense], ['income', 'Income', counts.income], ['transfer', 'Transfers', counts.transfer], ['fixedPaid', 'Fixed-expense paid records', counts.fixedPaid], ['all', 'All transactions in range', counts.all]]
    : [['meals', 'Daily meals', counts.meals], ['notes', 'Day notes', counts.notes], ['weight', 'Weight logs', counts.weight], ['inbody', 'InBody entries', counts.inbody]];

  const rangePill = (id, label) => (
    <button onClick={() => setRangeMode(id)} style={{
      padding: '7px 12px', borderRadius: 999, flexShrink: 0,
      background: rangeMode === id ? 'var(--accent)' : 'var(--surface-2)', color: rangeMode === id ? 'var(--on-accent)' : 'var(--text)',
      border: '1px solid ' + (rangeMode === id ? 'var(--accent)' : 'var(--border-2)'), fontSize: 12.5, fontWeight: 600, cursor: 'pointer', font: 'inherit',
    }}>{label}</button>
  );
  const fld = { width: '100%', border: '1px solid var(--border)', background: 'var(--surface-2)', borderRadius: 10, padding: '8px 12px', outline: 'none', font: 'inherit', fontSize: 14, color: 'var(--text)', boxSizing: 'border-box' };

  return (
    <SheetShell title={mode === 'finance' ? 'Clean up finance data' : 'Clean up diet data'} onClose={onClose}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.5 }}>
          Delete {mode === 'finance' ? 'transactions' : 'diet data'} in a date range. {mode === 'finance' ? 'Accounts, categories, projects, schedules, gold & rates are never touched.' : 'Recipes and your food library are never touched.'}
        </div>

        {/* range */}
        <div>
          <div style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>Range</div>
          <div style={{ display: 'flex', gap: 6, marginBottom: 8 }}>
            {rangePill('today', 'Today')}{rangePill('month', 'This month')}{rangePill('custom', 'Custom')}
          </div>
          {rangeMode === 'custom' && (
            <div style={{ display: 'flex', gap: 8 }}>
              <label style={{ flex: 1 }}><div style={{ fontSize: 10.5, color: 'var(--muted)', marginBottom: 3 }}>From</div><input type="date" value={from} onChange={e => setFrom(e.target.value)} style={fld}/></label>
              <label style={{ flex: 1 }}><div style={{ fontSize: 10.5, color: 'var(--muted)', marginBottom: 3 }}>To</div><input type="date" value={to} onChange={e => setTo(e.target.value)} style={fld}/></label>
            </div>
          )}
          <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 6 }}>{_clFmt(effFrom)} → {_clFmt(effTo)}{!validRange ? ' · invalid range' : ''}</div>
        </div>

        {/* targets */}
        <div>
          <div style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>What to delete</div>
          {TARGETS.map(([key, label, count]) => (
            <label key={key} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '10px 12px', marginBottom: 6, borderRadius: 12, background: 'var(--surface-2)', border: '1px solid var(--border)', cursor: 'pointer' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <input type="checkbox" checked={!!sel[key]} onChange={() => toggle(key)}/>
                <span style={{ fontSize: 13.5, fontWeight: 600 }}>{label}</span>
              </span>
              <span style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 600 }}>{count || 0}</span>
            </label>
          ))}
        </div>

        {/* preview */}
        <div style={{ ...nutriStyles.card, padding: 12, background: total > 0 ? 'rgba(194,85,78,0.06)' : 'var(--surface)', borderColor: total > 0 ? 'rgba(194,85,78,0.3)' : 'var(--border)' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: total > 0 ? '#C2554E' : 'var(--text)' }}>
            {total > 0 ? `Will delete ${total} item${total === 1 ? '' : 's'}` : 'Nothing selected to delete'}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 3 }}>in {_clFmt(effFrom)} → {_clFmt(effTo)}</div>
        </div>

        {requireType && (
          <div>
            <div style={{ fontSize: 12, color: '#C2554E', marginBottom: 6 }}>That’s a large delete. Type <b>DELETE</b> to confirm.</div>
            <input value={confirmText} onChange={e => setConfirmText(e.target.value)} placeholder="DELETE" style={fld}/>
          </div>
        )}

        <button onClick={doDelete} disabled={!canDelete} style={{
          width: '100%', padding: '12px', borderRadius: 12, font: 'inherit', fontSize: 14, fontWeight: 700, cursor: canDelete ? 'pointer' : 'default',
          background: canDelete ? '#C2554E' : 'var(--surface-2)', color: canDelete ? '#fff' : 'var(--muted)', border: '1px solid ' + (canDelete ? '#C2554E' : 'var(--border-2)'),
        }}>Delete {total > 0 ? total + ' item' + (total === 1 ? '' : 's') : ''}</button>
      </div>
    </SheetShell>
  );
}

Object.assign(window, { DataCleanupSheet });
