/* global React, Button */
// ============================================================================
// notes.jsx — the one way to add things anywhere on Today (026).
// NoteChip: a note on its row (task ☐, note 💬, test 📝, homework ☐, bring 🎒; 🔒 = parents only).
// NoteSheet: the bottom sheet to add or edit a note. What you tapped decides what it is attached to:
//   a class (lesson), a plan item, a sports session (schedule), a block, or the day.
// ============================================================================
(() => {
  const { useState, useEffect } = React;
  const A = () => window.PlanAPI;
  const DAY_SHORT = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  const short = (d) => `${DAY_SHORT[A().weekday(d)]} ${Number(d.slice(8, 10))}`;

  const KIND = {
    task: { icon: '☐', label: 'Task', tick: true },
    note: { icon: '💬', label: 'Note' },
    test: { icon: '📝', label: 'Test', color: 'var(--danger)' },
    handin: { icon: '☐', label: 'Homework', tick: true },
    bring: { icon: '🎒', label: 'Bring', tick: true },
  };
  const SCHOOL_KINDS = ['handin', 'test', 'bring', 'note', 'task'];
  const OTHER_KINDS = ['task', 'note', 'bring'];

  function NoteChip({ n, canWrite, onToggle, onEdit }) {
    const k = KIND[n.kind] || KIND.note;
    const canTick = k.tick && canWrite;
    return (
      <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start', fontSize: 13, marginTop: 4, padding: n.parents_only ? '3px 6px' : 0,
                    borderRadius: 6, background: n.parents_only ? 'var(--warning-tint)' : 'transparent',
                    color: k.color || 'var(--fg)', opacity: n.done ? 0.55 : 1 }}>
        {canTick
          ? <button onClick={() => onToggle(n)} aria-label={n.done ? 'Done' : 'Mark done'}
              style={{ all: 'unset', cursor: 'pointer', width: 16, textAlign: 'center', flexShrink: 0 }}>{n.done ? '☑' : '☐'}</button>
          : <span style={{ width: 16, textAlign: 'center', flexShrink: 0 }}>{k.icon}</span>}
        <button onClick={() => onEdit && onEdit(n)} disabled={!onEdit} style={{ all: 'unset', cursor: onEdit ? 'pointer' : 'default', flex: 1,
                  minWidth: 0, overflowWrap: 'anywhere', textDecoration: n.done ? 'line-through' : 'none' }}>
          {n.kind !== 'note' && n.kind !== 'task' && <strong style={{ fontWeight: 600 }}>{k.label}: </strong>}
          {n.anchor_type !== 'lesson' && n.subject ? `${n.subject} — ` : ''}{n.text}
          {n.parents_only && <span title="Parents only"> 🔒</span>}
          {n.carriedFrom && <span style={{ color: 'var(--warning)', fontSize: 12 }}> · from {short(n.carriedFrom)}</span>}
        </button>
      </div>
    );
  }

  function NoteList({ notes, canWrite, onToggle, onEdit, indent }) {
    if (!notes || !notes.length) return null;
    return <div style={{ padding: indent ? '0 0 6px 56px' : '2px 0 6px' }}>
      {notes.map(n => <NoteChip key={n.id + (n.carriedFrom || '')} n={n} canWrite={canWrite} onToggle={onToggle} onEdit={onEdit} />)}
    </div>;
  }

  // anchor: { type, ref, label, block, subject?, classes? (today's class names, for the School block's +) }
  function NoteSheet({ anchor, note, day, memberDb, isAdmin, onClose, onSaved }) {
    const editing = !!note;
    const schoolish = anchor.type === 'lesson' || (anchor.type === 'block' && anchor.ref === 'school');
    const kinds = schoolish ? SCHOOL_KINDS : OTHER_KINDS;
    const [kind, setKind] = useState(note ? note.kind : (schoolish ? 'handin' : 'task'));
    const [subject, setSubject] = useState(note ? note.subject || '' : anchor.subject || '');
    const [text, setText] = useState(note ? note.text : '');
    const [date, setDate] = useState(note ? note.day : day);
    const [dateTouched, setDateTouched] = useState(editing);
    const [priv, setPriv] = useState(note ? !!note.parents_only : false);
    const [busy, setBusy] = useState(false);
    const [err, setErr] = useState(null);

    // Homework and tests default to the next time that class is on his timetable
    useEffect(() => {
      if (dateTouched || !subject || !['handin', 'test'].includes(kind)) { if (!dateTouched) setDate(day); return; }
      let live = true;
      A().nextLessonDay(memberDb, subject, day).then(d => { if (live && d) setDate(d); });
      return () => { live = false; };
    }, [kind, subject]);

    async function save() {
      setBusy(true); setErr(null);
      const lessonAnchor = schoolish && subject;
      const row = {
        kind, text: text.trim(), day: date, parents_only: isAdmin ? priv : false,
        anchor_type: lessonAnchor ? 'lesson' : anchor.type, anchor_ref: lessonAnchor ? subject : anchor.ref,
        subject: lessonAnchor ? subject : (anchor.subject || null), block: anchor.block || null,
      };
      try {
        if (editing) await A().notes.update(note.id, row); else await A().notes.add(memberDb, row);
        onSaved(); onClose();
      } catch (e) { setErr(/relation .*note|does not exist|schema cache/i.test(e.message) ? 'Notes need migration 026 in the database first.' : e.message); }
      finally { setBusy(false); }
    }
    async function del() {
      if (!confirm('Remove this?')) return;
      try { await A().notes.remove(note); onSaved(); onClose(); } catch (e) { setErr(e.message); }
    }

    const inp = { padding: '10px 12px', border: '1px solid var(--border-strong)', borderRadius: 8, fontSize: 16, width: '100%',
      boxSizing: 'border-box', background: 'var(--bg-raised)', color: 'var(--fg)', fontFamily: 'var(--font-sans)' };
    const placeholder = { task: 'What needs doing?', note: 'The note (room change, bring your laptop…)', test: 'What is it on? (chapter 3…)',
      handin: 'What to do (page 34, essay…)', bring: 'What? (skates, picnic lunch, signed form…)' }[kind];
    return (
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 100, background: 'rgba(10,10,12,0.35)', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
        <div onClick={e => e.stopPropagation()} style={{ width: '100%', maxWidth: 640, background: 'var(--bg)', borderRadius: '16px 16px 0 0',
              padding: '14px 16px calc(16px + env(safe-area-inset-bottom))', boxShadow: 'var(--shadow-3)', fontFamily: 'var(--font-sans)' }}>
          <div style={{ width: 36, height: 4, borderRadius: 2, background: 'var(--ink-200)', margin: '0 auto 12px' }} />
          <div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{editing ? 'Edit' : 'Add to'}</div>
          <div style={{ fontSize: 17, fontWeight: 500, marginBottom: 12 }}>{anchor.label}</div>

          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {kinds.map(k => <Button key={k} size="sm" kind={kind === k ? 'primary' : 'secondary'} onClick={() => setKind(k)}>{KIND[k].label}</Button>)}
          </div>

          {anchor.type === 'block' && anchor.ref === 'school' && anchor.classes && anchor.classes.length > 0 && (
            <div style={{ marginTop: 10 }}>
              <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginBottom: 4 }}>Which class?</div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {anchor.classes.map(c => <Button key={c} size="sm" kind={subject === c ? 'primary' : 'ghost'} onClick={() => setSubject(subject === c ? '' : c)}>{c}</Button>)}
              </div>
            </div>
          )}

          <input autoFocus style={{ ...inp, marginTop: 12 }} value={text} onChange={e => setText(e.target.value)} placeholder={placeholder}
                 onKeyDown={e => { if (e.key === 'Enter' && text.trim()) save(); }} />

          <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginTop: 10, flexWrap: 'wrap' }}>
            <label style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{kind === 'handin' ? 'Due' : kind === 'test' ? 'Test day' : 'For'}</label>
            <input type="date" value={date} onChange={e => { setDate(e.target.value); setDateTouched(true); }} style={{ ...inp, width: 170, fontSize: 15 }} />
            {isAdmin && (
              <label style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 13, marginLeft: 'auto', cursor: 'pointer' }}>
                <input type="checkbox" checked={priv} onChange={e => setPriv(e.target.checked)} /> 🔒 Parents only
              </label>
            )}
          </div>
          {(kind === 'handin' || kind === 'test') && subject && !dateTouched && (
            <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>The next {subject} class. {kind === 'test' ? 'Revision shows up five days before.' : ''}</div>
          )}
          {kind === 'task' && <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>Not ticked? It moves to the next day until it's done.</div>}

          {err && <div style={{ color: 'var(--danger)', fontSize: 13, marginTop: 8 }}>{err}</div>}
          <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
            <Button disabled={busy || !text.trim() || !date} onClick={save}>{editing ? 'Save' : 'Add'}</Button>
            <Button kind="ghost" onClick={onClose}>Cancel</Button>
            {editing && <div style={{ marginLeft: 'auto' }}><Button kind="ghost" onClick={del}>Remove</Button></div>}
          </div>
        </div>
      </div>
    );
  }

  window.NoteChip = NoteChip;
  window.NoteList = NoteList;
  window.NoteSheet = NoteSheet;
})();
