// Schedule & Intake Log — slot-based, collapsed by default
const { TODAY_INTAKE: INTAKE_SEED, MED: MED_S, REGIMENS: REGS_S } = window.MESHI;

const SchedulePage = () => {
  const [intake, setIntake] = useState(INTAKE_SEED);
  const [day, setDay] = useState(5);
  const [expanded, setExpanded] = useState(null); // slot time

  const weekDays = ['Mon 13', 'Tue 14', 'Wed 15', 'Thu 16', 'Fri 17', 'Sat 18', 'Sun 19'];
  const adherence = [1.0, 1.0, 1.0, 0.88, 1.0, 0.50, 0.0];

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

  // Group by scheduled time
  const slots = [
    { time: '08:00', label: 'Morning', icon: 'sun' },
    { time: '21:00', label: 'Evening', icon: 'moon' },
  ].map(s => {
    const items = intake.filter(i => i.scheduled === s.time);
    const done = items.filter(i => i.status === 'taken').length;
    return { ...s, items, done, total: items.length, complete: done === items.length && items.length > 0 };
  });

  const totalDone = intake.filter(i => i.status === 'taken').length;

  return (
    <div className="mt-page">
      {/* Week strip — adherence heatmap */}
      <div className="sched-weekbar">
        <div className="sched-weekbar__label">
          <div style={{fontSize:10, color:'var(--ink-faint)', textTransform:'uppercase', letterSpacing:'.08em', fontWeight:500}}>This week</div>
          <div style={{fontSize:13, color:'var(--ink-strong)', fontWeight:500, marginTop:2}}>
            <span className="num">{Math.round(adherence.reduce((a,b)=>a+b,0)/adherence.length*100)}%</span> adherence
          </div>
        </div>
        <div className="sched-weekbar__days">
          {weekDays.map((d, i) => {
            const isToday = i === day;
            const a = adherence[i];
            return (
              <button key={d} className={'sched-weekday' + (isToday ? ' is-active' : '')} onClick={() => setDay(i)}>
                <div className="sched-weekday__label">{d.split(' ')[0]}</div>
                <div className="sched-weekday__num">{d.split(' ')[1]}</div>
                <div className="sched-weekday__bar">
                  <div className="sched-weekday__fill" style={{height: (a*100) + '%', background: a >= 1 ? 'var(--ok)' : a >= 0.5 ? 'var(--warn)' : a > 0 ? 'var(--danger)' : 'var(--border-strong)'}}/>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap: 16, marginTop: 16}}>
        <div className="mt-card">
          <div className="mt-card__head">
            <div>
              <div className="mt-card__title">Saturday, April 18</div>
              <div className="mt-card__sub"><span className="num">{totalDone}</span> of <span className="num">{intake.length}</span> doses · 18:30 now</div>
            </div>
            <button className="mt-btn mt-btn--ghost"><Icon name="plus" size={12}/> Log off-schedule</button>
          </div>

          <div className="sched-slots">
            {slots.map(slot => {
              const isOpen = expanded === slot.time;
              const now = 18.5;
              const slotHr = parseInt(slot.time);
              const status = slot.complete ? 'done' : slotHr < now ? 'overdue' : 'upcoming';
              return (
                <div key={slot.time} className={'sched-slot sched-slot--' + status + (isOpen ? ' is-open' : '')}>
                  <button className="sched-slot__row" onClick={() => setExpanded(isOpen ? null : slot.time)}>
                    <div className="sched-slot__time">
                      <div className="sched-slot__hour num">{slot.time}</div>
                      <div className="sched-slot__phase">{slot.label}</div>
                    </div>
                    <div className="sched-slot__main">
                      <div className="sched-slot__summary">
                        <span className="num" style={{fontSize:15, fontWeight:600, color:'var(--ink-strong)'}}>{slot.done}/{slot.total}</span>
                        <span style={{fontSize:13, color:'var(--ink-muted)'}}>doses</span>
                        <div className="sched-slot__dots">
                          {slot.items.map(i => {
                            const m = MED_S[i.medId];
                            return <span key={i.id} className={'sched-slot__dot' + (i.status === 'taken' ? ' is-taken' : '')} style={{background: i.status === 'taken' ? 'var(--viz-' + m.color + ')' : 'transparent', borderColor: 'var(--viz-' + m.color + ')'}}/>;
                          })}
                        </div>
                      </div>
                      {status === 'done' && <span className="mt-pill mt-pill--ok">All taken</span>}
                      {status === 'overdue' && <span className="mt-pill mt-pill--warn">Overdue</span>}
                      {status === 'upcoming' && <span className="mt-pill mt-pill--ghost">Upcoming</span>}
                    </div>
                    <div className="sched-slot__actions" onClick={e => e.stopPropagation()}>
                      {!slot.complete && <button className="mt-btn mt-btn--primary" onClick={() => markSlot(slot.time)}><Icon name="check" size={12}/> Take all</button>}
                      <Icon name="chevDown" size={14} style={{transform: isOpen ? 'rotate(180deg)' : 'none', transition:'transform .2s', color:'var(--ink-faint)'}}/>
                    </div>
                  </button>
                  {isOpen && (
                    <div className="sched-slot__detail">
                      {slot.items.map(i => {
                        const m = MED_S[i.medId];
                        return (
                          <button key={i.id} className={'sched-slot__item' + (i.status === 'taken' ? ' is-taken' : '')} onClick={() => toggle(i.id)}>
                            <span className={'sched-check' + (i.status === 'taken' ? ' is-taken' : '')}>{i.status === 'taken' && <Icon name="check" size={10}/>}</span>
                            <span style={{background:'var(--viz-'+m.color+')', width:3, height:20, borderRadius:2}}/>
                            <span style={{flex:1, display:'flex', flexDirection:'column', alignItems:'flex-start'}}>
                              <span style={{fontWeight:500, fontSize:13, color:'var(--ink-strong)'}}>{m.name}</span>
                              <span style={{fontSize:11, color:'var(--ink-muted)'}}>{i.qty} {m.form.toLowerCase()} · {m.strength}</span>
                            </span>
                            {i.status === 'taken' && <span className="mono" style={{fontSize:11, color:'var(--ink-muted)'}}>{i.takenAt}</span>}
                          </button>
                        );
                      })}
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          <div style={{padding:'4px 18px 16px', display:'flex', gap: 8, alignItems:'center', color:'var(--ink-faint)', fontSize:11}}>
            <Icon name="info" size={12}/> Tap a slot to see individual medicines. Off-schedule doses logged separately.
          </div>
        </div>

        <div className="mt-card">
          <div className="mt-card__head">
            <div>
              <div className="mt-card__title">Active regimens</div>
              <div className="mt-card__sub"><span className="num">{REGS_S.length}</span> configured</div>
            </div>
          </div>
          <div style={{padding:'4px 18px 16px'}}>
            {REGS_S.map(r => (
              <div key={r.id} className="sched-regimen">
                <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8}}>
                  <div>
                    <div style={{fontWeight:500, fontSize:13, color:'var(--ink-strong)'}}>Aeri's {r.name}</div>
                    <div style={{fontSize:11, color:'var(--ink-muted)'}}>{r.time} · {r.freq}</div>
                  </div>
                  <span className="mt-pill mt-pill--brand">Active</span>
                </div>
                <div style={{display:'flex', flexWrap:'wrap', gap: 4}}>
                  {r.items.map(it => {
                    const m = MED_S[it.medId];
                    return (
                      <span key={it.medId} className="mt-pill mt-pill--ghost" style={{fontSize:10}}>
                        <span style={{background:'var(--viz-'+m.color+')', width:6, height:6, borderRadius:3, display:'inline-block', marginRight:2}}/>
                        {m.name}
                      </span>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

window.SchedulePage = SchedulePage;
