// screens-comms.jsx — Parent communications surface
// 1. TeacherAnnouncementComposeScreen — broadcast to a class/section/all parents
// 2. TeacherPTMScheduleScreen — PTM slot board (parents pick a 10-min window)
// 3. TeacherParentMessageThreadScreen — per-student parent thread with auto-context

const { useState: useStateCM, useMemo: useMemoCM } = React;

// ─────────────────────────────────────────────────────────────
// 1. Compose announcement
// ─────────────────────────────────────────────────────────────
function TeacherAnnouncementComposeScreen({ nav, params }) {
  const initialCls = (params && params.cls) || '8-B';
  const [audience, setAudience] = useStateCM(initialCls); // class id or 'all-parents'
  const [channels, setChannels] = useStateCM(() => new Set(['inapp', 'whatsapp']));
  const [title, setTitle] = useStateCM('');
  const [body, setBody] = useStateCM('');
  const [schedule, setSchedule] = useStateCM('now'); // 'now' | 'pick'
  const [when, setWhen] = useStateCM('2025-03-13T08:30');
  const [savedToast, setSavedToast] = useStateCM(false);

  const toggleCh = (id) => setChannels(s => {
    const n = new Set(s);
    if (n.has(id)) n.delete(id); else n.add(id);
    return n;
  });

  const audienceCounts = {
    '8-B': { name: 'Class 8-B parents', n: 32 },
    '9-A': { name: 'Class 9-A parents', n: 28 },
    '10-C': { name: 'Class 10-C parents', n: 30 },
    'all': { name: 'All my classes', n: 90 },
  };
  const aud = audienceCounts[audience];

  const templates = [
    { id: 't1', title: 'Homework reminder', body: 'Reminder: Algebra Ex. 7.3 is due tomorrow. Please ensure your child completes it.' },
    { id: 't2', title: 'Class test next week', body: 'A class test on Linear Equations is scheduled for Mon 17 Mar. Syllabus: Ch. 7.1 to 7.3.' },
    { id: 't3', title: 'PTM reminder', body: 'PTM is scheduled this Saturday. Please book a slot in the app.' },
    { id: 't4', title: 'Custom — write my own', body: '' },
  ];

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title="New announcement" onBack={() => nav.pop()}/>
      <div className="app-body" style={{ paddingTop: 4 }}>

        {/* Audience */}
        <FieldT label="Send to" required>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {Object.entries(audienceCounts).map(([id, c]) => (
              <button key={id} onClick={() => setAudience(id)} style={{
                padding: '8px 14px', borderRadius: 10,
                background: audience === id ? 'var(--p600)' : '#fff',
                color: audience === id ? '#fff' : 'var(--n700)',
                border: audience === id ? '1px solid var(--p600)' : '1px solid var(--n200)',
                fontSize: 12, fontWeight: 700,
              }}>{c.name} <span style={{ fontWeight: 500, opacity: .7 }}>· {c.n}</span></button>
            ))}
          </div>
        </FieldT>

        {/* Templates */}
        <FieldT label="Quick template">
          <div className="col" style={{ gap: 6 }}>
            {templates.map(t => (
              <button key={t.id} onClick={() => { setTitle(t.title); setBody(t.body); }} className="card row" style={{ padding: 10, gap: 10, background: '#fff', textAlign: 'left' }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--p50)', color: 'var(--p600)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name="megaphone" size={14}/></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)' }}>{t.title}</div>
                  {t.body && <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.body}</div>}
                </div>
              </button>
            ))}
          </div>
        </FieldT>

        {/* Compose */}
        <FieldT label="Title" required>
          <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. PTM this Saturday" style={{
            width: '100%', height: 44, padding: '0 12px', borderRadius: 12,
            border: '1px solid var(--n200)', background: '#fff', fontSize: 14, fontWeight: 600, fontFamily: 'inherit',
          }}/>
        </FieldT>

        <FieldT label="Message" required>
          <textarea value={body} onChange={(e) => setBody(e.target.value)} rows={5} placeholder="Keep it under 500 chars for SMS friendliness…" style={{
            width: '100%', padding: 12, borderRadius: 12, border: '1px solid var(--n200)',
            fontSize: 13, fontFamily: 'inherit', resize: 'none',
          }}/>
          <div style={{ fontSize: 10.5, color: 'var(--n500)', marginTop: 4, fontFamily: 'var(--mono)', textAlign: 'right' }}>{body.length}/500</div>
        </FieldT>

        {/* Channels */}
        <FieldT label="Channels">
          <ListCard>
            {[
              { id: 'inapp', ic: 'bell', lab: 'In-app notification', sub: `${aud.n} parents · instant` },
              { id: 'whatsapp', ic: 'whatsapp', lab: 'WhatsApp', sub: 'Most reliable for India · ~₹0.30 each' },
              { id: 'sms', ic: 'phone', lab: 'SMS fallback', sub: 'Only when WhatsApp delivery fails' },
              { id: 'email', ic: 'mail', lab: 'Email digest', sub: 'Daily roll-up at 7 PM' },
            ].map((ch, i, a) => (
              <ToggleRow key={ch.id} ic={ch.ic} lab={ch.lab} sub={ch.sub} value={channels.has(ch.id)} onChange={() => toggleCh(ch.id)} last={i === a.length - 1}/>
            ))}
          </ListCard>
        </FieldT>

        {/* Schedule */}
        <FieldT label="When">
          <div className="row" style={{ gap: 6, marginBottom: schedule === 'pick' ? 8 : 0 }}>
            {[{ id: 'now', lab: 'Send now' }, { id: 'pick', lab: 'Schedule…' }].map(s => (
              <button key={s.id} onClick={() => setSchedule(s.id)} style={{
                flex: 1, padding: '10px 10px', borderRadius: 10,
                background: schedule === s.id ? 'var(--n900)' : '#fff',
                color: schedule === s.id ? '#fff' : 'var(--n700)',
                fontSize: 12, fontWeight: 700,
                border: '1px solid var(--n100)',
              }}>{s.lab}</button>
            ))}
          </div>
          {schedule === 'pick' && (
            <input type="datetime-local" value={when} onChange={(e) => setWhen(e.target.value)} style={{
              width: '100%', height: 44, padding: '0 12px', borderRadius: 12,
              border: '1px solid var(--n200)', background: '#fff', fontSize: 13, fontFamily: 'inherit',
            }}/>
          )}
        </FieldT>

        <button onClick={() => { setSavedToast(true); setTimeout(() => { setSavedToast(false); nav.pop(); }, 1100); }}
          disabled={!title.trim() || !body.trim() || channels.size === 0}
          className="btn-primary" style={{ height: 48, width: '100%', marginTop: 8 }}>
          <Icon name="send" size={14}/> {schedule === 'now' ? `Send to ${aud.n} parents` : 'Schedule'}
        </button>
        <div style={{ fontSize: 10.5, color: 'var(--n500)', marginTop: 8, lineHeight: 1.45, padding: '0 4px' }}>
          School policy: Class teachers can broadcast directly. HOD approval required for cross-class messages.
        </div>
      </div>

      {savedToast && (
        <div style={{ position: 'absolute', bottom: 32, left: 16, right: 16, background: 'var(--n900)', color: '#fff', padding: '12px 14px', borderRadius: 12, fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 10, boxShadow: '0 12px 32px rgba(0,0,0,.25)', zIndex: 70 }}>
          <Icon name="check" size={16} style={{ color: 'var(--success)' }}/> Announcement queued · {channels.size} channel{channels.size === 1 ? '' : 's'}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 2. PTM schedule
// ─────────────────────────────────────────────────────────────
function TeacherPTMScheduleScreen({ nav, params }) {
  const [date, setDate] = useStateCM('Sat · 22 Mar');
  // 8:30am to 1pm in 15-min slots — but visual cap to keep it readable
  const slotTimes = useMemoCM(() => {
    const out = [];
    for (let h = 9; h < 13; h++) {
      ['00','15','30','45'].forEach(m => out.push(`${h}:${m}`));
    }
    return out;
  }, []);
  // Mock bookings: roll number → slot index
  const bookings = useMemoCM(() => {
    const map = new Map();
    [
      [1, 0, 'Aarav Reddy'], [2, 1, 'Diya Nair'], [4, 4, 'Vihaan Iyer'],
      [5, 5, 'Riya Shah'], [7, 7, 'Ananya Verma'], [9, 8, 'Meera Krishnan'],
      [11, 10, 'Saanvi Joshi'], [12, 11, 'Aditya Das'], [13, 12, 'Ishaan Pillai'],
      [15, 13, 'Zoya Khan'], [17, 14, 'Nikhil Gupta'], [18, 15, 'Avni Rao'],
    ].forEach(([roll, slot, name]) => map.set(slot, { roll, name }));
    return map;
  }, []);
  const totalParents = 32;
  const booked = bookings.size;

  const [picked, setPicked] = useStateCM(null);

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <NavHeader title="PTM · Class 8-B" onBack={() => nav.pop()}
        right={<button onClick={() => nav.push('teachAnnouncementCompose', { cls: '8-B' })} style={{ height: 32, padding: '0 12px', borderRadius: 8, background: 'var(--p50)', color: 'var(--p600)', fontSize: 11, fontWeight: 700, fontFamily: 'var(--mono)', letterSpacing: '.04em' }}>REMIND</button>}/>

      <div className="app-body" style={{ paddingTop: 4 }}>
        {/* Summary */}
        <div className="card" style={{ padding: 14, background: '#fff', marginBottom: 12 }}>
          <div className="spread">
            <div>
              <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--n500)', textTransform: 'uppercase', letterSpacing: '.08em', fontFamily: 'var(--mono)' }}>{date} · 9:00 AM – 1:00 PM</div>
              <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--n900)', marginTop: 2 }}>{booked} of {totalParents} booked</div>
            </div>
            <div style={{ width: 56, height: 56, position: 'relative' }}>
              <svg width="56" height="56" viewBox="0 0 56 56" style={{ transform: 'rotate(-90deg)' }}>
                <circle cx="28" cy="28" r="24" fill="none" stroke="var(--n100)" strokeWidth="6"/>
                <circle cx="28" cy="28" r="24" fill="none" stroke="var(--p600)" strokeWidth="6"
                  strokeLinecap="round" strokeDasharray="151" strokeDashoffset={151 * (1 - booked / totalParents)}/>
              </svg>
              <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', fontSize: 13, fontWeight: 800, color: 'var(--p700)', fontVariantNumeric: 'tabular-nums' }}>{Math.round((booked / totalParents) * 100)}%</div>
            </div>
          </div>
        </div>

        {/* Slot board */}
        <SectionLabel label="Slot board · 15-min each" hint={`${slotTimes.length - booked} available · ${booked} booked`}/>
        <div className="card" style={{ padding: 12, background: '#fff' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 6 }}>
            {slotTimes.map((t, i) => {
              const b = bookings.get(i);
              const isPicked = picked === i;
              return (
                <button key={i} onClick={() => !b && setPicked(isPicked ? null : i)} disabled={!!b} style={{
                  padding: '10px 4px', borderRadius: 8,
                  background: b ? 'var(--n100)' : isPicked ? 'var(--p600)' : 'var(--success-50)',
                  color: b ? 'var(--n500)' : isPicked ? '#fff' : 'var(--success)',
                  border: 'none', textAlign: 'center',
                  fontFamily: 'var(--mono)', fontSize: 11, fontWeight: 800,
                  opacity: b ? .85 : 1,
                }}>
                  <div>{t}</div>
                  {b && <div style={{ fontSize: 8.5, fontWeight: 600, color: 'var(--n600)', marginTop: 2 }}>R{b.roll} · {b.name.split(' ')[0]}</div>}
                  {!b && !isPicked && <div style={{ fontSize: 8.5, fontWeight: 600, marginTop: 2, opacity: .7 }}>Open</div>}
                  {isPicked && <div style={{ fontSize: 8.5, fontWeight: 600, marginTop: 2 }}>Block</div>}
                </button>
              );
            })}
          </div>
        </div>

        {/* Booked list */}
        <SectionLabel label="Bookings"/>
        <div className="col" style={{ gap: 6 }}>
          {[...bookings.entries()].map(([slot, b], i) => (
            <button key={i} onClick={() => nav.push('teachParentMessageThread', { sid: 's' + b.roll.toString().padStart(2,'0'), parent: b.name + "'s parent" })}
              className="card row" style={{ padding: 10, gap: 10, background: '#fff', textAlign: 'left' }}>
              <div style={{ width: 56, padding: '4px 8px', borderRadius: 6, background: 'var(--p50)', color: 'var(--p700)', fontFamily: 'var(--mono)', fontSize: 11, fontWeight: 800, textAlign: 'center' }}>{slotTimes[slot]}</div>
              <div className="av av-32" style={{ flexShrink: 0 }}>{b.name[0]}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)' }}>{b.name}</div>
                <div style={{ fontSize: 10.5, color: 'var(--n500)', fontFamily: 'var(--mono)' }}>Roll {b.roll}</div>
              </div>
              <Icon name="chev-r" size={14} style={{ color: 'var(--n400)' }}/>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 3. Parent message thread (per-student)
// ─────────────────────────────────────────────────────────────
function TeacherParentMessageThreadScreen({ nav, params }) {
  const sid = (params && params.sid) || 's01';
  const stu = (window.findRosterStudent && window.findRosterStudent(sid)) || { name: 'Aarav Reddy', initial: 'A', clr: '', roll: 1, attendance: 91, avgPct: 78 };
  const parentName = (params && params.parent) || `${stu.name.split(' ')[0]}'s parent`;
  const [draft, setDraft] = useStateCM('');
  const [sent, setSent] = useStateCM(false);

  const messages = [
    { from: 'parent', txt: "Good morning Mrs. Reddy. Could you please share Aarav's progress on Linear Equations?", when: 'Mon · 9:14 AM' },
    { from: 'me', txt: "Good morning. Aarav scored 18/24 in the practice quiz this week — his work on word problems is improving. Could use more practice on inequalities.", when: 'Mon · 11:02 AM' },
    { from: 'parent', txt: 'Thank you. Should I get him to redo the worksheet?', when: 'Mon · 12:18 PM' },
    { from: 'me', txt: "Not strictly needed. I've shared 5 extra problems through the app under 'Practice'. He should attempt those by Friday.", when: 'Mon · 4:30 PM' },
  ];

  const quickReplies = [
    'Will look into this and get back today.',
    'Could you call after school hours? +91 90100 22311',
    "Thanks for letting me know. I'll discuss with the student.",
  ];

  return (
    <div className="app screen-in" style={{ background: 'var(--n50)' }}>
      <StatusBar/>
      <div className="app-body no-pad" style={{ display: 'flex', flexDirection: 'column' }}>
        {/* Header */}
        <div style={{ padding: '8px 14px 12px', background: '#fff', borderBottom: '1px solid var(--n100)' }}>
          <NavHeader title={parentName} onBack={() => nav.pop()}
            right={<button onClick={() => nav.push('teachStudentProfile', { id: sid })} style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--n50)', display: 'grid', placeItems: 'center' }}><Icon name="user" size={16}/></button>}/>
        </div>

        {/* Auto-context strip */}
        <div className="card" style={{ margin: 12, padding: 12, background: 'var(--p50)', border: '1px solid rgba(79,70,229,.15)' }}>
          <div className="row" style={{ gap: 10 }}>
            <div className={`av av-40 ${stu.clr}`}>{stu.initial}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--n900)' }}>{stu.name} · Roll {stu.roll}</div>
              <div className="row" style={{ gap: 8, marginTop: 3, fontSize: 10.5, fontFamily: 'var(--mono)' }}>
                <span style={{ color: 'var(--n600)' }}>Att {stu.attendance || 91}%</span>
                <span style={{ color: 'var(--n300)' }}>·</span>
                <span style={{ color: 'var(--n600)' }}>Avg {stu.avgPct || 78}%</span>
                <span style={{ color: 'var(--n300)' }}>·</span>
                <span style={{ color: 'var(--n600)' }}>HW 92%</span>
              </div>
            </div>
            <button onClick={() => nav.push('teachReportCard', { id: sid })} style={{ height: 28, padding: '0 10px', borderRadius: 8, background: '#fff', color: 'var(--p700)', fontSize: 11, fontWeight: 700, border: '1px solid rgba(79,70,229,.15)' }}>Report →</button>
          </div>
        </div>

        {/* Thread */}
        <div className="app-body" style={{ flex: 1, paddingTop: 0 }}>
          <div className="col" style={{ gap: 8 }}>
            {messages.map((m, i) => (
              <div key={i} style={{
                alignSelf: m.from === 'me' ? 'flex-end' : 'flex-start',
                maxWidth: '85%',
                background: m.from === 'me' ? 'var(--p600)' : '#fff',
                color: m.from === 'me' ? '#fff' : 'var(--n900)',
                padding: '10px 12px', borderRadius: 14,
                borderTopRightRadius: m.from === 'me' ? 4 : 14,
                borderTopLeftRadius: m.from === 'me' ? 14 : 4,
                fontSize: 13, lineHeight: 1.45, fontWeight: 500,
                border: m.from === 'me' ? 'none' : '1px solid var(--n100)',
              }}>
                {m.txt}
                <div style={{ fontSize: 9.5, opacity: .7, marginTop: 4, fontFamily: 'var(--mono)' }}>{m.when}</div>
              </div>
            ))}
            {sent && (
              <div style={{ alignSelf: 'flex-end', maxWidth: '85%', background: 'var(--p600)', color: '#fff', padding: '10px 12px', borderRadius: 14, borderTopRightRadius: 4, fontSize: 13 }}>
                {draft || 'Quick reply sent.'}
                <div style={{ fontSize: 9.5, opacity: .7, marginTop: 4, fontFamily: 'var(--mono)' }}>now · ✓</div>
              </div>
            )}
          </div>
        </div>

        {/* Quick replies + composer */}
        <div style={{ background: '#fff', borderTop: '1px solid var(--n100)', padding: 10 }}>
          <div className="row" style={{ gap: 6, overflowX: 'auto', paddingBottom: 8 }}>
            {quickReplies.map((q, i) => (
              <button key={i} onClick={() => setDraft(q)} style={{
                flexShrink: 0, padding: '6px 10px', borderRadius: 16, background: 'var(--n50)', color: 'var(--n700)', fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap',
              }}>{q.length > 36 ? q.slice(0, 36) + '…' : q}</button>
            ))}
          </div>
          <div className="row" style={{ gap: 8 }}>
            <input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="Type a reply…" style={{
              flex: 1, height: 44, padding: '0 14px', borderRadius: 22,
              border: '1px solid var(--n200)', background: 'var(--n50)', fontSize: 13, fontFamily: 'inherit',
            }}/>
            <button onClick={() => { if (draft.trim()) { setSent(true); setDraft(''); } }} disabled={!draft.trim()} style={{
              width: 44, height: 44, borderRadius: 22, background: 'var(--p600)', color: '#fff',
              display: 'grid', placeItems: 'center', border: 'none',
              opacity: draft.trim() ? 1 : .5,
            }}><Icon name="send" size={16}/></button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  TeacherAnnouncementComposeScreen,
  TeacherPTMScheduleScreen,
  TeacherParentMessageThreadScreen,
});
