// Bill calendar — visual month grid showing upcoming bills + income.

const PageCalendar = () => {
  const { state, addBill, deleteBill, loadDemo } = useAppState();
  const [showAdd, setShowAdd] = React.useState(false);

  const now = today();
  const year = now.getFullYear();
  const month = now.getMonth();
  const firstDay = new Date(year, month, 1).getDay() || 7; // Mon=1..Sun=7
  const daysInMonth = new Date(year, month + 1, 0).getDate();

  // Build cells (start with empty cells before day 1)
  const cells = [];
  for (let i = 1; i < firstDay; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);

  const billsByDay = {};
  state.bills.forEach(b => {
    if (b.dayOfMonth >= 1 && b.dayOfMonth <= daysInMonth) {
      (billsByDay[b.dayOfMonth] = billsByDay[b.dayOfMonth] || []).push(b);
    }
  });

  // Income (recurring)
  const incomeByDay = {};
  state.transactions.filter(t => t.recurring === 'monthly' && t.type === 'income').forEach(t => {
    if (t.dayOfMonth >= 1 && t.dayOfMonth <= daysInMonth) {
      (incomeByDay[t.dayOfMonth] = incomeByDay[t.dayOfMonth] || []).push(t);
    }
  });

  const totalBills = state.bills.reduce((a, b) => a + b.amount, 0);
  const upcomingBills = state.bills
    .filter(b => b.dayOfMonth >= now.getDate())
    .sort((a, b) => a.dayOfMonth - b.dayOfMonth);

  return (
    <div>
      <div className="topbar">
        <div>
          <h1 className="page-title">Bill <span className="serif">calendar</span></h1>
          <div className="page-sub">{monthNames[month]} {year} · {fmtZAR(totalBills, {cents:false})} in recurring bills</div>
        </div>
        <div className="row" style={{gap:8}}>
          {state.bills.length === 0 && state.transactions.length === 0 && (
            <button className="btn" onClick={loadDemo}><IPlay size={13}/> Load demo</button>
          )}
          <button className="btn btn-primary" onClick={() => setShowAdd(true)}><IPlus size={14}/> Add bill</button>
        </div>
      </div>

      <div className="grid" style={{gridTemplateColumns:'2fr 1fr', gap:20}}>
        <div className="card card-pad-lg fade-up">
          <div className="row-between" style={{marginBottom:14}}>
            <div className="serif" style={{fontSize:22}}>{monthNames[month]} {year}</div>
            <div className="row" style={{gap:14, fontSize:11, color:'var(--ink-3)'}}>
              <span className="row" style={{gap:5}}><span className="dot" style={{background:'var(--coral)'}}></span> Bill</span>
              <span className="row" style={{gap:5}}><span className="dot" style={{background:'var(--mint)'}}></span> Income</span>
            </div>
          </div>

          <div style={{display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:6, marginBottom:6}}>
            {dayNames.map((d, i) => (
              <div key={i} style={{fontSize:10, color:'var(--ink-3)', textAlign:'center', fontWeight:500, padding:'4px 0', textTransform:'uppercase', letterSpacing:'0.06em'}}>{d}</div>
            ))}
          </div>

          <div className="cal-grid">
            {cells.map((d, i) => {
              if (d === null) return <div key={i} style={{aspectRatio:'1'}}/>;
              const bills = billsByDay[d] || [];
              const incomes = incomeByDay[d] || [];
              const totalDayBills = bills.reduce((a, b) => a + b.amount, 0);
              const totalDayIncome = incomes.reduce((a, t) => a + t.amount, 0);
              const isToday = d === now.getDate();
              return (
                <div
                  key={i}
                  className={`cal-cell ${bills.length ? 'has-bill' : ''} ${incomes.length && !bills.length ? 'has-income' : ''} ${isToday ? 'today' : ''}`}
                  style={{animation: `fadeUp 0.3s ${i*0.008}s both`}}
                  title={[
                    ...bills.map(b => `${b.name}: ${fmtZAR(b.amount, {cents:false})}`),
                    ...incomes.map(t => `${t.note || 'Income'}: +${fmtZAR(t.amount, {cents:false})}`),
                  ].join('\n')}
                >
                  <div style={{fontWeight:500, fontSize:11.5}}>{d}</div>
                  {totalDayBills > 0 && <div className="mono" style={{marginTop:'auto', fontSize:10, fontWeight:500}}>−{fmtZARShort(totalDayBills)}</div>}
                  {totalDayIncome > 0 && !totalDayBills && <div className="mono" style={{marginTop:'auto', fontSize:10, fontWeight:500}}>+{fmtZARShort(totalDayIncome)}</div>}
                </div>
              );
            })}
          </div>
        </div>

        <div className="card card-pad-lg fade-up" style={{animationDelay:'0.1s'}}>
          <div className="card-title">Coming up</div>
          {upcomingBills.length === 0 ? (
            <div style={{fontSize:13, color:'var(--ink-3)', padding:'12px 0'}}>No bills left this month — nice.</div>
          ) : (
            <div style={{display:'flex', flexDirection:'column', gap:12}}>
              {upcomingBills.map((b, i) => {
                const cat = categoryById(b.category);
                const daysAway = b.dayOfMonth - now.getDate();
                return (
                  <div key={b.id} className="row-between" style={{animation:`slideInRight 0.4s ${i*0.06}s both`, padding:'4px 0'}}>
                    <div className="row" style={{gap:10}}>
                      <div style={{
                        width:36, height:36, borderRadius:9,
                        background:`var(${cat.cssVar.replace(')','-soft)').replace('-soft-soft','-soft')})`,
                        color:`var(${cat.cssVar})`,
                        display:'inline-flex', alignItems:'center', justifyContent:'center',
                        fontSize:11, fontWeight:600,
                      }}>{b.dayOfMonth}</div>
                      <div>
                        <div style={{fontSize:13.5, fontWeight:500}}>{b.name}</div>
                        <div style={{fontSize:11, color:'var(--ink-3)'}}>{daysAway === 0 ? 'Today' : daysAway === 1 ? 'Tomorrow' : `In ${daysAway} days`}</div>
                      </div>
                    </div>
                    <div className="row" style={{gap:6}}>
                      <span className="mono" style={{fontWeight:500, fontSize:13}}>{fmtZAR(b.amount, {cents:false})}</span>
                      <button className="btn btn-ghost btn-sm" onClick={() => deleteBill(b.id)}><ITrash size={11}/></button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {showAdd && <AddBillModal onClose={() => setShowAdd(false)} onAdd={b => { addBill(b); setShowAdd(false); }}/>}
    </div>
  );
};

const AddBillModal = ({ onClose, onAdd }) => {
  const { state } = useAppState();
  const [name, setName] = React.useState('');
  const [amount, setAmount] = React.useState('');
  const [day, setDay] = React.useState('1');
  const [category, setCategory] = React.useState('utilities');
  const [memberId, setMemberId] = React.useState(state.members[0]?.id);

  const submit = (e) => {
    e.preventDefault();
    onAdd({
      name: name.trim() || 'New bill',
      amount: parseFloat(amount) || 0,
      dayOfMonth: parseInt(day) || 1,
      category,
      memberId,
    });
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="row-between" style={{marginBottom:18}}>
          <div className="serif" style={{fontSize:24}}>New recurring bill</div>
          <button className="btn btn-ghost btn-sm" onClick={onClose}><IClose size={16}/></button>
        </div>
        <form onSubmit={submit} className="grid" style={{gap:14}}>
          <div className="field">
            <label className="label">Bill name</label>
            <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Eskom" autoFocus required/>
          </div>
          <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:12}}>
            <div className="field">
              <label className="label">Amount (R)</label>
              <input className="input" type="number" step="0.01" value={amount} onChange={e => setAmount(e.target.value)} required/>
            </div>
            <div className="field">
              <label className="label">Day of month</label>
              <input className="input" type="number" min="1" max="31" value={day} onChange={e => setDay(e.target.value)} required/>
            </div>
          </div>
          <div className="field">
            <label className="label">Category</label>
            <select className="select" value={category} onChange={e => setCategory(e.target.value)}>
              {CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
            </select>
          </div>
          <div className="row" style={{gap:8, marginTop:6}}>
            <button type="button" className="btn" style={{flex:1, justifyContent:'center'}} onClick={onClose}>Cancel</button>
            <button type="submit" className="btn btn-primary" style={{flex:1, justifyContent:'center'}}>Add bill</button>
          </div>
        </form>
      </div>
    </div>
  );
};

Object.assign(window, { PageCalendar, AddBillModal });
