const { useState, useMemo, useRef, useEffect } = React;

// Iconos SVG inline (en lugar de lucide-react para evitar bundler)
const Icon = ({ name, size = 14, style = {} }) => {
  const common = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', style };
  const paths = {
    search: <><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></>,
    arrows: <><path d="M8 3 4 7l4 4"/><path d="M4 7h16"/><path d="m16 21 4-4-4-4"/><path d="M20 17H4"/></>,
    pill: <><path d="m10.5 20.5 10-10a4.95 4.95 0 1 0-7-7l-10 10a4.95 4.95 0 1 0 7 7Z"/><path d="m8.5 8.5 7 7"/></>,
    alert: <><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z"/><path d="M12 9v4"/><path d="M12 17h.01"/></>,
    x: <><path d="M18 6 6 18"/><path d="m6 6 12 12"/></>,
    ext: <><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/></>,
    shield: <><path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/><path d="m9 12 2 2 4-4"/></>,
    chevron: <><path d="m9 18 6-6-6-6"/></>,
    info: <><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></>,
    file: <><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></>,
    layers: <><path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z"/><path d="m6.08 9.5-3.5 1.6a1 1 0 0 0 0 1.81l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9a1 1 0 0 0 0-1.83l-3.5-1.59"/><path d="m6.08 14.5-3.5 1.6a1 1 0 0 0 0 1.81l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9a1 1 0 0 0 0-1.83l-3.5-1.59"/></>,
  };
  return <svg {...common}>{paths[name]}</svg>;
};

const FREQ_ORDER = ['muy_frecuente', 'frecuente', 'poco_frecuente', 'rara', 'muy_rara', 'desconocida'];
const FREQ_META = {
  muy_frecuente:  { label: 'Muy frecuente',  short: '≥1/10',              tone: 'high'    },
  frecuente:      { label: 'Frecuente',      short: '≥1/100 a <1/10',     tone: 'mid'     },
  poco_frecuente: { label: 'Poco frecuente', short: '≥1/1.000 a <1/100',  tone: 'low'     },
  rara:           { label: 'Rara',           short: '≥1/10.000 a <1/1.000', tone: 'rare'  },
  muy_rara:       { label: 'Muy rara',       short: '<1/10.000',          tone: 'rare'    },
  desconocida:    { label: 'No conocida',    short: 'frecuencia no determinada', tone: 'neutral' },
};
const TONE_STYLES = {
  high:    { bg: '#5a3a1f', fg: '#f7ead4', border: '#5a3a1f' },
  mid:     { bg: '#8a6b3a', fg: '#fbf5e6', border: '#8a6b3a' },
  low:     { bg: '#c9a96a', fg: '#3a2818', border: '#c9a96a' },
  rare:    { bg: '#e8dcc0', fg: '#5a3a1f', border: '#d4c4a0' },
  neutral: { bg: '#ede4d0', fg: '#5a4a30', border: '#d4c4a0' },
};

const norm = (s) => s.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim();

function App() {
  const [DATA, setDATA] = useState(null);
  const [loadError, setLoadError] = useState(null);
  const [mode, setMode] = useState('med');
  const [query, setQuery] = useState('');
  const [selected, setSelected] = useState(null);
  const [freqFilter, setFreqFilter] = useState('all');
  const [socFilter, setSocFilter] = useState('all');
  const inputRef = useRef(null);

  useEffect(() => {
    fetch('./data.json')
      .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
      .then(d => setDATA(d))
      .catch(e => setLoadError(e.message));
  }, []);

  useEffect(() => {
    setQuery(''); setSelected(null);
    setFreqFilter('all'); setSocFilter('all');
    inputRef.current?.focus();
  }, [mode]);

  useEffect(() => { setFreqFilter('all'); setSocFilter('all'); }, [selected]);

  const ALL_MEDS = useMemo(() =>
    DATA ? Object.keys(DATA.medicamentos).sort((a,b) => a.localeCompare(b, 'es')) : []
  , [DATA]);

  const ALL_EVENT_SLUGS = useMemo(() =>
    DATA ? Object.keys(DATA.eventos).sort((a,b) =>
      DATA.eventos[a].event_name.localeCompare(DATA.eventos[b].event_name, 'es')
    ) : []
  , [DATA]);

  const filtered = useMemo(() => {
    if (!DATA) return [];
    const q = norm(query);
    if (mode === 'med') {
      if (!q) return ALL_MEDS;
      return ALL_MEDS.filter(m => norm(m).includes(q));
    } else {
      if (!q) return ALL_EVENT_SLUGS;
      return ALL_EVENT_SLUGS.filter(slug =>
        norm(DATA.eventos[slug].event_name).includes(q)
      );
    }
  }, [query, mode, DATA, ALL_MEDS, ALL_EVENT_SLUGS]);

  const detail = useMemo(() => {
    if (!DATA || !selected) return null;
    if (mode === 'med') {
      const data = DATA.medicamentos[selected];
      if (!data) return null;
      return { type: 'med', name: selected, raw: data };
    } else {
      const data = DATA.eventos[selected];
      if (!data) return null;
      return { type: 'event', slug: selected, raw: data };
    }
  }, [selected, mode, DATA]);

  if (loadError) {
    return (
      <div style={styles.shell}>
        <div style={{ ...styles.disclaimer, borderLeftColor: '#a04040' }}>
          <strong style={{ color: '#a04040' }}>Error cargando los datos:</strong> {loadError}.
          Verifique que el archivo <code>data.json</code> está en el mismo directorio.
        </div>
      </div>
    );
  }
  if (!DATA) {
    return (
      <div style={styles.shell}>
        <div style={styles.loading}>
          <div style={styles.loadingSpinner} />
          <span>Cargando datos oficiales de CIMA AEMPS…</span>
        </div>
      </div>
    );
  }

  return (
    <div style={styles.shell}>
      <header style={styles.header}>
        <div style={styles.headerInner}>
          <div>
            <div style={styles.eyebrow}>Sala de infusión · Índice oficial</div>
            <h1 style={styles.title}>
              Eventos adversos<span style={styles.titleAccent}> oncológicos</span>
            </h1>
            <p style={styles.subtitle}>
              {DATA.metadata.total_drugs} medicamentos · {DATA.metadata.total_unique_events} eventos · {DATA.metadata.total_event_entries} entradas
              <span style={styles.subtitleSep}>·</span>
              <span style={styles.subtitleMuted}>Fuente: CIMA AEMPS</span>
            </p>
          </div>
        </div>
      </header>

      <div style={styles.disclaimer}>
        <Icon name="shield" size={16} style={{ flexShrink: 0, marginTop: 2, color: '#3d4a2e' }} />
        <div>
          <strong style={styles.disclaimerStrong}>Datos oficiales de ficha técnica.</strong>{' '}
          Reacciones adversas, frecuencias (MedDRA) y System Organ Class extraídos de las fichas técnicas vigentes en{' '}
          <a className="ext-link-inline" href="https://cima.aemps.es/cima/publico/lista.html" target="_blank" rel="noopener noreferrer">CIMA (AEMPS)</a>.
          Cada medicamento enlaza a su ficha técnica específica. Fuentes complementarias:{' '}
          <a className="ext-link-inline" href="https://dailymed.nlm.nih.gov" target="_blank" rel="noopener noreferrer">DailyMed (FDA)</a>{' y '}
          <a className="ext-link-inline" href="https://www.ema.europa.eu" target="_blank" rel="noopener noreferrer">EMA</a>.
        </div>
      </div>

      <div style={styles.modeToggle}>
        <button className="mode-pill" onClick={() => setMode('med')}
          style={{ ...styles.modePill, ...(mode === 'med' ? styles.modePillActive : {}) }}>
          <Icon name="pill" size={16} /><span>Por medicamento</span>
          <span style={styles.modeHint}>→ eventos asociados</span>
        </button>
        <div style={styles.swap}><Icon name="arrows" size={14} style={{ opacity: 0.4 }} /></div>
        <button className="mode-pill" onClick={() => setMode('event')}
          style={{ ...styles.modePill, ...(mode === 'event' ? styles.modePillActive : {}) }}>
          <Icon name="alert" size={16} /><span>Por evento adverso</span>
          <span style={styles.modeHint}>→ medicamentos asociados</span>
        </button>
      </div>

      <div style={styles.body}>
        <aside style={styles.listPane}>
          <div style={styles.searchBox}>
            <Icon name="search" size={16} style={{ color: '#8a6b3a', flexShrink: 0 }} />
            <input ref={inputRef} type="text"
              placeholder={mode === 'med' ? 'Buscar medicamento…' : 'Buscar evento adverso…'}
              value={query} onChange={(e) => setQuery(e.target.value)}
              style={styles.searchInput} />
            {query && (
              <button onClick={() => setQuery('')} style={styles.clearBtn}>
                <Icon name="x" size={14} />
              </button>
            )}
          </div>
          <div style={styles.listMeta}>
            {filtered.length} {filtered.length === 1 ? 'resultado' : 'resultados'}
          </div>
          <div style={styles.list}>
            {filtered.length === 0 ? (
              <div style={styles.empty}>Sin coincidencias.</div>
            ) : (
              filtered.map(key => {
                const isSel = selected === key;
                let name, count;
                if (mode === 'med') {
                  name = key;
                  count = DATA.medicamentos[key].events.length;
                } else {
                  name = DATA.eventos[key].event_name;
                  count = DATA.eventos[key].meds.length;
                }
                return (
                  <button key={key} className={`row-btn ${isSel ? 'selected' : ''}`}
                    onClick={() => setSelected(key)} style={styles.row}>
                    <span style={styles.rowName}>{name}</span>
                    <span className="row-count" style={styles.rowCount}>
                      {count}<Icon name="chevron" size={12} style={{ marginLeft: 2 }} />
                    </span>
                  </button>
                );
              })
            )}
          </div>
        </aside>

        <section style={styles.detailPane}>
          {!detail ? (
            <EmptyDetail mode={mode} />
          ) : detail.type === 'med' ? (
            <MedDetail detail={detail} DATA={DATA}
              freqFilter={freqFilter} setFreqFilter={setFreqFilter}
              socFilter={socFilter} setSocFilter={setSocFilter}
              setMode={setMode} setSelected={setSelected} />
          ) : (
            <EventDetail detail={detail} DATA={DATA}
              freqFilter={freqFilter} setFreqFilter={setFreqFilter}
              setMode={setMode} setSelected={setSelected} />
          )}
        </section>
      </div>

      <footer style={styles.footer}>
        <strong>Fuentes regulatorias:</strong>{' '}
        <a href="https://cima.aemps.es/cima/publico/lista.html" target="_blank" rel="noopener noreferrer" style={styles.footerLink}>CIMA (AEMPS)</a>
        {' · '}
        <a href="https://dailymed.nlm.nih.gov/dailymed/index.cfm" target="_blank" rel="noopener noreferrer" style={styles.footerLink}>DailyMed (FDA)</a>
        {' · '}
        <a href="https://www.ema.europa.eu" target="_blank" rel="noopener noreferrer" style={styles.footerLink}>EMA</a>
        <br />
        Las decisiones clínicas deben basarse en la valoración integral del paciente, las guías institucionales
        y la ficha técnica vigente del fabricante. La frecuencia se categoriza según convención MedDRA:
        Muy frecuente ≥1/10 · Frecuente ≥1/100 a &lt;1/10 · Poco frecuente ≥1/1.000 a &lt;1/100 ·
        Rara ≥1/10.000 a &lt;1/1.000 · Muy rara &lt;1/10.000.
      </footer>
    </div>
  );
}

function EmptyDetail({ mode }) {
  return (
    <div style={styles.emptyDetail}>
      <div style={styles.emptyIconRing}>
        <Icon name={mode === 'med' ? 'pill' : 'alert'} size={26} />
      </div>
      <h3 style={styles.emptyTitle}>
        {mode === 'med' ? 'Seleccione un medicamento' : 'Seleccione un evento adverso'}
      </h3>
      <p style={styles.emptyText}>
        {mode === 'med'
          ? 'Verá los eventos adversos documentados con frecuencia (MedDRA), System Organ Class, descripción y enlace a la ficha técnica oficial.'
          : 'Verá los medicamentos en cuya ficha técnica está documentado este evento, con la frecuencia reportada para cada uno.'}
      </p>
    </div>
  );
}

function FrequencyBadge({ cat, label }) {
  const meta = FREQ_META[cat] || FREQ_META.desconocida;
  const t = TONE_STYLES[meta.tone];
  return (
    <span style={{ ...styles.freqBadge, background: t.bg, color: t.fg, borderColor: t.border }}>
      {label || meta.label}
    </span>
  );
}

function FreqFilterRow({ value, onChange, counts, totalCount }) {
  return (
    <div style={styles.filterRow}>
      <span style={styles.filterLabel}>Frecuencia:</span>
      <button className="freq-chip" onClick={() => onChange('all')}
        style={{
          ...styles.freqChip,
          background: value === 'all' ? '#3d4a2e' : 'transparent',
          color: value === 'all' ? '#f7ead4' : '#3d4a2e',
          borderColor: '#3d4a2e',
        }}>
        Todas <span style={styles.chipCount}>{totalCount}</span>
      </button>
      {FREQ_ORDER.map(cat => {
        const meta = FREQ_META[cat];
        const c = counts[cat] || 0;
        const t = TONE_STYLES[meta.tone];
        const active = value === cat;
        return (
          <button key={cat} className="freq-chip" onClick={() => onChange(cat)}
            disabled={c === 0}
            style={{
              ...styles.freqChip,
              background: active ? t.bg : 'transparent',
              color: active ? t.fg : t.bg,
              borderColor: t.border,
              boxShadow: active ? '0 2px 8px rgba(58,42,24,0.18)' : 'none',
            }}
            title={meta.short}>
            {meta.label} <span style={styles.chipCount}>{c}</span>
          </button>
        );
      })}
    </div>
  );
}

function MedDetail({ detail, DATA, freqFilter, setFreqFilter, socFilter, setSocFilter, setMode, setSelected }) {
  const { name, raw } = detail;
  const allEvents = raw.events;

  const freqCounts = useMemo(() => {
    const c = {};
    allEvents.forEach(e => { c[e.freq_cat] = (c[e.freq_cat] || 0) + 1; });
    return c;
  }, [allEvents]);

  const socCounts = useMemo(() => {
    const c = {};
    allEvents.forEach(e => {
      if (freqFilter === 'all' || e.freq_cat === freqFilter) {
        c[e.soc] = (c[e.soc] || 0) + 1;
      }
    });
    return c;
  }, [allEvents, freqFilter]);

  const socsOrdered = useMemo(() =>
    Object.keys(socCounts).sort((a, b) => socCounts[b] - socCounts[a])
  , [socCounts]);

  const visibleEvents = useMemo(() => {
    let r = allEvents;
    if (freqFilter !== 'all') r = r.filter(e => e.freq_cat === freqFilter);
    if (socFilter !== 'all') r = r.filter(e => e.soc === socFilter);
    const freqIdx = FREQ_ORDER.reduce((a, c, i) => { a[c] = i; return a; }, {});
    return [...r].sort((a, b) => {
      const fa = freqIdx[a.freq_cat] ?? 99;
      const fb = freqIdx[b.freq_cat] ?? 99;
      if (fa !== fb) return fa - fb;
      if (a.soc !== b.soc) return a.soc.localeCompare(b.soc, 'es');
      return a.event.localeCompare(b.event, 'es');
    });
  }, [allEvents, freqFilter, socFilter]);

  const findEventSlug = (eventName) => {
    const target = norm(eventName);
    for (const slug of Object.keys(DATA.eventos)) {
      if (norm(DATA.eventos[slug].event_name) === target) return slug;
    }
    return null;
  };

  const crossNav = (eventName) => {
    const slug = findEventSlug(eventName);
    if (!slug) return;
    setMode('event');
    setTimeout(() => setSelected(slug), 30);
  };

  return (
    <div className="detail-card" key={name}>
      <div style={styles.detailHeader}>
        <div style={styles.detailLabel}>Medicamento</div>
        <h2 style={styles.detailTitle}>{name}</h2>
        <div style={styles.detailMeta}>
          {allEvents.length} eventos adversos documentados
          {visibleEvents.length !== allEvents.length && (
            <span style={{ color: '#8a6b3a', marginLeft: 8 }}>· {visibleEvents.length} tras filtro</span>
          )}
        </div>
      </div>

      <div style={styles.sourceBlock}>
        <div style={styles.sourceHeader}>
          <Icon name="file" size={14} style={{ color: '#3d4a2e' }} />
          <span style={styles.sourceTitle}>Ficha técnica oficial</span>
        </div>
        <a href={raw.source_url} target="_blank" rel="noopener noreferrer"
           className="src-link" style={styles.primarySrcLink}>
          <div>
            <div style={styles.srcLinkLabel}>Abrir ficha técnica en CIMA (AEMPS)</div>
            <div style={styles.srcLinkSub}>{raw.source_url}</div>
          </div>
          <Icon name="ext" size={16} style={{ color: '#8a6b3a' }} />
        </a>
        <div style={styles.altSources}>
          <a href={`https://dailymed.nlm.nih.gov/dailymed/search.cfm?query=${encodeURIComponent(name)}`}
             target="_blank" rel="noopener noreferrer" style={styles.altSrcChip}>
            <Icon name="ext" size={11} /> DailyMed
          </a>
          <a href={`https://www.ema.europa.eu/en/search?search_api_fulltext=${encodeURIComponent(name)}`}
             target="_blank" rel="noopener noreferrer" style={styles.altSrcChip}>
            <Icon name="ext" size={11} /> EMA
          </a>
        </div>
      </div>

      <FreqFilterRow value={freqFilter} onChange={setFreqFilter}
        counts={freqCounts} totalCount={allEvents.length} />

      {socsOrdered.length > 1 && (
        <div style={styles.socFilterBlock}>
          <div style={styles.filterLabel}>
            <Icon name="layers" size={12} style={{ marginRight: 4, verticalAlign: -1 }} />
            System Organ Class:
          </div>
          <div style={styles.socFilterRow}>
            <button className={`soc-chip ${socFilter === 'all' ? 'active' : ''}`}
              onClick={() => setSocFilter('all')} style={styles.socChip}>
              Todos <span style={styles.chipCount}>{Object.values(socCounts).reduce((a,b)=>a+b,0)}</span>
            </button>
            {socsOrdered.map(soc => (
              <button key={soc}
                className={`soc-chip ${socFilter === soc ? 'active' : ''}`}
                onClick={() => setSocFilter(soc)} style={styles.socChip}>
                {soc} <span style={styles.chipCount}>{socCounts[soc]}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      <div style={styles.itemsHeader}>
        Eventos adversos
        <span style={styles.itemsHeaderHint}>· clic en cualquier evento para ver otros medicamentos asociados</span>
      </div>

      <div style={styles.eventsList}>
        {visibleEvents.length === 0 ? (
          <div style={styles.empty}>Sin eventos con este filtro.</div>
        ) : (
          visibleEvents.map((e, i) => (
            <button key={e.event + i} className="cross-card"
              onClick={() => crossNav(e.event)} style={styles.eventCard}>
              <div style={styles.eventTopRow}>
                <span style={styles.eventName}>{e.event}</span>
                <FrequencyBadge cat={e.freq_cat} label={FREQ_META[e.freq_cat]?.label} />
              </div>
              <div style={styles.eventSoc}>{e.soc}</div>
              {e.description && <p style={styles.eventDesc}>{e.description}</p>}
              <div style={styles.eventFooter}>
                Ver medicamentos asociados <Icon name="chevron" size={11} />
              </div>
            </button>
          ))
        )}
      </div>
    </div>
  );
}

function EventDetail({ detail, DATA, freqFilter, setFreqFilter, setMode, setSelected }) {
  const { raw } = detail;
  const allMeds = raw.meds;

  const freqCounts = useMemo(() => {
    const c = {};
    allMeds.forEach(m => { c[m.freq_cat] = (c[m.freq_cat] || 0) + 1; });
    return c;
  }, [allMeds]);

  const visibleMeds = useMemo(() => {
    let r = allMeds;
    if (freqFilter !== 'all') r = r.filter(m => m.freq_cat === freqFilter);
    const freqIdx = FREQ_ORDER.reduce((a, c, i) => { a[c] = i; return a; }, {});
    return [...r].sort((a, b) => {
      const fa = freqIdx[a.freq_cat] ?? 99;
      const fb = freqIdx[b.freq_cat] ?? 99;
      if (fa !== fb) return fa - fb;
      return a.drug.localeCompare(b.drug, 'es');
    });
  }, [allMeds, freqFilter]);

  const crossNav = (drugName) => {
    if (!DATA.medicamentos[drugName]) return;
    setMode('med');
    setTimeout(() => setSelected(drugName), 30);
  };

  return (
    <div className="detail-card" key={detail.slug}>
      <div style={styles.detailHeader}>
        <div style={styles.detailLabel}>Evento adverso</div>
        <h2 style={styles.detailTitle}>{raw.event_name}</h2>
        {raw.soc && raw.soc !== 'Sin clasificar' && (
          <div style={styles.eventSocLabel}>
            <Icon name="layers" size={11} style={{ verticalAlign: -1, marginRight: 4 }} />
            {raw.soc}
          </div>
        )}
        {raw.description && <p style={styles.detailDefinition}>{raw.description}</p>}
        <div style={styles.detailMeta}>
          Reportado en {allMeds.length} medicamento{allMeds.length === 1 ? '' : 's'}
          {visibleMeds.length !== allMeds.length && (
            <span style={{ color: '#8a6b3a', marginLeft: 8 }}>· {visibleMeds.length} tras filtro</span>
          )}
        </div>
      </div>

      <FreqFilterRow value={freqFilter} onChange={setFreqFilter}
        counts={freqCounts} totalCount={allMeds.length} />

      <div style={styles.itemsHeader}>
        Medicamentos asociados
        <span style={styles.itemsHeaderHint}>· clic en el nombre para ver todos sus eventos · enlace abre ficha técnica</span>
      </div>

      <div style={styles.medsList}>
        {visibleMeds.length === 0 ? (
          <div style={styles.empty}>Sin medicamentos con este filtro.</div>
        ) : (
          visibleMeds.map((m, i) => (
            <div key={m.drug + i} style={styles.medCard}>
              <button className="cross-card" onClick={() => crossNav(m.drug)}
                style={styles.medCardMain}>
                <span style={styles.medCardName}>{m.drug}</span>
                <FrequencyBadge cat={m.freq_cat} label={FREQ_META[m.freq_cat]?.label} />
              </button>
              {m.source_url && (
                <a href={m.source_url} target="_blank" rel="noopener noreferrer"
                   style={styles.medCardFtLink} title="Abrir ficha técnica en CIMA">
                  <Icon name="file" size={12} /><span>Ficha</span><Icon name="ext" size={10} />
                </a>
              )}
            </div>
          ))
        )}
      </div>
    </div>
  );
}

const styles = {
  shell: { fontFamily: "'IBM Plex Sans', sans-serif", background: '#f7f1e1', backgroundImage: `radial-gradient(at 12% 0%, rgba(61,74,46,0.06) 0%, transparent 50%), radial-gradient(at 88% 100%, rgba(138,107,58,0.08) 0%, transparent 50%)`, color: '#2d2418', minHeight: '100vh', padding: '32px 28px 24px', maxWidth: 1320, margin: '0 auto' },
  loading: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 14, padding: 80, color: '#8a6b3a', fontSize: 14 },
  loadingSpinner: { width: 20, height: 20, border: '2px solid #d4c4a0', borderTopColor: '#3d4a2e', borderRadius: '50%', animation: 'spin 0.8s linear infinite' },
  header: { borderBottom: '1px solid #d4c4a0', paddingBottom: 20, marginBottom: 16 },
  headerInner: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 24, flexWrap: 'wrap' },
  eyebrow: { fontFamily: "'IBM Plex Mono', monospace", fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#8a6b3a', marginBottom: 8 },
  title: { fontFamily: "'Fraunces', serif", fontSize: 40, lineHeight: 1.05, fontWeight: 500, margin: 0, color: '#2d2418', letterSpacing: '-0.015em' },
  titleAccent: { fontStyle: 'italic', fontWeight: 400, color: '#3d4a2e' },
  subtitle: { margin: '10px 0 0', color: '#5a4a30', fontSize: 14 },
  subtitleSep: { margin: '0 8px', color: '#c9b88f' },
  subtitleMuted: { color: '#8a6b3a', fontStyle: 'italic' },
  disclaimer: { display: 'flex', gap: 12, background: '#fbf5e6', border: '1px solid #d4c4a0', borderLeft: '3px solid #3d4a2e', padding: '14px 18px', marginBottom: 18, fontSize: 13, lineHeight: 1.55, color: '#3a3024' },
  disclaimerStrong: { color: '#3d4a2e' },
  modeToggle: { display: 'flex', alignItems: 'center', gap: 0, marginBottom: 18, flexWrap: 'wrap' },
  modePill: { display: 'flex', alignItems: 'center', gap: 10, padding: '12px 18px', background: '#fff', border: '1px solid #d4c4a0', color: '#5a4a30', fontFamily: 'inherit', fontSize: 14, fontWeight: 500, cursor: 'pointer', borderRadius: 0, transition: 'all 0.2s ease' },
  modePillActive: { background: '#3d4a2e', color: '#f7ead4', borderColor: '#3d4a2e' },
  modeHint: { fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, opacity: 0.6, letterSpacing: '0.05em', marginLeft: 4 },
  swap: { width: 36, height: 44, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#fff', borderTop: '1px solid #d4c4a0', borderBottom: '1px solid #d4c4a0' },
  body: { display: 'grid', gridTemplateColumns: '320px 1fr', gap: 18, alignItems: 'flex-start' },
  listPane: { background: '#fff', border: '1px solid #d4c4a0', padding: 14, position: 'sticky', top: 16, maxHeight: 'calc(100vh - 60px)', display: 'flex', flexDirection: 'column' },
  searchBox: { display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', border: '1px solid #d4c4a0', background: '#faf5e6', marginBottom: 10 },
  searchInput: { flex: 1, border: 'none', outline: 'none', background: 'transparent', fontFamily: 'inherit', fontSize: 14, color: '#2d2418' },
  clearBtn: { background: 'none', border: 'none', color: '#8a6b3a', cursor: 'pointer', padding: 2, display: 'flex' },
  listMeta: { fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, color: '#8a6b3a', letterSpacing: '0.08em', textTransform: 'uppercase', padding: '4px 4px 8px', borderBottom: '1px solid #ede4d0', marginBottom: 4 },
  list: { overflowY: 'auto', flex: 1, paddingRight: 2 },
  row: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%', background: 'transparent', border: 'none', borderBottom: '1px solid #f0e8d4', padding: '11px 10px', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13.5, color: '#2d2418', textAlign: 'left', transition: 'background 0.12s' },
  rowName: { flex: 1, paddingRight: 8 },
  rowCount: { display: 'inline-flex', alignItems: 'center', fontFamily: "'IBM Plex Mono', monospace", fontSize: 11, color: '#8a6b3a', fontWeight: 500 },
  empty: { padding: '20px 10px', fontSize: 13, color: '#8a6b3a', fontStyle: 'italic' },
  detailPane: { background: '#fff', border: '1px solid #d4c4a0', padding: '26px 30px', minHeight: 500 },
  emptyDetail: { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '80px 20px', color: '#8a6b3a', textAlign: 'center' },
  emptyIconRing: { width: 64, height: 64, borderRadius: '50%', background: '#f7f1e1', border: '1px solid #d4c4a0', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#3d4a2e', marginBottom: 18 },
  emptyTitle: { fontFamily: "'Fraunces', serif", fontSize: 20, fontWeight: 500, margin: 0, color: '#3d4a2e' },
  emptyText: { marginTop: 10, fontSize: 14, maxWidth: 420, lineHeight: 1.55 },
  detailHeader: { paddingBottom: 16, borderBottom: '1px solid #ede4d0', marginBottom: 18 },
  detailLabel: { fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#8a6b3a', marginBottom: 6 },
  detailTitle: { fontFamily: "'Fraunces', serif", fontSize: 28, fontWeight: 500, margin: 0, color: '#2d2418', letterSpacing: '-0.015em' },
  eventSocLabel: { marginTop: 8, fontFamily: "'IBM Plex Mono', monospace", fontSize: 11, color: '#5a4a30', letterSpacing: '0.04em' },
  detailDefinition: { marginTop: 12, fontSize: 14, lineHeight: 1.6, color: '#3a3024', fontFamily: "'Fraunces', serif", fontWeight: 400, fontStyle: 'italic' },
  detailMeta: { marginTop: 12, fontFamily: "'IBM Plex Mono', monospace", fontSize: 11, color: '#5a4a30', letterSpacing: '0.04em' },
  sourceBlock: { background: '#faf5e6', border: '1px solid #d4c4a0', padding: '14px 16px', marginBottom: 18 },
  sourceHeader: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 },
  sourceTitle: { fontFamily: "'Fraunces', serif", fontSize: 14, fontWeight: 500, color: '#3d4a2e' },
  primarySrcLink: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, padding: '12px 14px', background: '#fff', border: '1px solid #d4c4a0', textDecoration: 'none', color: '#2d2418', transition: 'all 0.15s', cursor: 'pointer', marginBottom: 8 },
  srcLinkLabel: { fontSize: 13.5, fontWeight: 600, color: 'inherit', marginBottom: 3 },
  srcLinkSub: { fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, color: '#8a6b3a', letterSpacing: '0.02em', wordBreak: 'break-all' },
  altSources: { display: 'flex', gap: 8, flexWrap: 'wrap' },
  altSrcChip: { display: 'inline-flex', alignItems: 'center', gap: 5, padding: '5px 10px', background: '#fff', border: '1px solid #d4c4a0', fontSize: 11.5, color: '#5a4a30', textDecoration: 'none', fontFamily: 'inherit' },
  filterRow: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginBottom: 12 },
  filterLabel: { fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, color: '#5a4a30', letterSpacing: '0.08em', textTransform: 'uppercase', marginRight: 6 },
  freqChip: { display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 11px', fontSize: 12, fontFamily: 'inherit', fontWeight: 500, border: '1px solid', borderRadius: 999, cursor: 'pointer' },
  chipCount: { fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, fontWeight: 600, opacity: 0.85 },
  socFilterBlock: { background: '#fbf5e6', border: '1px solid #ede4d0', padding: '10px 12px', marginBottom: 16 },
  socFilterRow: { display: 'flex', gap: 5, flexWrap: 'wrap', marginTop: 6 },
  socChip: { display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 9px', fontSize: 11.5, fontFamily: 'inherit', fontWeight: 500, background: '#fff', border: '1px solid #d4c4a0', color: '#3a3024', cursor: 'pointer' },
  itemsHeader: { fontFamily: "'IBM Plex Mono', monospace", fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#5a4a30', marginBottom: 10, paddingBottom: 8, borderBottom: '1px solid #ede4d0' },
  itemsHeaderHint: { marginLeft: 8, color: '#8a6b3a', fontStyle: 'italic', textTransform: 'none', letterSpacing: 0 },
  eventsList: { display: 'flex', flexDirection: 'column', gap: 8 },
  eventCard: { background: '#faf5e6', border: '1px solid #ede4d0', borderLeft: '3px solid #3d4a2e', padding: '12px 14px', cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', color: '#2d2418', transition: 'all 0.15s' },
  eventTopRow: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10, marginBottom: 4 },
  eventName: { fontSize: 14, fontWeight: 500, color: '#2d2418', flex: 1 },
  eventSoc: { fontFamily: "'IBM Plex Mono', monospace", fontSize: 10, color: '#8a6b3a', letterSpacing: '0.04em', marginBottom: 6 },
  eventDesc: { margin: '4px 0 6px', fontSize: 12.5, lineHeight: 1.55, color: '#4a3a26' },
  eventFooter: { fontFamily: "'IBM Plex Mono', monospace", fontSize: 9.5, color: '#8a6b3a', letterSpacing: '0.08em', textTransform: 'uppercase', display: 'inline-flex', alignItems: 'center', gap: 3 },
  medsList: { display: 'flex', flexDirection: 'column', gap: 6 },
  medCard: { display: 'flex', alignItems: 'stretch', gap: 0, background: '#faf5e6', border: '1px solid #ede4d0', borderLeft: '3px solid #c9a96a' },
  medCardMain: { flex: 1, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, background: 'transparent', border: 'none', padding: '10px 14px', cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', color: '#2d2418', transition: 'background 0.15s' },
  medCardName: { fontSize: 14, fontWeight: 500 },
  medCardFtLink: { display: 'inline-flex', alignItems: 'center', gap: 5, padding: '0 14px', background: '#fff', color: '#3d4a2e', fontSize: 11, fontFamily: 'inherit', textDecoration: 'none', borderLeft: '1px solid #ede4d0', fontWeight: 500, letterSpacing: '0.02em' },
  freqBadge: { display: 'inline-block', padding: '3px 9px', fontSize: 10.5, fontFamily: "'IBM Plex Mono', monospace", fontWeight: 500, letterSpacing: '0.02em', border: '1px solid', whiteSpace: 'nowrap', flexShrink: 0 },
  footer: { marginTop: 26, paddingTop: 18, borderTop: '1px solid #d4c4a0', fontSize: 11.5, color: '#8a6b3a', lineHeight: 1.7, maxWidth: 920 },
  footerLink: { color: '#3d4a2e', textDecoration: 'none', fontWeight: 500, borderBottom: '1px dotted #8a6b3a' },
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
