// screens.jsx — Chat detail (renders interactive HTML artifact in iframe), system view, notes
const fontHead = `'Fraunces', Georgia, serif`;
const fontBody = `'Geist', system-ui, sans-serif`;
const fontMono = `'JetBrains Mono', monospace`;

function BackBar({ nav, palette, title, subtitle, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '18px 32px',
                  borderBottom: `1px solid ${palette.ink}10`, background: palette.bg, position: 'sticky', top: 0, zIndex: 5 }}>
      <button onClick={() => nav('home')} style={{
        width: 36, height: 36, borderRadius: 10, border: `1px solid ${palette.ink}20`,
        background: palette.surface, cursor: 'pointer', fontSize: 16, color: palette.ink,
      }}>←</button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.1em', textTransform: 'uppercase', color: palette.inkSoft }}>{subtitle}</div>
        <div style={{ fontFamily: fontHead, fontSize: 22, fontWeight: 500, lineHeight: 1.2, marginTop: 2,
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</div>
      </div>
      {right}
    </div>
  );
}

function pillBtn(palette, key = 'accent1') {
  return {
    background: palette[key], color: '#fff', border: 0, borderRadius: 999,
    padding: '8px 16px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: fontBody,
  };
}

function ChatDetail({ chatId, nav, palette }) {
  const d = window.MED_DATA;
  const chat = d.chats.find(c => c.id === chatId) || d.chats[0];
  const Icon = window.SYSTEM_ICONS[chat.system] || window.PillIcon;
  const sysLabel = d.systems.find(s => s.id === chat.system)?.label || 'Other';
  const [tab, setTab] = React.useState('chat'); // chat | notes
  const iframeRef = React.useRef(null);
  const [favs, toggleFav] = window.useFavorites();
  const isFav = favs.has(chat.id);

  // Cycle to next/prev chat in same system
  const sameSystem = d.chats.filter(c => c.system === chat.system);
  const idx = sameSystem.findIndex(c => c.id === chat.id);
  const prev = sameSystem[(idx - 1 + sameSystem.length) % sameSystem.length];
  const next = sameSystem[(idx + 1) % sameSystem.length];

  return (
    <div style={{ background: palette.bg, color: palette.ink, fontFamily: fontBody, minHeight: '100%' }}>
      <BackBar nav={nav} palette={palette} subtitle={sysLabel} title={chat.title}
               right={
                 <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                   <button onClick={() => toggleFav(chat.id)} title={isFav ? 'Remove from favorites' : 'Save to favorites'} style={{
                     background: isFav ? palette.accent2 : palette.surface,
                     color: isFav ? '#fff' : palette.ink,
                     border: `1px solid ${isFav ? palette.accent2 : palette.ink + '20'}`,
                     borderRadius: 999, padding: '6px 12px', cursor: 'pointer', fontSize: 12,
                     fontFamily: fontBody, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 6,
                   }}>
                     <span style={{ fontSize: 13 }}>{isFav ? '★' : '☆'}</span>
                     {isFav ? 'Saved' : 'Save'}
                   </button>
                   <button onClick={() => nav('chat', prev.id)} title={prev.title} style={{
                     background: palette.surface, border: `1px solid ${palette.ink}20`, borderRadius: 999,
                     padding: '6px 12px', cursor: 'pointer', fontSize: 12, fontFamily: fontBody, color: palette.ink,
                   }}>← {sysLabel}</button>
                   <button onClick={() => nav('chat', next.id)} title={next.title} style={{
                     background: palette.surface, border: `1px solid ${palette.ink}20`, borderRadius: 999,
                     padding: '6px 12px', cursor: 'pointer', fontSize: 12, fontFamily: fontBody, color: palette.ink,
                   }}>{sysLabel} →</button>
                   <a href={chat.file} target="_blank" rel="noopener" style={{ ...pillBtn(palette, 'accent3'), textDecoration: 'none', display: 'inline-block' }}>↗ Open</a>
                 </div>
               }/>

      <div style={{ padding: '20px 32px 16px', display: 'flex', gap: 12, alignItems: 'center' }}>
        <div style={{ width: 44, height: 44, borderRadius: 12, background: palette.chip, display: 'grid', placeItems: 'center' }}>
          <Icon size={28} color={palette[window.SYSTEM_ACCENT[chat.system]]} stroke={palette.ink}/>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: palette.inkSoft }}>{sysLabel} · {chat.lastStudied}</div>
          <div style={{ fontFamily: fontHead, fontSize: 20, fontWeight: 500, lineHeight: 1.2, marginTop: 2 }}>{chat.title}</div>
        </div>
        <div style={{ display: 'flex', gap: 4, padding: 4, background: palette.chip, borderRadius: 999 }}>
          {[
            { id: 'chat', label: 'Reference' },
            { id: 'notes', label: 'My notes' },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              background: tab === t.id ? palette.surface : 'transparent',
              color: palette.ink, border: 0, borderRadius: 999,
              padding: '6px 14px', cursor: 'pointer', fontSize: 13, fontWeight: tab === t.id ? 600 : 500,
              fontFamily: fontBody,
              boxShadow: tab === t.id ? `0 1px 3px ${palette.ink}15` : 'none',
            }}>{t.label}</button>
          ))}
        </div>
      </div>

      {tab === 'chat' && (
        <div style={{ padding: '0 32px 32px' }}>
          <div style={{ background: palette.surface, border: `1px solid ${palette.ink}15`, borderRadius: 18,
                        overflow: 'hidden', boxShadow: `0 4px 16px ${palette.ink}08` }}>
            <iframe ref={iframeRef} src={chat.file} title={chat.title}
                    style={{ width: '100%', height: 'calc(100vh - 220px)', minHeight: 540, border: 0, display: 'block', background: '#fff' }}/>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, fontSize: 12, color: palette.inkSoft }}>
            <span>Interactive reference · scroll, click tabs, explore inside ↑</span>
            <a href={chat.file} target="_blank" rel="noopener" style={{ color: palette.accent1, fontWeight: 600, textDecoration: 'none' }}>Open in new tab ↗</a>
          </div>
        </div>
      )}

      {tab === 'notes' && (
        <div style={{ padding: '0 32px 40px', maxWidth: 760 }}>
          <NotesPad palette={palette} chatId={chat.id}/>
        </div>
      )}
    </div>
  );
}

function NotesPad({ palette, chatId }) {
  const [notes, setNotes] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(`notes-${chatId}`) || '""') || ''; } catch { return ''; }
  });
  React.useEffect(() => { localStorage.setItem(`notes-${chatId}`, JSON.stringify(notes)); }, [notes, chatId]);
  return (
    <div style={{
      background: `repeating-linear-gradient(transparent, transparent 27px, ${palette.ink}15 28px)`,
      border: `1px solid ${palette.ink}15`, borderRadius: 14, padding: 16, minHeight: 360, position: 'relative',
    }}>
      <div style={{ position: 'absolute', top: 16, left: 36, bottom: 16, width: 1, background: palette.accent3, opacity: .4 }}/>
      <textarea value={notes} onChange={e => setNotes(e.target.value)}
                placeholder="Jot down your own annotations, mnemonics, mistakes you want to remember…"
                style={{
                  width: '100%', minHeight: 320, border: 0, background: 'transparent',
                  resize: 'none', outline: 'none', font: `15px/28px ${fontBody}`,
                  paddingLeft: 36, color: palette.ink,
                }}/>
      <div style={{ fontSize: 11, color: palette.inkSoft, fontFamily: fontMono, marginTop: 6 }}>
        ✎ saved locally · {notes.length} chars
      </div>
    </div>
  );
}

function SystemView({ systemId, nav, palette }) {
  const d = window.MED_DATA;
  const sys = d.systems.find(s => s.id === systemId) || d.systems[0];
  const Icon = window.SYSTEM_ICONS[sys.id] || window.PillIcon;
  const chats = d.chats.filter(c => c.system === sys.id);
  return (
    <div style={{ background: palette.bg, color: palette.ink, fontFamily: fontBody, minHeight: '100%' }}>
      <BackBar nav={nav} palette={palette} subtitle="System" title={sys.label}/>
      <div style={{ padding: '28px 32px 60px', maxWidth: 1100, margin: '0 auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, background: palette.surface,
                      border: `1px solid ${palette.ink}10`, borderRadius: 20, padding: 22, marginBottom: 20 }}>
          <div style={{ width: 72, height: 72, borderRadius: 18, background: palette.chip, display: 'grid', placeItems: 'center' }}>
            <Icon size={48} color={palette[window.SYSTEM_ACCENT[sys.id]]} stroke={palette.ink}/>
          </div>
          <div>
            <div style={{ fontFamily: fontHead, fontSize: 32, fontWeight: 500, lineHeight: 1 }}>{sys.label}</div>
            <div style={{ color: palette.inkSoft, fontSize: 14, marginTop: 4 }}>{chats.length} chat{chats.length !== 1 ? 's' : ''}</div>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
          {chats.map(c => (
            <button key={c.id} onClick={() => nav('chat', c.id)} style={{
              background: palette.surface, border: `1px solid ${palette.ink}10`, borderRadius: 16,
              padding: 16, textAlign: 'left', cursor: 'pointer', font: 'inherit', color: 'inherit',
            }}>
              <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 6, lineHeight: 1.3 }}>{c.title}</div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <div style={{ flex: 1, height: 4, background: palette.chip, borderRadius: 2, overflow: 'hidden' }}>
                  <div style={{ width: `${c.progress*100}%`, height: '100%', background: palette.accent1 }}/>
                </div>
                <span style={{ fontSize: 11, color: palette.inkSoft }}>{c.lastStudied}</span>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function SystemsView({ nav, palette }) {
  const d = window.MED_DATA;
  return (
    <div style={{ background: palette.bg, color: palette.ink, fontFamily: fontBody, minHeight: '100%' }}>
      <BackBar nav={nav} palette={palette} subtitle="Browse" title="All systems"/>
      <div style={{ padding: '28px 32px 60px', maxWidth: 1100, margin: '0 auto',
                    display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
        {d.systems.map(s => {
          const Icon = window.SYSTEM_ICONS[s.id] || window.PillIcon;
          return (
            <button key={s.id} onClick={() => nav('system', s.id)} style={{
              background: palette.surface, border: `1px solid ${palette.ink}10`, borderRadius: 18,
              padding: 20, cursor: 'pointer', font: 'inherit', color: 'inherit', textAlign: 'left',
              display: 'flex', flexDirection: 'column', gap: 12, minHeight: 140,
            }}>
              <div style={{ width: 52, height: 52, borderRadius: 14, background: palette.chip, display: 'grid', placeItems: 'center' }}>
                <Icon size={32} color={palette[window.SYSTEM_ACCENT[s.id]]} stroke={palette.ink}/>
              </div>
              <div style={{ marginTop: 'auto' }}>
                <div style={{ fontFamily: fontHead, fontSize: 22, fontWeight: 500 }}>{s.label}</div>
                <div style={{ fontSize: 12, color: palette.inkSoft, marginTop: 2 }}>{s.count} chat{s.count !== 1 ? 's' : ''}</div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function FavoritesView({ nav, palette }) {
  const d = window.MED_DATA;
  const [favs, toggleFav] = window.useFavorites();
  const [search, setSearch] = React.useState('');
  const [page, setPage] = React.useState(1);
  const [perPage, setPerPage] = React.useState(() => {
    try { return parseInt(localStorage.getItem('med-hub-perpage') || '20', 10) || 20; } catch { return 20; }
  });
  React.useEffect(() => { try { localStorage.setItem('med-hub-perpage', String(perPage)); } catch {} }, [perPage]);

  const favChats = React.useMemo(() => {
    let xs = d.chats.filter(c => favs.has(c.id));
    if (search.trim()) {
      const q = search.toLowerCase();
      xs = xs.filter(c => c.title.toLowerCase().includes(q));
    }
    return xs;
  }, [d.chats, favs, search]);

  React.useEffect(() => { setPage(1); }, [search, perPage, favs.size]);

  const totalPages = Math.max(1, Math.ceil(favChats.length / perPage));
  const safePage = Math.min(page, totalPages);
  const pageStart = (safePage - 1) * perPage;
  const pageItems = favChats.slice(pageStart, pageStart + perPage);

  return (
    <div style={{ background: palette.bg, color: palette.ink, fontFamily: fontBody, minHeight: '100%' }}>
      <BackBar nav={nav} palette={palette} subtitle="Saved" title="Your favorites"/>
      <div style={{ padding: '28px 32px 60px', maxWidth: 1100, margin: '0 auto' }}>

        {/* Hero */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, background: palette.surface,
                      border: `1px solid ${palette.ink}10`, borderRadius: 20, padding: 22, marginBottom: 20 }}>
          <div style={{ width: 72, height: 72, borderRadius: 18, background: palette.chip, display: 'grid', placeItems: 'center', color: palette.accent2, fontSize: 38 }}>
            <svg width="42" height="42" viewBox="0 0 24 24" fill="currentColor"><polygon points="12 2 15 8.5 22 9.3 17 14.1 18.2 21 12 17.8 5.8 21 7 14.1 2 9.3 9 8.5 12 2"/></svg>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: fontHead, fontSize: 32, fontWeight: 500, lineHeight: 1 }}>Your favorites</div>
            <div style={{ color: palette.inkSoft, fontSize: 14, marginTop: 4 }}>
              {favs.size === 0 ? 'No saved chats yet — tap the ★ on any chat to save it here.' :
                `${favs.size} saved chat${favs.size === 1 ? '' : 's'} · personal shortlist`}
            </div>
          </div>
          {favs.size > 0 && (
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Filter favorites…"
              style={{ flex: '0 0 220px', padding: '8px 12px', borderRadius: 999, border: `1px solid ${palette.ink}20`,
                       background: palette.bg, font: 'inherit', color: palette.ink, outline: 'none', fontSize: 13 }}/>
          )}
        </div>

        {favs.size === 0 ? (
          <div style={{ textAlign: 'center', padding: '60px 20px', color: palette.inkSoft }}>
            <div style={{ fontSize: 48, marginBottom: 12, color: palette.inkSoft + '60' }}>★</div>
            <div style={{ fontSize: 16, marginBottom: 6, color: palette.ink }}>Nothing saved yet</div>
            <div style={{ fontSize: 13, maxWidth: 360, margin: '0 auto 18px' }}>
              Browse your library and tap the star on any chat to keep your most-used references here.
            </div>
            <button onClick={() => nav('home')} style={{
              background: palette.accent1, color: '#fff', border: 0, borderRadius: 999,
              padding: '10px 20px', cursor: 'pointer', font: 'inherit', fontSize: 14, fontWeight: 600,
            }}>Go to library →</button>
          </div>
        ) : favChats.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 40, color: palette.inkSoft, fontSize: 14 }}>No favorites match "{search}".</div>
        ) : (
          <>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
              {pageItems.map(c => {
                const Icon = window.SYSTEM_ICONS[c.system] || window.PillIcon;
                return (
                  <button key={c.id} onClick={() => nav('chat', c.id)} style={{
                    background: palette.surface, border: `1px solid ${palette.ink}10`, borderRadius: 12,
                    padding: '12px 14px', textAlign: 'left', cursor: 'pointer', font: 'inherit', color: 'inherit',
                    display: 'flex', gap: 12, alignItems: 'center',
                  }}>
                    <div style={{ width: 32, height: 32, borderRadius: 8, background: palette.chip, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                      <Icon size={20} color={palette[window.SYSTEM_ACCENT[c.system]]} stroke={palette.ink}/>
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 500, fontSize: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.title}</div>
                      <div style={{ fontSize: 11, color: palette.inkSoft, marginTop: 2 }}>
                        {(d.systems.find(s => s.id === c.system)?.label) || 'Other'} · {c.lastStudied}
                      </div>
                    </div>
                    <window.FavStar active={true} onClick={() => toggleFav(c.id)} palette={palette}/>
                  </button>
                );
              })}
            </div>
            <window.Pagination palette={palette} page={safePage} setPage={setPage} totalPages={totalPages}
                               perPage={perPage} setPerPage={setPerPage} total={favChats.length}
                               pageStart={pageStart} pageEnd={Math.min(pageStart + perPage, favChats.length)}/>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ChatDetail, SystemView, SystemsView, FavoritesView, BackBar, pillBtn });
