/* global React, Card, Button, Pill, Eyebrow */
// ============================================================================
// School card on Today (024): what to bring, tests, what to hand in, the day's lessons,
// homework after school, and what to pack for tomorrow. Data: PlanAPI.getSchoolDay.
// The first time, it asks the boy which group he is in, by a lesson he recognises.
// ============================================================================
(() => {
  const { useState, useEffect, useCallback } = React;
  const A = () => window.PlanAPI;
  const hm = (t) => (t ? String(t).slice(0, 5) : '');
  const DAY_SHORT = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  const dueLabel = (d, day) => {
    if (d === A().addDays(day, 1)) return 'tomorrow';
    return DAY_SHORT[A().weekday(d)] + ' ' + Number(d.slice(8, 10));
  };
  const muted = { fontSize: 13, color: 'var(--fg-muted)' };
  const inp = { padding: '8px 10px', border: '1px solid var(--border-strong)', borderRadius: 6, fontSize: 15, minWidth: 0,
    background: 'var(--bg-raised)', color: 'var(--fg)', fontFamily: 'var(--font-sans)', boxSizing: 'border-box' };

  function Tick({ on, onClick, disabled }) {
    return (
      <button onClick={onClick} disabled={disabled} aria-label={on ? 'Done' : 'Not done'} style={{
        width: 22, height: 22, flexShrink: 0, borderRadius: 6, cursor: disabled ? 'default' : 'pointer',
        border: `1.5px solid ${on ? 'var(--success)' : 'var(--border-strong)'}`, background: on ? 'var(--success)' : 'transparent',
        color: '#fff', fontSize: 13, lineHeight: '18px', padding: 0,
      }}>{on ? '✓' : ''}</button>
    );
  }

  function Section({ label, color, children }) {
    return (
      <div style={{ marginTop: 12 }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase',
                      color: color || 'var(--fg-subtle)', marginBottom: 4 }}>{label}</div>
        {children}
      </div>
    );
  }

  function Line({ children, done }) {
    return <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '5px 0', fontSize: 15,
      color: done ? 'var(--fg-muted)' : 'var(--fg)', textDecoration: done ? 'line-through' : 'none', overflowWrap: 'anywhere' }}>{children}</div>;
  }

  // One-time: which group is he in? Options are named by a lesson he can recognise.
  function GroupQuestions({ s, memberDb, onSaved }) {
    const [err, setErr] = useState(null);
    async function pick(key, v) {
      try { await A().setSchoolChoice(memberDb, key, v); onSaved(); } catch (e) { setErr(e.message); }
    }
    return (
      <div style={{ marginTop: 10, padding: 12, background: 'var(--signal-tint, var(--ink-50))', borderRadius: 8 }}>
        <div style={{ fontSize: 14, fontWeight: 500 }}>Set up your timetable (once)</div>
        <div style={{ ...muted, marginTop: 2 }}>Your class is split into groups. Answer and you only see your own lessons.</div>
        {s.missing.map(q => (
          <div key={q.key} style={{ marginTop: 10 }}>
            <div style={{ fontSize: 14 }}>{q.q}</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 6 }}>
              {q.opts.map(([v, label]) => <Button key={v} size="sm" kind="secondary" onClick={() => pick(q.key, v)}>{label}</Button>)}
            </div>
          </div>
        ))}
        {err && <div style={{ color: 'var(--danger)', fontSize: 13, marginTop: 6 }}>{err}</div>}
      </div>
    );
  }

  // What an item looks like on its class row
  const CHIP = {
    test: { icon: '📝', label: 'Test', color: 'var(--danger)' },
    homework: { icon: '✅', label: 'Hand in', color: 'var(--fg)' },
    deadline: { icon: '✅', label: 'Hand in', color: 'var(--fg)' },
    bring: { icon: '🎒', label: 'Bring', color: 'var(--fg)' },
    note: { icon: '💬', label: 'Note', color: 'var(--fg-muted)' },
  };
  function ItemChip({ i, canWrite, onToggle }) {
    const c = CHIP[i.kind] || CHIP.note;
    const tickable = ['homework', 'deadline', 'bring'].includes(i.kind);
    return (
      <div style={{ display: 'flex', gap: 6, alignItems: 'flex-start', fontSize: 13, marginTop: 3, color: c.color,
                    textDecoration: i.done ? 'line-through' : 'none', opacity: i.done ? 0.6 : 1 }}>
        {tickable && canWrite
          ? <button onClick={() => onToggle(i)} aria-label={i.done ? 'Done' : 'Mark done'} style={{ all: 'unset', cursor: 'pointer', width: 16, textAlign: 'center' }}>{i.done ? '☑' : '☐'}</button>
          : <span style={{ width: 16, textAlign: 'center' }}>{c.icon}</span>}
        <span style={{ overflowWrap: 'anywhere' }}><strong style={{ fontWeight: 600 }}>{c.label}:</strong> {i.title || i.subject}</span>
      </div>
    );
  }

  // The school block in Today's timeline: the day's classes, each with its own test / hand-in / bring / note.
  function SchoolBlock({ s, isToday, canWrite, onToggle, memberDb, day, reload, children, onAdd, onEdit }) {
    const classes = [...new Set(s.lessons.filter(l => !l.alt && !['Mentor', 'Lasstund', 'Studiev', 'Vardegrund'].includes(l.subject)).map(l => l.name))];
    const NL = window.NoteList;
    const now = new Date(), nowHm = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
    return (
      <div style={{ border: '1px solid var(--border)', borderLeft: '3px solid var(--signal)', borderRadius: 8, marginBottom: 8,
                    background: 'var(--bg-raised)', padding: '10px 12px' }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'baseline' }}>
          <div style={{ width: 44, fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-muted)' }}>{s.start}</div>
          <div style={{ flex: 1, fontSize: 15, fontWeight: 500 }}>School <span style={{ ...muted, fontWeight: 400 }}>until {s.end}</span></div>
          {canWrite && onAdd && <button onClick={() => onAdd({ type: 'block', ref: 'school', block: 'school', label: 'School', classes })} aria-label="Add to School"
            style={{ all: 'unset', cursor: 'pointer', width: 28, height: 28, borderRadius: 14, textAlign: 'center', lineHeight: '28px', fontSize: 20,
                     color: 'var(--signal)', border: '1px solid var(--border)' }}>+</button>}
        </div>
        {canWrite && s.missing.length > 0 && <GroupQuestions s={s} memberDb={memberDb} onSaved={reload} />}
        <div style={{ marginTop: 6 }}>
          {s.lessons.map(l => {
            const current = isToday && !l.alt && hm(l.start_time) <= nowHm && nowHm < hm(l.end_time);
            const autoBring = l.bring && !l.alt;
            return (
              <div key={l.id} onClick={() => canWrite && !l.alt && onAdd && onAdd({ type: 'lesson', ref: l.name, subject: l.name, block: 'school', label: `${l.name} · ${hm(l.start_time)}` })}
                   style={{ cursor: canWrite && !l.alt ? 'pointer' : 'default', display: 'flex', gap: 12, padding: '5px 6px', margin: '0 -6px', borderRadius: 6,
                    borderTop: '1px solid var(--border)', background: current ? 'var(--signal-tint, var(--ink-50))' : 'transparent',
                    opacity: l.alt ? 0.5 : 1 }}>
                <div style={{ width: 44, fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-muted)', paddingTop: 2 }}>{hm(l.start_time)}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
                    <span style={{ flex: 1, fontSize: 14, fontWeight: current ? 600 : 400 }}>
                      {l.name}{l.alt ? <span style={muted}> (or)</span> : null}
                    </span>
                    <span style={{ ...muted, fontSize: 12, flexShrink: 0 }}>{[l.room, `ends ${hm(l.end_time)}`].filter(Boolean).join(' · ')}</span>
                  </div>
                  {autoBring && <div style={{ fontSize: 13, marginTop: 3 }}>🎒 <strong style={{ fontWeight: 600 }}>Bring:</strong> {l.bring}</div>}
                  <div onClick={e => e.stopPropagation()}>{NL && <NL notes={l.items} canWrite={canWrite} onToggle={onToggle} onEdit={onEdit} />}</div>
                </div>
              </div>
            );
          })}
          {(s.unmatched.length > 0 || s.notes.length > 0) && (
            <div style={{ borderTop: '1px solid var(--border)', paddingTop: 6, marginTop: 2 }}>
              <div style={{ ...muted, fontSize: 12 }}>For school today</div>
              {NL && <NL notes={[...s.notes, ...s.unmatched.map(n => ({ ...n, anchor_type: 'x' }))]} canWrite={canWrite} onToggle={onToggle} onEdit={onEdit} />}
            </div>
          )}
          {children}
        </div>
      </div>
    );
  }

  // Pieces the other day blocks show: what to pack this morning, homework due soon, pack for tomorrow
  function MorningPack({ s, canWrite, onToggle }) {
    if (!s || !s.schoolDay || !s.bring.length) return null;
    return (
      <Section label="Pack for school">
        {s.bring.map((b, n) => b.auto
          ? <Line key={'a' + n}><span>🎒</span><span>{b.what} <span style={muted}>· {b.why}</span></span></Line>
          : <Line key={b.id} done={b.done}><Tick on={b.done} disabled={!canWrite} onClick={() => onToggle(b.item)} /><span>{b.what}</span></Line>)}
      </Section>
    );
  }
  function DueSoon({ s, day, canWrite, onToggle }) {
    if (!s || !s.todo || !s.todo.length) return null;
    return (
      <Section label="Homework due soon">
        {s.todo.map(i => (
          <Line key={(i.revise ? 'r' : '') + i.id} done={!i.revise && i.done}>
            {i.revise ? <span style={{ width: 22, textAlign: 'center' }}>📖</span> : <Tick on={i.done} disabled={!canWrite} onClick={() => onToggle(i)} />}
            <span style={{ flex: 1 }}>
              {i.revise ? <>Revise for the <strong>{i.subject}</strong> test{i.title ? ` (${i.title})` : ''}</> : <><strong>{i.subject}</strong>{i.title ? ` — ${i.title}` : ''}</>}
              <span style={muted}> · {i.revise ? 'test' : 'due'} {dueLabel(i.due_on, day)}</span>
            </span>
          </Line>
        ))}
      </Section>
    );
  }
  function PackTomorrow({ tomorrow, day }) {
    if (!tomorrow || !tomorrow.schoolDay || (!tomorrow.bring.length && !tomorrow.tests.length)) return null;
    return (
      <Section label={`Pack for ${tomorrow.day === A().addDays(day, 1) ? 'tomorrow' : DAY_SHORT[A().weekday(tomorrow.day)]}`}>
        {tomorrow.bring.map((b, n) => <Line key={n}>🎒 {b.what}</Line>)}
        {tomorrow.tests.map(t => <Line key={t.id}>📝 Test: <strong>{t.subject}</strong>{t.title ? ` — ${t.title}` : ''}</Line>)}
      </Section>
    );
  }

  function AddSchoolItem({ memberDb, day, subjects, onSaved }) {
    const [open, setOpen] = useState(false);
    const [f, setF] = useState({ kind: 'homework', subject: '', title: '', due_on: A().nextSchoolDay(day) });
    const [err, setErr] = useState(null);
    if (!open) return <button onClick={() => setOpen(true)} style={{ background: 'none', border: 'none', color: 'var(--signal)',
      cursor: 'pointer', fontSize: 14, padding: '8px 0 0', fontFamily: 'var(--font-sans)', textAlign: 'left', display: 'block' }}>+ Add a test, homework or something to bring</button>;
    async function save() {
      setErr(null);
      try {
        await A().school.add(memberDb, { kind: f.kind, subject: f.subject.trim() || '—', title: f.title.trim(), due_on: f.due_on });
        setOpen(false); setF({ ...f, subject: '', title: '' }); onSaved();
      } catch (e) { setErr(e.message); }
    }
    const kinds = [['homework', 'Homework'], ['test', 'Test'], ['bring', 'Bring'], ['note', 'Note']];
    return (
      <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--border)' }}>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {kinds.map(([v, l]) => <Button key={v} size="sm" kind={f.kind === v ? 'primary' : 'secondary'} onClick={() => setF({ ...f, kind: v })}>{l}</Button>)}
        </div>
        {(
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 8 }}>
            {subjects.map(sub => <Button key={sub} size="sm" kind={f.subject === sub ? 'primary' : 'ghost'} onClick={() => setF({ ...f, subject: sub })}>{sub}</Button>)}
          </div>
        )}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 150px', gap: 6, marginTop: 8 }}>
          <input style={inp} value={f.title} onChange={e => setF({ ...f, title: e.target.value })}
            placeholder={f.kind === 'bring' ? 'What? (picnic lunch, fruit, signed form…)' : f.kind === 'test' ? 'What is it on? (chapter 3…)' : f.kind === 'note' ? 'The note (bring your laptop, room change…)' : 'What to do (page 34, essay…)'} />
          <input style={inp} type="date" value={f.due_on} onChange={e => setF({ ...f, due_on: e.target.value })} />
        </div>
        <div style={{ ...muted, fontSize: 12, marginTop: 4 }}>
          {f.kind === 'bring' ? 'The day to bring it. Pick a subject to pin it to that class.' : f.kind === 'test' ? 'The day of the test. It shows on that class, and revision shows up five days before.' : f.kind === 'note' ? 'The day it is for. Pick a subject to pin it to that class.' : 'The day it has to be handed in or reported. It shows on that class.'}
        </div>
        {err && <div style={{ color: 'var(--danger)', fontSize: 13, marginTop: 6 }}>{err}</div>}
        <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
          <Button size="sm" disabled={!f.title.trim() || !f.due_on} onClick={save}>Save</Button>
          <Button size="sm" kind="ghost" onClick={() => setOpen(false)}>Cancel</Button>
        </div>
      </div>
    );
  }

  // The card under the check-in: set-up, what to pack this morning, homework after school,
  // pack for tomorrow, and + Add. The classes themselves are in the timeline (SchoolBlock).
  function SchoolCard({ s, tomorrow, reload, memberDb, day, canWrite, isToday }) {
    const [err, setErr] = useState(null);
    if (!s) return null;
    const toggle = async (i) => { try { await A().school.toggle(i.id, !i.done); reload(); } catch (e) { setErr(e.message); } };
    const packNext = tomorrow && tomorrow.schoolDay && (tomorrow.bring.length > 0 || tomorrow.tests.length > 0);

    if (!s.schoolDay) {
      if (s.holiday && s.holiday.kind === 'travel') return (
        <Card pad={14} style={{ marginTop: 12 }}>
          <Eyebrow>School · {s.holiday.label}</Eyebrow>
          {s.holiday.note && <div style={{ fontSize: 14, marginTop: 6, lineHeight: 1.5 }}>{s.holiday.note}</div>}
        </Card>
      );
      if (!packNext || !isToday) return null;
      return (
        <Card pad={14} style={{ marginTop: 12 }}>
          <Eyebrow>School {s.holiday ? `· ${s.holiday.label}` : ''}</Eyebrow>
          <Section label={`Pack for ${DAY_SHORT[A().weekday(tomorrow.day)]}`}>
            {tomorrow.bring.map((b, n) => <Line key={n}>🎒 {b.what}</Line>)}
            {tomorrow.tests.map(t => <Line key={t.id}>📝 Test: <strong>{t.subject}</strong>{t.title ? ` — ${t.title}` : ''}</Line>)}
          </Section>
        </Card>
      );
    }

    // Today's subjects first, then the rest of the core list, so anything can be added for any subject
    const CORE = ['Maths', 'Swedish', 'English', 'Science', 'Social studies', 'Spanish', 'French', 'German', 'Art', 'Music', 'Crafts', 'Home economics', 'PE'];
    const todays = s.lessons.filter(l => !l.alt && !['Mentor', 'Lasstund', 'Studiev', 'Vardegrund'].includes(l.subject)).map(l => l.name);
    const subjects = [...new Set([...todays, ...CORE])];
    const afternoon = isToday && new Date().getHours() >= 13;
    const testsToday = s.lessons.flatMap(l => (l.items || []).filter(i => i.kind === 'test').map(i => ({ ...i, at: hm(l.start_time) })))
      .concat(s.unmatched.filter(i => i.kind === 'test'));
    return (
      <Card pad={16} style={{ marginTop: 12 }}>
        <Eyebrow>School today</Eyebrow>
        {canWrite && s.missing.length > 0 && <GroupQuestions s={s} memberDb={memberDb} onSaved={reload} />}

        {testsToday.length > 0 && (
          <Section label="Test today" color="var(--danger)">
            {testsToday.map(t => <Line key={t.id}><span>📝</span><span><strong>{t.subject}</strong>{t.title ? ` — ${t.title}` : ''}{t.at ? <span style={muted}> · {t.at}</span> : null}</span></Line>)}
          </Section>
        )}

        {s.bring.length > 0 && (
          <Section label="Pack this morning">
            {s.bring.map((b, n) => b.auto
              ? <Line key={'a' + n}><span>🎒</span><span>{b.what} <span style={muted}>· {b.why}</span></span></Line>
              : <Line key={b.id} done={b.done}><Tick on={b.done} disabled={!canWrite} onClick={() => toggle(b.item)} /><span>{b.what}</span></Line>)}
          </Section>
        )}

        <Section label="Homework after school">
          {s.todo.length === 0
            ? <div style={{ ...muted, padding: '4px 0' }}>Nothing entered. Check Unikum and Classroom, and add what's coming.</div>
            : s.todo.map(i => (
              <Line key={(i.revise ? 'r' : '') + i.id} done={!i.revise && i.done}>
                {i.revise ? <span style={{ width: 22, textAlign: 'center' }}>📖</span> : <Tick on={i.done} disabled={!canWrite} onClick={() => toggle(i)} />}
                <span style={{ flex: 1 }}>
                  {i.revise ? <>Revise for the <strong>{i.subject}</strong> test{i.title ? ` (${i.title})` : ''}</> : <><strong>{i.subject}</strong>{i.title ? ` — ${i.title}` : ''}</>}
                  <span style={muted}> · {i.revise ? 'test' : 'due'} {dueLabel(i.due_on, day)}</span>
                </span>
              </Line>
            ))}
        </Section>

        {afternoon && packNext && (
          <Section label={`Pack for ${tomorrow.day === A().addDays(day, 1) ? 'tomorrow' : DAY_SHORT[A().weekday(tomorrow.day)]}`}>
            {tomorrow.bring.map((b, n) => <Line key={n}>🎒 {b.what}</Line>)}
            {tomorrow.tests.map(t => <Line key={t.id}>📝 Test: <strong>{t.subject}</strong>{t.title ? ` — ${t.title}` : ''}</Line>)}
          </Section>
        )}

        {err && <div style={{ color: 'var(--danger)', fontSize: 13, marginTop: 6 }}>{err}</div>}
        {canWrite && <AddSchoolItem memberDb={memberDb} day={day} subjects={subjects} onSaved={reload} />}
      </Card>
    );
  }

  window.SchoolCard = SchoolCard;
  window.SchoolBlock = SchoolBlock;
  window.SchoolParts = { MorningPack, DueSoon, PackTomorrow };
})();
