/* global React, RIcons, DOCTORS, HISTORY_ROUNDS, TODAY_ROUND, BUNDLE_SUGGESTIONS, structureBundle, PROVIDER_QUEUE, SICK_NIGHT_ROUNDS */
// Schedule / Bundle compose / Sick-night mode / Provider queue.

const { useState: useS, useEffect: useEs, useMemo: useMs, useRef: useRs } = React;

// ─── SCHEDULE (cadence proof) ─────────────────────────────────────────────
function ScheduleScreen({ onBack, onOpenToday }) {
  return (
    <div className="pg" data-screen-label="Schedule">
      <div className="pg-top">
        <button className="doc-iconbtn" onClick={onBack}><RIcons.ChevronLeft /></button>
        <div className="doc-pill" style={{
          color: 'var(--accent)',
          background: 'rgba(125,128,230,0.10)',
          borderColor: 'rgba(125,128,230,0.28)',
        }}>30 days · 30 signed</div>
        <div style={{ width: 36 }} />
      </div>

      <div className="pg-title">Nora’s last 30 nights.</div>

      <div className="sched-list">
        {/* Tomorrow — upcoming */}
        <div className="sched-month">Upcoming</div>
        <div className="sched-row upcoming">
          <div className="day">
            <div className="num">31</div>
            <div className="dow">Sun</div>
          </div>
          <div className="body">
            <div className="ttl">Tomorrow’s Morning Round · 7:30 AM</div>
            <div className="by">
              <RIcons.Doctor size={11} /> Rotation: Dr. Patel on call
            </div>
          </div>
          <div className="status pending">On deck</div>
        </div>

        {/* Today */}
        <div className="sched-month">Today</div>
        <div className="sched-row today" onClick={onOpenToday}>
          <div className="day">
            <div className="num">30</div>
            <div className="dow">Sat</div>
          </div>
          <div className="body">
            <div className="ttl">{TODAY_ROUND.narrative.split('.')[0]}.</div>
            <div className="by">
              <span className="ava" style={{ backgroundImage: `url('${DOCTORS[TODAY_ROUND.by].ava}')` }} />
              Signed by {DOCTORS[TODAY_ROUND.by].short} · 7:31 AM
            </div>
          </div>
          <div className="status signed">Signed</div>
        </div>

        {/* History */}
        <div className="sched-month">This week</div>
        {HISTORY_ROUNDS.map((r) => {
          const doc = DOCTORS[r.doc];
          return (
            <div key={r.id} className="sched-row">
              <div className="day">
                <div className="num">{r.date}</div>
                <div className="dow">{r.dow}</div>
              </div>
              <div className="body">
                <div className="ttl">{r.title}</div>
                <div className="by">
                  <span className="ava" style={{ backgroundImage: `url('${doc.ava}')` }} />
                  Signed by {doc.short}
                </div>
              </div>
              <div className="status signed">Signed</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── BUNDLE compose (active inside passive) ──────────────────────────────
function BundleScreen({ onBack, onConfirm }) {
  const [text, setText] = useS('');
  const [chips, setChips] = useS([]);
  const draft = text || (chips[0] || '');
  const structured = useMs(() => structureBundle(draft), [draft]);

  function toggleChip(s) {
    setChips(prev => prev.includes(s) ? prev.filter(x => x !== s) : [s]);
    setText('');
  }

  return (
    <div className="bundle-page pg" data-screen-label="Bundle">
      <div className="pg-top">
        <button className="doc-iconbtn" onClick={onBack}><RIcons.ChevronLeft /></button>
        <div className="doc-pill" style={{
          color: 'var(--accent)',
          background: 'rgba(125,128,230,0.10)',
          borderColor: 'rgba(125,128,230,0.28)',
        }}>For tomorrow’s round</div>
        <div style={{ width: 36 }} />
      </div>

      <div className="bundle-hero">
        <div className="kicker" style={{ color: 'var(--accent)', marginBottom: 4 }}>
          Add to tomorrow
        </div>
        <h2>What should tomorrow’s doctor know?</h2>
        <p>No appointment to schedule.</p>
        <div className="next">Next round · Tomorrow, 7:30 AM</div>
      </div>

      <div className="bundle-input">
        <textarea
          value={text}
          onChange={e => { setText(e.target.value); if (e.target.value) setChips([]); }}
          placeholder="What's on your mind? — e.g., she's been fussy around the same time each night"
        />
      </div>

      <div className="bundle-section">
        <h4>Or pick from common asks</h4>
      </div>
      <div className="bundle-chips">
        {BUNDLE_SUGGESTIONS.map(s => (
          <button
            key={s}
            className={`bundle-chip ${chips.includes(s) ? 'on' : ''}`}
            onClick={() => toggleChip(s)}>
            {s}
          </button>
        ))}
      </div>

      {structured && (
        <div style={{ marginTop: 8 }}>
          <div className="bundle-section">
            <h4>What the round will see</h4>
          </div>
          <div className="ai-preview">
            <div className="lbl"><span className="dot" /> Structured for the doctor</div>
            <p className="q">“{structured.summary}”</p>
            <div className="meta">
              {structured.fields.map((f, i) => (
                <span className="pill" key={i}><b style={{ color: '#fff', fontWeight: 600 }}>{f.label}:</b> {f.value}</span>
              ))}
              <div style={{ marginTop: 6 }}>Routes to <b style={{ color: 'var(--primary)' }}>{structured.routedTo}</b></div>
            </div>
          </div>
        </div>
      )}

      <div className="footer-cta">
        <button
          className="cta"
          disabled={!structured}
          onClick={onConfirm}
          style={{ opacity: structured ? 1 : 0.4, cursor: structured ? 'pointer' : 'not-allowed' }}
        >
          Add to tomorrow’s round
          <RIcons.ChevronRight size={16} />
        </button>
      </div>
    </div>
  );
}

// Confirmation after a bundle is added.
function BundleConfirmScreen({ onDone }) {
  return (
    <div className="pg" data-screen-label="Bundle confirm" style={{
      display: 'flex', flexDirection: 'column',
      justifyContent: 'center', minHeight: '100%',
      padding: '40px 24px', textAlign: 'center',
    }}>
      <div style={{
        width: 80, height: 80, borderRadius: 999,
        margin: '0 auto 22px',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: 'linear-gradient(180deg, #e8d4a5 0%, #c9a875 100%)',
        color: '#2a1f0a',
        boxShadow: '0 0 0 4px rgba(232,212,165,0.18), 0 18px 40px rgba(0,0,0,0.45)',
      }}>
        <RIcons.Check size={32} />
      </div>
      <div className="kicker" style={{ color: 'var(--seal)', marginBottom: 10 }}>Added to the queue</div>
      <h2 style={{
        fontFamily: 'var(--font-heading)', fontWeight: 600,
        fontSize: 24, lineHeight: '30px', color: '#fff',
        margin: '0 0 28px',
      }}>
        On Dr. Patel’s screen tomorrow at 7:30 AM.
      </h2>

      <button className="cta" onClick={onDone}>
        Back to home
      </button>
    </div>
  );
}

// ─── SICK-NIGHT MODE ─────────────────────────────────────────────────────
function ModeScreen({ onBack, modeOn, onToggle, onOpenSick }) {
  return (
    <div className="pg" data-screen-label="Mode">
      <div className="pg-top">
        <button className="doc-iconbtn" onClick={onBack}><RIcons.ChevronLeft /></button>
        <div style={{ width: 36 }} />
        <div style={{ width: 36 }} />
      </div>

      <div className="pg-title">Tonight.</div>

      {/* Default */}
      <div className="mode-toggle">
        <div className="icn"><RIcons.Sun size={18} /></div>
        <div className="body">
          <div className="ttl">Morning Round · 7:30 AM</div>
          <div className="sub">One round, signed by the rotating pediatrician.</div>
        </div>
        <div style={{
          fontSize: 10, fontWeight: 700, letterSpacing: '0.12em',
          textTransform: 'uppercase', color: 'var(--primary)',
        }}>Default</div>
      </div>

      {/* Sick-night */}
      <div className={`mode-toggle ${modeOn ? 'on' : ''}`}>
        <div className="icn"><RIcons.Moon size={18} /></div>
        <div className="body">
          <div className="ttl">Sick-night mode</div>
          <div className="sub">Rounds every 4 hours. Broader inputs (symptoms, meds, feeds).</div>
        </div>
        <button
          className={`ios-toggle ${modeOn ? 'on' : ''}`}
          onClick={onToggle}
          aria-label="Toggle sick-night mode"
        >
          <div className="knob" />
        </button>
      </div>

      {modeOn && (
        <>
          <div style={{ padding: '4px 20px 8px' }}>
            <div className="kicker" style={{ marginBottom: 6 }}>Tonight’s cadence</div>
          </div>
          <div style={{ padding: '0 16px 22px' }}>
            {SICK_NIGHT_ROUNDS.map(r => {
              const doc = DOCTORS[r.doc];
              const isPending = r.status === 'pending';
              const isUpcoming = r.status === 'upcoming';
              return (
                <div
                  key={r.id}
                  className="sched-row"
                  onClick={r.status === 'signed' ? onOpenSick : undefined}
                  style={{
                    cursor: r.status === 'signed' ? 'pointer' : 'default',
                    opacity: isUpcoming ? 0.65 : 1,
                  }}
                >
                  <div className="day">
                    <div className="num" style={{ fontSize: 13, lineHeight: '15px' }}>{r.time.split(' ')[0]}</div>
                    <div className="dow">{r.time.split(' ')[1]}</div>
                  </div>
                  <div className="body">
                    <div className="ttl">{r.label}</div>
                    <div className="by">
                      {r.sum
                        ? <span style={{ color: 'var(--foreground-muted)' }}>{r.sum}</span>
                        : <span><RIcons.Doctor size={11} /> {doc.short} on call</span>}
                    </div>
                  </div>
                  <div className={`status ${r.status === 'signed' ? 'signed' : isPending ? 'pending' : 'bundled'}`}>
                    {r.status === 'signed' ? 'Signed' : isPending ? 'Now' : 'Soon'}
                  </div>
                </div>
              );
            })}
          </div>
        </>
      )}
    </div>
  );
}

// ─── PROVIDER QUEUE (stretch — investor moment) ──────────────────────────
function ProviderQueueScreen({ onBack }) {
  const [approved, setApproved] = useS({}); // id -> true
  const [doneCount, setDoneCount] = useS(47);
  const [elapsed, setElapsed] = useS('12:14');
  const intervalRef = useRs(null);

  // Auto-approve animation: 1 round per ~1.5s
  useEs(() => {
    intervalRef.current = setInterval(() => {
      setApproved(prev => {
        const remaining = PROVIDER_QUEUE.find(q => !prev[q.id]);
        if (!remaining) return prev;
        return { ...prev, [remaining.id]: true };
      });
      setDoneCount(c => c + 1);
    }, 1500);
    return () => clearInterval(intervalRef.current);
  }, []);

  return (
    <div className="prov-page" data-screen-label="Provider queue">
      <div className="prov-top">
        <button className="doc-iconbtn" onClick={onBack}><RIcons.ChevronLeft /></button>
        <div style={{ textAlign: 'right', flex: 1 }}>
          <div className="who">Dr. Anika Patel</div>
          <div className="meta">Morning Round queue · {elapsed} elapsed</div>
        </div>
      </div>

      <div className="prov-stats">
        <div className="prov-stat">
          <div className="v">{doneCount}</div>
          <div className="l">Reviewed</div>
        </div>
        <div className="prov-stat">
          <div className="v">{PROVIDER_QUEUE.length - Object.keys(approved).length}</div>
          <div className="l">In queue</div>
        </div>
        <div className="prov-stat">
          <div className="v">$0.94</div>
          <div className="l">Cost / member</div>
        </div>
      </div>

      <div style={{ padding: '0 16px 6px' }}>
        <div className="kicker">Up next · auto-routing</div>
      </div>

      <div className="prov-queue">
        {PROVIDER_QUEUE.map((q, i) => (
          <div
            key={q.id}
            className={`prov-card ${approved[q.id] ? 'approved' : ''}`}
          >
            <div className="num">{i + 1}</div>
            <div className="body">
              <div className="name">{q.name} · {q.age}</div>
              <div className="sum">{q.sum}</div>
            </div>
            <div className={`badge ${q.flag ? 'flag' : 'ok'}`}>
              {approved[q.id] ? 'Signed' : q.flag ? 'Review' : 'AI draft'}
            </div>
          </div>
        ))}
      </div>

      <div className="prov-bulk">
        <button className="cta">
          <RIcons.Seal size={16} />
          Sign all matching · MD review
        </button>
        <div className="muted" style={{
          fontSize: 11, marginTop: 8, textAlign: 'center',
          letterSpacing: '0.04em',
        }}>200 rounds per batch · ~$1/member/month · Powered by MDI</div>
      </div>
    </div>
  );
}

const RScreens = { ScheduleScreen, BundleScreen, BundleConfirmScreen, ModeScreen, ProviderQueueScreen };
