/* ClinicFlow AI — interactive widgets: toast, modal, panels, menus.
   All globals on window. */

const { useState: _is, useEffect: _ie, useRef: _ir, useMemo: _im } = React;

// -------- TOAST SYSTEM --------
const ToastCtx = React.createContext({ toast: () => {} });

let _toastSeq = 1;
function ToastHost({ children }) {
  const [toasts, setToasts] = _is([]);
  const push = (msg, opts = {}) => {
    const id = _toastSeq++;
    const item = { id, msg, sub: opts.sub, type: opts.type || 'success', icon: opts.icon };
    setToasts(t => [...t, item]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), opts.duration || 3200);
  };
  // Make toast globally available
  _ie(() => { window.toast = push; }, []);
  return (
    <ToastCtx.Provider value={{ toast: push }}>
      {children}
      <div className="toast-host">
        {toasts.map(t => (
          <div key={t.id} className={`toast ${t.type}`}>
            <span className="toast-icon">
              {t.type === 'success' && <I.check size={12} sw={3} stroke="white"/>}
              {t.type === 'error'   && <I.x size={12} sw={3} stroke="white"/>}
              {t.type === 'info'    && <I.zap size={11} fill="white" sw="0" stroke="white"/>}
            </span>
            <div className="toast-msg">
              {t.msg}
              {t.sub && <div className="toast-sub">{t.sub}</div>}
            </div>
            <button className="toast-close" onClick={() => setToasts(ts => ts.filter(x => x.id !== t.id))}>
              <I.x size={13}/>
            </button>
          </div>
        ))}
      </div>
    </ToastCtx.Provider>
  );
}

// -------- MODAL --------
function Modal({ open, onClose, title, children, footer, size }) {
  _ie(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose?.(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="scrim" onClick={onClose}>
      <div className={`modal ${size === 'lg' ? 'lg' : ''}`} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div className="modal-title">{title}</div>
          <button className="btn-icon" onClick={onClose}><I.x size={14}/></button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
}

// -------- SLIDE PANEL (notifications) --------
function SlidePanel({ open, onClose, title, children, foot }) {
  _ie(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose?.(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <>
      <div className="scrim" style={{ background: 'rgba(12,7,20,0.25)', padding: 0 }} onClick={onClose} />
      <aside className="slide-panel" onClick={e => e.stopPropagation()}>
        <div className="slide-panel-head">
          <div className="modal-title">{title}</div>
          <button className="btn-icon" onClick={onClose}><I.x size={14}/></button>
        </div>
        <div className="slide-panel-body">{children}</div>
        {foot}
      </aside>
    </>
  );
}

// -------- DROPDOWN MENU --------
function Menu({ open, onClose, children, style }) {
  if (!open) return null;
  return (
    <>
      <div className="click-shield" onClick={onClose} />
      <div className="menu" style={style} onClick={e => e.stopPropagation()}>
        {children}
      </div>
    </>
  );
}

// -------- NOTIFICATIONS PANEL --------
const NOTIFICATIONS_SEED = [
  { id: 'n1', kind: 'wa', title: 'WhatsApp reply from Aanya Sharma', sub: '"CONFIRM" — appointment confirmed for May 22', time: '2m ago', unread: true, color: '#25D366' },
  { id: 'n2', kind: 'ai', title: 'AI Agent completed scheduled run', sub: 'Processed 18 candidates · 12 messages queued for tonight', time: '1h ago', unread: true, color: '#7C3AED' },
  { id: 'n3', kind: 'missed', title: 'Vikram Singh missed 12:00 PM appointment', sub: 'Auto-flagged for outreach. AI will reach out at 5:30 PM.', time: '3h ago', unread: true, color: '#EF4444' },
  { id: 'n4', kind: 'patient', title: 'New patient registered — Sneha Reddy', sub: 'Added by Riya Sen · welcome flow triggered', time: '5h ago', unread: false, color: '#8B5CF6' },
  { id: 'n5', kind: 'success', title: 'Weekly summary delivered', sub: 'Sent to Dr. Vimal Rao at 8:00 AM · read 8:14 AM', time: 'Yesterday', unread: false, color: '#10B981' },
  { id: 'n6', kind: 'system', title: 'WhatsApp template approved', sub: '"Test Result Ready" template is now live', time: '2 days ago', unread: false, color: '#0EA5E9' },
];

function NotificationsPanel({ open, onClose }) {
  const [items, setItems] = _is(NOTIFICATIONS_SEED);
  const unreadCount = items.filter(i => i.unread).length;
  const markAll = () => setItems(items.map(i => ({ ...i, unread: false })));
  const iconFor = (k) => {
    if (k === 'wa') return <I.wa size={14} fill="white" sw="0"/>;
    if (k === 'ai') return <I.zap size={14} fill="white" sw="0"/>;
    if (k === 'missed') return <I.x size={14} sw={2.5}/>;
    if (k === 'patient') return <I.user size={14}/>;
    if (k === 'success') return <I.check size={14} sw={2.5}/>;
    return <I.bell size={14}/>;
  };
  return (
    <SlidePanel open={open} onClose={onClose}
      title={<>Notifications {unreadCount > 0 && <span className="badge badge-purple" style={{ marginLeft: 8 }}>{unreadCount} new</span>}</>}
      foot={
        <div style={{ padding: 12, borderTop: '1px solid var(--border-strong)', display: 'flex', justifyContent: 'space-between' }}>
          <button className="btn btn-link" onClick={markAll}>Mark all as read</button>
          <button className="btn btn-link">Settings</button>
        </div>
      }>
      {items.length === 0 ? (
        <div style={{ padding: 40, textAlign: 'center', color: 'var(--gray-500)', fontSize: 13 }}>
          You're all caught up.
        </div>
      ) : items.map(n => (
        <div key={n.id} className={`notif-item ${n.unread ? 'unread' : ''}`}
             onClick={() => setItems(its => its.map(i => i.id === n.id ? { ...i, unread: false } : i))}>
          <span className="notif-dot" style={{ background: n.color, color: 'white' }}>{iconFor(n.kind)}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="notif-title">{n.title}</div>
            <div className="notif-sub">{n.sub}</div>
            <div className="notif-time">{n.time}</div>
          </div>
          {n.unread && <span style={{ width: 7, height: 7, borderRadius: 999, background: 'var(--purple-600)', marginTop: 6 }}/>}
        </div>
      ))}
    </SlidePanel>
  );
}

// -------- SEARCH OVERLAY (CMD+K) --------
function SearchOverlay({ open, onClose, navigate }) {
  const [q, setQ] = _is('');
  const inputRef = _ir(null);
  _ie(() => {
    if (open) setTimeout(() => inputRef.current?.focus(), 50);
    if (!open) setQ('');
  }, [open]);
  if (!open) return null;

  const { PATIENTS } = window.CF_DATA;
  const pages = [
    { id: 'dashboard', label: 'Dashboard', icon: <I.layout size={14}/> },
    { id: 'patients', label: 'Patients', icon: <I.users size={14}/> },
    { id: 'appointments', label: 'Appointments', icon: <I.calendar size={14}/> },
    { id: 'followups', label: 'AI Follow-ups', icon: <I.zap size={14}/> },
    { id: 'communications', label: 'Communications', icon: <I.message size={14}/> },
    { id: 'analytics', label: 'Analytics', icon: <I.chart size={14}/> },
    { id: 'settings', label: 'Settings', icon: <I.settings size={14}/> },
  ];
  const term = q.trim().toLowerCase();
  const matchedPages = pages.filter(p => !term || p.label.toLowerCase().includes(term));
  const matchedPatients = term
    ? PATIENTS.filter(p => p.name.toLowerCase().includes(term) || p.phone.includes(q) || p.id.toLowerCase().includes(term)).slice(0, 5)
    : PATIENTS.slice(0, 3);

  return (
    <div className="search-overlay" onClick={onClose}>
      <div className="search-modal" onClick={e => e.stopPropagation()}>
        <div className="search-header">
          <I.search size={16} stroke="#9CA3AF" />
          <input ref={inputRef} placeholder="Search patients, pages, or commands..."
            value={q} onChange={e => setQ(e.target.value)} />
          <span className="kbd">ESC</span>
        </div>
        <div className="search-results">
          {matchedPatients.length > 0 && <div className="menu-label">Patients</div>}
          {matchedPatients.map(p => (
            <div key={p.id} className="search-result" onClick={() => { onClose(); navigate('profile', p.id); }}>
              <PatientAvatar name={p.name} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{p.name}</div>
                <div style={{ fontSize: 12, color: 'var(--gray-500)' }} className="mono">{p.phone} · {p.id}</div>
              </div>
              <StatusBadge value={p.risk} />
            </div>
          ))}
          {matchedPages.length > 0 && <div className="menu-label" style={{ marginTop: 8 }}>Pages</div>}
          {matchedPages.map(p => (
            <div key={p.id} className="search-result" onClick={() => { onClose(); navigate(p.id); }}>
              <span className="search-result-icon">{p.icon}</span>
              <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>{p.label}</div>
              <I.arrowRight size={13} stroke="#9CA3AF" style={{ marginLeft: 'auto' }}/>
            </div>
          ))}
          {term && matchedPages.length === 0 && matchedPatients.length === 0 && (
            <div style={{ padding: 32, textAlign: 'center', color: 'var(--gray-500)', fontSize: 13 }}>
              No matches for "{q}"
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// -------- ADD PATIENT MODAL --------
function AddPatientModal({ open, onClose, onSave }) {
  const [form, setForm] = _is({ name: '', phone: '', email: '', dob: '', doctor: 'Dr. Verma', tags: '' });
  _ie(() => { if (open) setForm({ name: '', phone: '', email: '', dob: '', doctor: 'Dr. Verma', tags: '' }); }, [open]);
  const submit = () => {
    if (!form.name || !form.phone) { window.toast('Name and phone are required', { type: 'error' }); return; }
    onSave?.(form);
    onClose();
  };
  return (
    <Modal open={open} onClose={onClose} title="Add new patient"
      footer={
        <>
          <button className="btn btn-subtle" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary" onClick={submit}><I.plus size={13}/>Add patient</button>
        </>
      }>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <div className="field" style={{ gridColumn: '1 / -1' }}>
          <label className="field-label">Full name</label>
          <input className="input" placeholder="e.g. Priya Sharma"
            value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} autoFocus />
        </div>
        <div className="field">
          <label className="field-label">Phone (WhatsApp)</label>
          <div className="input-prefix">
            <span className="prefix"><I.wa size={14} fill="currentColor" sw="0"/></span>
            <input placeholder="+91 98765 43210"
              value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} />
          </div>
        </div>
        <div className="field">
          <label className="field-label">Date of birth</label>
          <input className="input" type="date"
            value={form.dob} onChange={e => setForm({ ...form, dob: e.target.value })} />
        </div>
        <div className="field" style={{ gridColumn: '1 / -1' }}>
          <label className="field-label">Email</label>
          <input className="input" placeholder="patient@email.com"
            value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} />
        </div>
        <div className="field">
          <label className="field-label">Assigned doctor</label>
          <select className="input" value={form.doctor} onChange={e => setForm({ ...form, doctor: e.target.value })}>
            <option>Dr. Verma</option>
            <option>Dr. Iyer</option>
            <option>Dr. Khan</option>
          </select>
        </div>
        <div className="field">
          <label className="field-label">Tags</label>
          <input className="input" placeholder="e.g. Diabetic, Returning"
            value={form.tags} onChange={e => setForm({ ...form, tags: e.target.value })} />
        </div>
      </div>
    </Modal>
  );
}

// -------- ADD APPOINTMENT MODAL --------
function AddAppointmentModal({ open, onClose, onSave }) {
  const [form, setForm] = _is({ patient: '', date: '2026-05-22', time: '10:00', doctor: 'Dr. Verma', kind: 'Follow-up consultation' });
  const { PATIENTS } = window.CF_DATA;
  _ie(() => { if (open) setForm({ patient: '', date: '2026-05-22', time: '10:00', doctor: 'Dr. Verma', kind: 'Follow-up consultation' }); }, [open]);
  const submit = () => {
    if (!form.patient) { window.toast('Pick a patient', { type: 'error' }); return; }
    onSave?.(form);
    onClose();
  };
  return (
    <Modal open={open} onClose={onClose} title="New appointment"
      footer={<>
        <button className="btn btn-subtle" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary" onClick={submit}><I.calendar size={13}/>Schedule</button>
      </>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <div className="field" style={{ gridColumn: '1 / -1' }}>
          <label className="field-label">Patient</label>
          <select className="input" value={form.patient} onChange={e => setForm({ ...form, patient: e.target.value })}>
            <option value="">Select a patient...</option>
            {PATIENTS.map(p => <option key={p.id} value={p.name}>{p.name} — {p.phone}</option>)}
          </select>
        </div>
        <div className="field"><label className="field-label">Date</label>
          <input className="input" type="date" value={form.date} onChange={e => setForm({ ...form, date: e.target.value })}/></div>
        <div className="field"><label className="field-label">Time</label>
          <input className="input" type="time" value={form.time} onChange={e => setForm({ ...form, time: e.target.value })}/></div>
        <div className="field"><label className="field-label">Doctor</label>
          <select className="input" value={form.doctor} onChange={e => setForm({ ...form, doctor: e.target.value })}>
            <option>Dr. Verma</option><option>Dr. Iyer</option><option>Dr. Khan</option>
          </select></div>
        <div className="field"><label className="field-label">Type</label>
          <select className="input" value={form.kind} onChange={e => setForm({ ...form, kind: e.target.value })}>
            <option>Follow-up consultation</option>
            <option>Routine checkup</option>
            <option>Post-op review</option>
            <option>Lab review</option>
            <option>New consultation</option>
          </select></div>
        <label className="flex items-center gap-2" style={{ gridColumn: '1 / -1', fontSize: 13, color: 'var(--gray-700)', marginTop: 4 }}>
          <input type="checkbox" defaultChecked style={{ accentColor: 'var(--purple-600)' }}/>
          Send WhatsApp reminder 24h before
        </label>
      </div>
    </Modal>
  );
}

// -------- COMPOSE MESSAGE MODAL --------
function ComposeModal({ open, onClose, patient }) {
  const [text, setText] = _is('');
  _ie(() => { if (open) setText(''); }, [open]);
  if (!patient) return null;
  const templates = ['Appointment Reminder', 'Follow-up Check', 'Prescription Refill', 'Test Result Ready'];
  const send = () => {
    if (!text.trim()) { window.toast('Message is empty', { type: 'error' }); return; }
    window.toast(`Message sent to ${patient.name}`, { sub: 'Delivered via WhatsApp Business', type: 'success' });
    onClose();
  };
  return (
    <Modal open={open} onClose={onClose} size="lg"
      title={<span className="flex items-center gap-2"><I.wa size={16} fill="#25D366" sw="0"/>Message {patient.name}</span>}
      footer={<>
        <button className="btn btn-subtle" onClick={onClose}>Cancel</button>
        <button className="btn btn-wa" onClick={send}><I.send size={13}/>Send via WhatsApp</button>
      </>}>
      <div className="flex items-center gap-3" style={{ padding: 12, background: 'var(--gray-50)', borderRadius: 10, marginBottom: 16 }}>
        <PatientAvatar name={patient.name}/>
        <div style={{ flex: 1 }}>
          <div className="font-semi text-ink text-sm">{patient.name}</div>
          <div className="mono">{patient.phone}</div>
        </div>
        <span className="badge badge-success"><span className="status-dot" style={{ background: 'var(--success)' }}/>Online</span>
      </div>
      <div className="field">
        <label className="field-label">Use a template</label>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {templates.map(t => (
            <button key={t} className="chip" onClick={() => setText(`Hi ${patient.name.split(' ')[0]}, this is a ${t.toLowerCase()} from Apollo Family Clinic.`)}>{t}</button>
          ))}
        </div>
      </div>
      <div className="field">
        <label className="field-label">Message</label>
        <textarea className="input" rows={5} style={{ height: 'auto', padding: '10px 12px', resize: 'vertical' }}
          placeholder="Write a message..."
          value={text} onChange={e => setText(e.target.value)} />
        <span className="field-hint">{text.length}/1024 characters</span>
      </div>
    </Modal>
  );
}

// -------- EDIT FOLLOW-UP MODAL --------
function EditFollowupModal({ open, onClose, item, onSave }) {
  const [text, setText] = _is('');
  const [when, setWhen] = _is('');
  _ie(() => { if (open && item) { setText(item.preview); setWhen(item.scheduledFor); } }, [open, item]);
  if (!item) return null;
  return (
    <Modal open={open} onClose={onClose} title={<>Edit follow-up · <span className="mono" style={{ fontSize: 13 }}>{item.id}</span></>}
      footer={<>
        <button className="btn btn-subtle" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary" onClick={() => { onSave?.({ ...item, preview: text, scheduledFor: when }); window.toast('Follow-up updated', { sub: `Saved for ${item.patient}` }); onClose(); }}>
          <I.check size={13}/>Save changes
        </button>
      </>}>
      <div className="flex items-center gap-3" style={{ marginBottom: 14 }}>
        <PatientAvatar name={item.patient}/>
        <div>
          <div className="font-semi text-ink text-sm">{item.patient}</div>
          <div className="text-xs text-muted">{item.type} follow-up</div>
        </div>
        {item.ai && <span style={{ marginLeft: 'auto' }}><AIBadge/></span>}
      </div>
      <div className="field">
        <label className="field-label">Message</label>
        <textarea className="input" rows={5} style={{ height: 'auto', padding: '10px 12px', resize: 'vertical' }}
          value={text} onChange={e => setText(e.target.value)} />
      </div>
      <div className="field">
        <label className="field-label">Scheduled for</label>
        <input className="input" value={when} onChange={e => setWhen(e.target.value)} />
      </div>
    </Modal>
  );
}

Object.assign(window, {
  ToastHost, ToastCtx,
  Modal, SlidePanel, Menu,
  NotificationsPanel, SearchOverlay,
  AddPatientModal, AddAppointmentModal, ComposeModal, EditFollowupModal,
});
