// Dashboard — today at a glance. Integrated view of meds + intake + refills + spending.

const { TODAY_INTAKE, MED, CABINET, REGIMENS, SPENDING, PURCHASES, ACTIVITY, PRICES, STORES } = window.MESHI;

const DashboardPage = ({ onNav }) => {
  const [intake, setIntake] = useState(TODAY_INTAKE);

  const taken = intake.filter(i => i.status === 'taken').length;
  const total = intake.length;
  const pct = Math.round((taken / total) * 100);

  const lowMeds = CABINET.map(r => ({ r, s: cabinetStatus(r) })).filter(x => x.s.level !== 'ok').sort((a, b) => a.s.days - b.s.days);

  const thisMonth = SPENDING[SPENDING.length - 1].amount;
  const lastMonth = SPENDING[SPENDING.length - 2].amount;
  const spendDelta = ((thisMonth - lastMonth) / lastMonth) * 100;

  const toggleTake = (id) => {
    setIntake(intake.map(i => i.id === id ? { ...i, status: i.status === 'taken' ? 'upcoming' : 'taken', takenAt: '21:04' } : i));
  };

  // Days supply across meds for mini sparkline
  const sparkMax = 60;
  const supplyData = CABINET.map(r => ({ med: MED[r.medId], days: cabinetStatus(r).days }))
    .sort((a, b) => a.days - b.days);

  return (
    <div className="mt-page">
      <div className="dash-hero">
        <div className="dash-hero__greet">
          <div className="dash-hero__day">Saturday · April 18</div>
          <div className="dash-hero__title">Good evening, aeri.</div>
          <div className="dash-hero__sub">Evening pills are due in <span className="mt-mono" style={{color:'var(--ink-strong)'}}>2h 34m</span>. Everything else is on track.</div>
        </div>
        <div className="dash-hero__ring">
          <svg viewBox="0 0 120 120" width="120" height="120">
            <circle cx="60" cy="60" r="52" fill="none" stroke="var(--bg-inset)" strokeWidth="10" />
            <circle cx="60" cy="60" r="52" fill="none" stroke="var(--brand)" strokeWidth="10"
              strokeDasharray={2 * Math.PI * 52}
              strokeDashoffset={2 * Math.PI * 52 * (1 - pct / 100)}
              strokeLinecap="round"
              transform="rotate(-90 60 60)"
            />
            <text x="60" y="56" textAnchor="middle" fill="var(--ink-strong)" style={{fontFamily:'var(--font-display)', fontSize:24, fontWeight:500}}>{taken}<tspan fill="var(--ink-muted)" fontSize="14">/{total}</tspan></text>
            <text x="60" y="74" textAnchor="middle" fill="var(--ink-muted)" fontSize="10" letterSpacing="1">DOSES TAKEN</text>
          </svg>
        </div>
      </div>

      <div className="dash-grid">
        <section className="mt-card dash-panel" style={{ gridColumn: 'span 8' }}>
          <div className="mt-card__head">
            <div>
              <div className="mt-card__title">Today's schedule</div>
              <div className="mt-card__sub">{total - taken} upcoming · {taken} completed</div>
            </div>
            <button className="mt-btn mt-btn--ghost" onClick={() => onNav('schedule')}>Open log <Icon name="arrow" size={12}/></button>
          </div>
          <div className="dash-schedule">
            {['08:00', '21:00'].map(time => {
              const items = intake.filter(i => i.scheduled === time);
              if (!items.length) return null;
              const allTaken = items.every(i => i.status === 'taken');
              return (
                <div key={time} className={'dash-sched__slot' + (allTaken ? ' is-done' : '')}>
                  <div className="dash-sched__time">
                    <div className="mono" style={{fontSize:18, fontWeight:500, color:'var(--ink-strong)'}}>{time}</div>
                    <div style={{fontSize:10, color:'var(--ink-faint)', textTransform:'uppercase', letterSpacing:'.06em'}}>{time === '08:00' ? 'Morning' : 'Evening'}</div>
                  </div>
                  <div className="dash-sched__items">
                    {items.map(i => {
                      const m = MED[i.medId];
                      return (
                        <button key={i.id} className={'dash-sched__pill' + (i.status === 'taken' ? ' is-taken' : '')} onClick={() => toggleTake(i.id)}>
                          <span className={'dash-sched__check' + (i.status === 'taken' ? ' is-taken' : '')}>
                            {i.status === 'taken' && <Icon name="check" size={10} />}
                          </span>
                          <span style={{ color: 'var(--viz-' + m.color + ')', width: 6, height: 6, borderRadius: 3, background: 'currentColor', display: 'inline-block' }} />
                          <span className="dash-sched__name">{m.name}</span>
                          <span className="dash-sched__dose">{i.qty} {m.form.toLowerCase()}</span>
                        </button>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        </section>

        <section className="mt-card dash-panel" style={{ gridColumn: 'span 4' }}>
          <div className="mt-card__head">
            <div>
              <div className="mt-card__title">Running low</div>
              <div className="mt-card__sub">{lowMeds.length} need attention</div>
            </div>
            <button className="mt-btn mt-btn--ghost" onClick={() => onNav('refills')}>Refills</button>
          </div>
          <div className="dash-low">
            {lowMeds.slice(0, 4).map(({ r, s }) => {
              const m = MED[r.medId];
              return (
                <div key={r.medId} className="dash-low__item">
                  <div className="cab-card__swatch cab-card__swatch--sm" style={{ '--c': 'var(--viz-' + m.color + ')' }}>
                    <Icon name={m.form === 'Injection' ? 'injection' : m.form === 'Capsule' ? 'capsule' : 'pill'} size={12} />
                  </div>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{fontSize:13, fontWeight:500, color:'var(--ink-strong)'}}>{m.name}</div>
                    <div style={{fontSize:11, color:'var(--ink-muted)'}}>{r.qty} {r.unit}</div>
                  </div>
                  <div style={{textAlign:'right'}}>
                    <div className="num" style={{fontSize:14, fontWeight:600, color: s.level === 'critical' ? 'var(--danger)' : 'var(--warn)'}}>{s.days}d</div>
                    <div style={{fontSize:10, color:'var(--ink-faint)'}}>left</div>
                  </div>
                </div>
              );
            })}
          </div>
        </section>

        <section className="mt-card dash-panel" style={{ gridColumn: 'span 5' }}>
          <div className="mt-card__head">
            <div>
              <div className="mt-card__title">Spending · 6 months</div>
              <div className="mt-card__sub">{fmtJPY(thisMonth)} this month <span style={{color: spendDelta < 0 ? 'var(--ok)' : 'var(--danger)', marginLeft:4}}>{spendDelta < 0 ? '↓' : '↑'} {Math.abs(Math.round(spendDelta))}%</span></div>
            </div>
            <button className="mt-btn mt-btn--ghost" onClick={() => onNav('activity')}>Details</button>
          </div>
          <div className="dash-spend">
            <svg viewBox="0 0 360 140" width="100%" height="140" preserveAspectRatio="none">
              {SPENDING.map((m, i) => {
                const max = Math.max(...SPENDING.map(s => s.amount));
                const h = (m.amount / max) * 100;
                const x = 20 + i * 56;
                const isLast = i === SPENDING.length - 1;
                return (
                  <g key={m.month}>
                    <rect x={x} y={120 - h} width="36" height={h} rx="3"
                      fill={isLast ? 'var(--brand)' : 'var(--brand-soft)'}
                      stroke={isLast ? 'var(--brand-deep)' : 'none'}
                    />
                    <text x={x + 18} y="135" textAnchor="middle" fontSize="9" fill="var(--ink-faint)">{m.month.slice(5)}</text>
                    <text x={x + 18} y={120 - h - 4} textAnchor="middle" fontSize="9" fill={isLast ? 'var(--ink)' : 'var(--ink-muted)'} fontWeight={isLast ? 600 : 400}>
                      {(m.amount / 1000).toFixed(0)}k
                    </text>
                  </g>
                );
              })}
            </svg>
          </div>
        </section>

        <section className="mt-card dash-panel" style={{ gridColumn: 'span 7' }}>
          <div className="mt-card__head">
            <div>
              <div className="mt-card__title">Cabinet — days of supply</div>
              <div className="mt-card__sub">At current usage</div>
            </div>
            <button className="mt-btn mt-btn--ghost" onClick={() => onNav('cabinet')}>Open cabinet</button>
          </div>
          <div className="dash-supply">
            {supplyData.map(s => {
              const pct = Math.min(100, (s.days / sparkMax) * 100);
              const tone = s.days <= 7 ? 'critical' : s.days <= 14 ? 'low' : 'ok';
              return (
                <div key={s.med.id} className="dash-supply__row">
                  <div className="dash-supply__name">{s.med.name}</div>
                  <div className="dash-supply__bar">
                    <div className={'dash-supply__fill dash-supply__fill--' + tone} style={{ width: pct + '%' }} />
                  </div>
                  <div className="dash-supply__days num">{s.days}<span>d</span></div>
                </div>
              );
            })}
          </div>
        </section>

        <section className="mt-card dash-panel" style={{ gridColumn: 'span 6' }}>
          <div className="mt-card__head">
            <div>
              <div className="mt-card__title">Pending orders</div>
              <div className="mt-card__sub">{PURCHASES.filter(p => p.status === 'pending').length} awaiting arrival</div>
            </div>
            <button className="mt-btn mt-btn--ghost" onClick={() => onNav('purchases')}>All purchases</button>
          </div>
          <div className="dash-orders">
            {PURCHASES.filter(p => p.status === 'pending').map(p => {
              const s = STORES.find(s => s.id === p.store);
              const total = p.items.reduce((a, i) => a + i.price, 0);
              return (
                <div key={p.id} className="dash-order">
                  <div className="dash-order__icon"><Icon name="truck" size={14} /></div>
                  <div style={{flex:1}}>
                    <div style={{fontWeight:500, fontSize:13}}>{s?.name}</div>
                    <div style={{fontSize:11, color:'var(--ink-muted)'}}>{p.items.map(i => MED[i.medId].name).join(', ')}</div>
                  </div>
                  <div style={{textAlign:'right'}}>
                    <div className="num" style={{fontSize:13, fontWeight:500}}>{fmtJPY(total)}</div>
                    <div style={{fontSize:10, color:'var(--ink-faint)'}}>ordered {p.date}</div>
                  </div>
                </div>
              );
            })}
            {PURCHASES.filter(p => p.status === 'received').slice(0, 2).map(p => {
              const s = STORES.find(s => s.id === p.store);
              return (
                <div key={p.id} className="dash-order is-past">
                  <div className="dash-order__icon"><Icon name="check" size={14} /></div>
                  <div style={{flex:1}}>
                    <div style={{fontSize:12, color:'var(--ink-muted)'}}>{s?.name} · {p.items.length} items received</div>
                  </div>
                  <div style={{fontSize:10, color:'var(--ink-faint)'}}>{p.date}</div>
                </div>
              );
            })}
          </div>
        </section>

        <section className="mt-card dash-panel" style={{ gridColumn: 'span 6' }}>
          <div className="mt-card__head">
            <div>
              <div className="mt-card__title">Recent activity</div>
              <div className="mt-card__sub">Cabinet changes</div>
            </div>
            <button className="mt-btn mt-btn--ghost" onClick={() => onNav('activity')}>See all</button>
          </div>
          <div className="dash-activity">
            {ACTIVITY.slice(0, 5).map(a => {
              const m = MED[a.medId];
              return (
                <div key={a.id} className="dash-act">
                  <span className={'mt-pill mt-pill--' + (a.type === 'consumed' ? 'info' : a.type === 'added' ? 'ok' : 'warn')} style={{minWidth:76, justifyContent:'center'}}>{a.type}</span>
                  <span style={{flex:1, fontSize:12}}>
                    <strong style={{fontWeight:500}}>{m.name}</strong>
                    <span className="num" style={{marginLeft:6, color: a.delta < 0 ? 'var(--ink-muted)' : 'var(--ok)'}}>
                      {a.delta > 0 ? '+' : ''}{a.delta}
                    </span>
                    <span className="num" style={{color:'var(--ink-faint)', marginLeft:6}}>{a.before}→{a.after}</span>
                  </span>
                  <span className="mono" style={{fontSize:10, color:'var(--ink-faint)'}}>{a.at.slice(5)}</span>
                </div>
              );
            })}
          </div>
        </section>
      </div>
    </div>
  );
};

window.DashboardPage = DashboardPage;
