// Screen: Schädlings-Bibliothek — Liste der häufigsten Plage-Geister
// mit Detail-Ansicht (Symptome, Erkennen, Bio-Behandlung, Vorbeugung).
// Wird über Erkennen-Tab erreicht ("Etwas an meiner Pflanze ist nicht
// in Ordnung").

const NLH_TONE_SCH = {
  warm: {
    h:        "Schädlinge",
    s:        "Wenn etwas an deiner Pflanze nicht stimmt — hier findest du die häufigsten Plage-Geister mit Behandlungs-Tipps.",
    suche:    "Was siehst du?",
    leer:     "Nichts gefunden. Versuch's mit „Gespinst", „weiß", „Blattläuse" …",
    indoor:   "Drinnen",
    outdoor:  "Draußen",
    beides:   "Beides",
    symptome:    "Symptome",
    erkennen:    "So erkennst du sie",
    ursache:     "Warum sind sie da?",
    behandlung:  "Was tun — sanft zuerst",
    vorbeugung:  "Damit's nicht wiederkommt",
    haeufig:     "Häufig",
    selten:      "Seltener",
    hinweis:     "Bio-Mittel und Hausmittel zuerst. Wenn's gar nicht reicht: lieber jemand erfahrenes fragen, statt zur Chemie zu greifen.",
  },
  knapp: {
    h:        "Schädlinge",
    s:        "Was tun, wenn was nicht stimmt.",
    suche:    "Suchen",
    leer:     "Nix gefunden.",
    indoor:   "Drinnen",
    outdoor:  "Draußen",
    beides:   "Beides",
    symptome:    "Symptome",
    erkennen:    "Erkennen",
    ursache:     "Ursache",
    behandlung:  "Behandlung",
    vorbeugung:  "Vorbeugung",
    haeufig:     "Häufig",
    selten:      "Selten",
    hinweis:     "Bio zuerst.",
  },
};
function useToneSch(t) { return NLH_TONE_SCH[t === 'knapp' ? 'knapp' : 'warm']; }

function ScreenSchaedlinge({ tone = "warm" }) {
  const T = useToneSch(tone);
  const nav = useNav();
  const [selected, setSel] = React.useState(nav.context.schaedlingId || null);
  const [q, setQ] = React.useState('');

  const alle = window.NLH_SCHAEDLINGE || [];
  const sel = alle.find(s => s.id === selected);

  // Filtern: Name, Latein, Symptome, kurz — alles mit reinwerfen.
  const term = q.trim().toLowerCase();
  const treffer = !term
    ? alle
    : alle.filter(s => {
        const blob = [
          s.name, s.latein, s.kurz, s.erkennen,
          ...(s.symptome || []),
        ].join(' ').toLowerCase();
        return blob.includes(term);
      });

  return (
    <PhoneShell label="Schädlinge">
      <ZGlobalCSS />
      <div style={{ flex: 1, overflow: 'auto', paddingBottom: 16 }}>
        <NavBar />

        {selected && sel ? (
          <SchaedlingDetail s={sel} T={T} onBack={() => setSel(null)} />
        ) : (
          <SchaedlingListe alle={treffer} T={T} q={q} setQ={setQ}
                            onPick={(id) => setSel(id)} />
        )}
      </div>
      <BottomNav active="" />
    </PhoneShell>
  );
}

function SchaedlingListe({ alle, T, q, setQ, onPick }) {
  return (
    <>
      {/* Kopf */}
      <header style={{ padding: '6px 20px 14px' }}>
        <p className="label">{T.h}</p>
        <h1 style={{ fontSize: 28, lineHeight: 1.1, marginTop: 6,
                     textWrap: 'balance' }}>{T.h}</h1>
        <p style={{ fontSize: 13.5, color: 'var(--text-leise)', marginTop: 8,
                    lineHeight: 1.5, textWrap: 'pretty' }}>{T.s}</p>
      </header>

      {/* Suche */}
      <div style={{ padding: '0 20px 14px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '8px 12px', borderRadius: 12,
          background: 'var(--creme-card)',
          border: '1px solid var(--creme-tief)',
        }}>
          <Icon name="search" size={14} color="var(--text-sekundaer)" />
          <input type="search" value={q}
                 onChange={e => setQ(e.target.value)}
                 placeholder={T.suche}
                 style={{
                   flex: 1, boxSizing: 'border-box',
                   background: 'transparent', border: 0, outline: 0,
                   padding: '4px 0',
                   fontFamily: 'var(--font-haupt)', fontSize: 14,
                   color: 'var(--text-primaer)',
                 }} />
        </div>
      </div>

      {/* Liste */}
      <div style={{ padding: '0 20px',
                    display: 'flex', flexDirection: 'column', gap: 8 }}>
        {alle.length === 0 ? (
          <p style={{ padding: '16px 12px', fontSize: 13.5,
                      color: 'var(--text-leise)', textAlign: 'center',
                      lineHeight: 1.5, textWrap: 'pretty' }}>
            {T.leer}
          </p>
        ) : (
          alle.map(s => (
            <SchaedlingZeile key={s.id} s={s} T={T}
                              onClick={() => onPick(s.id)} />
          ))
        )}
      </div>
    </>
  );
}

function SchaedlingZeile({ s, T, onClick }) {
  const typLabel = s.bei_pflanze === 'innen' ? T.indoor
                  : s.bei_pflanze === 'außen'  ? T.outdoor
                                                : T.beides;
  return (
    <button onClick={onClick} type="button" className="card" style={{
      all: 'unset', cursor: 'pointer', boxSizing: 'border-box',
      display: 'flex', alignItems: 'flex-start', gap: 12,
      padding: 'var(--s-4)',
      background: 'var(--creme-card)',
      borderRadius: 'var(--r-card)',
      boxShadow: 'var(--shadow-card)',
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10, flex: 'none',
        background: s.typ === 'pilz'
          ? 'var(--creme-tief)'
          : 'var(--warn-soft)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={s.typ === 'pilz' ? 'cloud' : 'alert'} size={16}
              color={s.typ === 'pilz' ? 'var(--text-sekundaer)' : 'var(--warnung)'} />
      </div>
      <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6,
                      flexWrap: 'wrap' }}>
          <p style={{ fontSize: 15, color: 'var(--text-primaer)',
                      fontWeight: 500 }}>{s.name}</p>
          {s.haeufig && (
            <span className="mono" style={{ fontSize: 10,
                                              color: 'var(--text-leise)',
                                              padding: '1px 6px',
                                              background: 'var(--creme-tief)',
                                              borderRadius: 999 }}>
              {T.haeufig}
            </span>
          )}
        </div>
        <p style={{ fontSize: 11.5, color: 'var(--text-leise)',
                    fontStyle: 'italic', marginTop: 2 }}>{s.latein}</p>
        <p style={{ fontSize: 12.5, color: 'var(--text-sekundaer)',
                    marginTop: 4, lineHeight: 1.45, textWrap: 'pretty' }}>
          {s.kurz}
        </p>
        <p className="mono" style={{ fontSize: 10.5,
                                      color: 'var(--text-leise)',
                                      marginTop: 4 }}>
          {typLabel}
        </p>
      </div>
      <Icon name="chevron_r" size={14} color="var(--text-leise)" />
    </button>
  );
}

function SchaedlingDetail({ s, T, onBack }) {
  return (
    <>
      <button onClick={onBack} type="button" style={{
        all: 'unset', cursor: 'pointer',
        padding: '6px 20px 10px',
        display: 'inline-flex', alignItems: 'center', gap: 4,
        color: 'var(--text-leise)', fontSize: 13,
      }}>
        <Icon name="chevron_r" size={14} style={{ transform: 'rotate(180deg)' }} />
        Alle Schädlinge
      </button>

      <header style={{ padding: '6px 20px 14px' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12, flex: 'none',
            background: s.typ === 'pilz'
              ? 'var(--creme-tief)'
              : 'var(--warn-soft)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name={s.typ === 'pilz' ? 'cloud' : 'alert'} size={22}
                  color={s.typ === 'pilz' ? 'var(--text-sekundaer)' : 'var(--warnung)'} />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <h1 style={{ fontSize: 24, lineHeight: 1.2,
                         textWrap: 'balance' }}>{s.name}</h1>
            <p style={{ fontSize: 12.5, color: 'var(--text-leise)',
                        fontStyle: 'italic', marginTop: 2 }}>{s.latein}</p>
          </div>
        </div>
        <p style={{ fontSize: 14, color: 'var(--text-sekundaer)', marginTop: 12,
                    lineHeight: 1.55, textWrap: 'pretty' }}>
          {s.kurz}
        </p>
      </header>

      {/* Symptome */}
      {s.symptome && s.symptome.length > 0 && (
        <section style={{ padding: '0 20px 18px' }}>
          <div className="label" style={{ marginBottom: 8 }}>{T.symptome}</div>
          <div className="card">
            <ul style={{ listStyle: 'none', padding: 0, margin: 0,
                          display: 'flex', flexDirection: 'column', gap: 6 }}>
              {s.symptome.map((sy, i) => (
                <li key={i} style={{ display: 'flex', alignItems: 'flex-start',
                                      gap: 8, fontSize: 13.5,
                                      color: 'var(--text-primaer)',
                                      lineHeight: 1.5, textWrap: 'pretty' }}>
                  <span style={{ marginTop: 7, width: 4, height: 4,
                                  borderRadius: 2,
                                  background: 'var(--salbei-pressed)',
                                  flex: 'none' }} />
                  <span>{sy}</span>
                </li>
              ))}
            </ul>
          </div>
        </section>
      )}

      {/* Erkennen */}
      {s.erkennen && (
        <section style={{ padding: '0 20px 18px' }}>
          <div className="label" style={{ marginBottom: 8 }}>{T.erkennen}</div>
          <div className="card">
            <p style={{ fontSize: 13.5, color: 'var(--text-primaer)',
                        lineHeight: 1.55, textWrap: 'pretty' }}>
              {s.erkennen}
            </p>
          </div>
        </section>
      )}

      {/* Ursache */}
      {s.ursache && (
        <section style={{ padding: '0 20px 18px' }}>
          <div className="label" style={{ marginBottom: 8 }}>{T.ursache}</div>
          <div className="card" style={{ background: 'var(--creme-card)' }}>
            <p style={{ fontSize: 13.5, color: 'var(--text-sekundaer)',
                        lineHeight: 1.55, textWrap: 'pretty' }}>
              {s.ursache}
            </p>
          </div>
        </section>
      )}

      {/* Behandlung — Bio zuerst, jede Maßnahme als eigene Karte */}
      {s.behandlung_bio && s.behandlung_bio.length > 0 && (
        <section style={{ padding: '0 20px 18px' }}>
          <div className="label" style={{ marginBottom: 8 }}>{T.behandlung}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {s.behandlung_bio.map((b, i) => (
              <div key={i} style={{
                padding: '12px 14px', borderRadius: 10,
                background: 'var(--salbei-nebel)',
                border: '1px solid var(--salbei-blass)',
              }}>
                <p style={{ fontSize: 14, color: 'var(--salbei-pressed)',
                            fontWeight: 500, lineHeight: 1.3 }}>
                  {b.name}
                </p>
                <p style={{ fontSize: 13, color: 'var(--text-sekundaer)',
                            marginTop: 6, lineHeight: 1.55,
                            textWrap: 'pretty' }}>
                  {typeof ProduktText !== 'undefined'
                    ? <ProduktText text={b.wie} />
                    : b.wie}
                </p>
              </div>
            ))}
          </div>
          <p style={{ fontSize: 11.5, color: 'var(--text-leise)',
                      marginTop: 8, lineHeight: 1.5, textWrap: 'pretty',
                      fontStyle: 'italic' }}>
            {T.hinweis}
          </p>
        </section>
      )}

      {/* Vorbeugung */}
      {s.vorbeugung && (
        <section style={{ padding: '0 20px 24px' }}>
          <div className="label" style={{ marginBottom: 8 }}>{T.vorbeugung}</div>
          <div className="card" style={{ background: 'var(--salbei-blass)' }}>
            <p style={{ fontSize: 13.5, color: 'var(--text-primaer)',
                        lineHeight: 1.55, textWrap: 'pretty' }}>
              {typeof ProduktText !== 'undefined'
                ? <ProduktText text={s.vorbeugung} />
                : s.vorbeugung}
            </p>
          </div>
        </section>
      )}
    </>
  );
}

// ─── Typische-Schädlinge-Karte ────────────────────────────────
// Wird auf der Pflanzen-Detail-Seite (eigene) und im Wiki gezeigt, wenn
// die Bibliothek für diese Sorte typische Plagen kennt. Klick auf eine
// Pille führt direkt zum Schädling-Detail.
//
// variante = 'eigene'  → Framing "Bei ihr typisch — falls was komisch ist"
// variante = 'wiki'    → Framing "Diese Plagen kommen bei der Art häufiger vor"
function TypischeSchaedlingeKarte({ p, variante, nav }) {
  if (!p || !Array.isArray(p.typische_schaedlinge) || p.typische_schaedlinge.length === 0) {
    return null;
  }
  const alle = window.NLH_SCHAEDLINGE || [];

  // Auflösen: ID → Schädling-Objekt. Unbekannte werden übersprungen.
  const treffer = p.typische_schaedlinge
    .map(id => alle.find(s => s.id === id))
    .filter(Boolean);
  if (treffer.length === 0) return null;

  const istEigene = variante === 'eigene';

  return (
    <section style={{ padding: '0 20px 18px' }}>
      <div className="label" style={{ marginBottom: 8 }}>
        {istEigene
          ? 'Was bei ihr schiefgehen könnte'
          : 'Typische Plagen bei dieser Art'}
      </div>
      <div className="card" style={{ background: 'var(--warn-soft)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
          <div style={{
            width: 32, height: 32, borderRadius: 8, flex: 'none',
            background: 'var(--creme-card)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="alert" size={16} color="var(--warnung)" />
          </div>
          <p style={{ flex: 1, fontSize: 12.5, color: 'var(--warn-tief)',
                      lineHeight: 1.55, textWrap: 'pretty' }}>
            {istEigene
              ? 'Wenn du was Komisches siehst — checke hier zuerst. Tipp auf eine Plage für die Beschreibung und Behandlungs-Tipps.'
              : 'Bevor du sie zu dir holst: das könnte sie kriegen, mit etwas Pech. Tipp drauf für Erkennen und Bio-Behandlung.'}
          </p>
        </div>

        <div style={{ marginTop: 12, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {treffer.map(s => (
            <button key={s.id} type="button"
                    onClick={() => nav.go('schaedlinge', { schaedlingId: s.id })}
                    style={{
              all: 'unset', cursor: 'pointer', boxSizing: 'border-box',
              display: 'inline-flex', alignItems: 'center', gap: 5,
              padding: '6px 12px', borderRadius: 999,
              background: 'var(--creme-card)',
              border: '1px solid var(--warn-tief)',
              color: 'var(--warn-tief)',
              fontSize: 12.5, fontWeight: 500, lineHeight: 1, whiteSpace: 'nowrap',
            }}>
              <Icon name={s.typ === 'pilz' ? 'cloud' : 'alert'} size={11}
                    color="currentColor" />
              {s.name}
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

window.ScreenSchaedlinge = ScreenSchaedlinge;
window.TypischeSchaedlingeKarte = TypischeSchaedlingeKarte;
