// Global search overlay — searches tenants (rentals) + equipment
const { useState: useStateS, useMemo: useMemoS, useEffect: useEffectS, useRef: useRefS } = React;

function SearchOverlay({ open, onClose, equipment = [], rentals = [], go }) {
  const t = useTheme();
  const [q, setQ] = useStateS('');
  const [visible, setVisible] = useStateS(open);
  const inputRef = useRefS(null);

  useEffectS(() => {
    if (open) { setVisible(true); return; }
    const id = setTimeout(() => setVisible(false), 340);
    return () => clearTimeout(id);
  }, [open]);

  useEffectS(() => {
    if (open) { setQ(''); setTimeout(() => inputRef.current && inputRef.current.focus(), 250); }
  }, [open]);

  const query = q.trim().toLowerCase();

  // Unique tenants from rentals (Stammkunden)
  const tenants = useMemoS(() => {
    const map = {};
    rentals.forEach(r => {
      const key = r.tenantName.toLowerCase();
      if (!map[key]) map[key] = { name: r.tenantName, count: 0, last: '', phone: r.phone, email: r.email };
      map[key].count += 1;
      if (r.start > map[key].last) map[key].last = r.start;
    });
    return Object.values(map);
  }, [rentals]);

  const tenantHits = query ? tenants.filter(x =>
    x.name.toLowerCase().includes(query) ||
    (x.phone || '').toLowerCase().includes(query) ||
    (x.email || '').toLowerCase().includes(query)) : [];

  const eqHits = query ? equipment.filter(e =>
    e.name.toLowerCase().includes(query) ||
    (e.cat || '').toLowerCase().includes(query) ||
    (e.kind || '').toLowerCase().includes(query)) : [];

  const rentalHits = query ? rentals.filter(r =>
    (r.purpose || '').toLowerCase().includes(query) ||
    (r.equipmentName || '').toLowerCase().includes(query)) : [];

  const empty = query && tenantHits.length === 0 && eqHits.length === 0 && rentalHits.length === 0;

  const Section = ({ title, count }) => (
    <div style={{ padding: '16px 20px 6px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
      <div style={{ fontSize: 12, fontWeight: 700, color: t.textSec, textTransform: 'uppercase', letterSpacing: 0.6 }}>{title}</div>
      <div style={{ fontSize: 11, color: t.textTer, fontWeight: 600 }}>{count}</div>
    </div>
  );

  const nav = (fn) => { onClose(); setTimeout(fn, 60); };

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 95, background: t.bg,
      transform: open ? 'translateY(0)' : 'translateY(100%)',
      opacity: open ? 1 : 0,
      visibility: (open || visible) ? 'visible' : 'hidden',
      transition: 'transform 0.3s cubic-bezier(0.2,0.7,0.3,1), opacity 0.2s',
      pointerEvents: open ? 'auto' : 'none',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Search header */}
      <div style={{ padding: '52px 16px 12px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1, background: t.chip, borderRadius: 12, padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon d={icons.search} color={t.textSec} size={16} sw={2}/>
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)}
            placeholder="Mieter oder Equipment suchen"
            style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 15, color: t.text, fontFamily: 'inherit' }}/>
          {q && (
            <Pressable onClick={() => setQ('')} scale={0.85}>
              <div style={{ width: 18, height: 18, borderRadius: 9, background: t.textTer, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <svg width="9" height="9" viewBox="0 0 12 12" fill="none" stroke={t.bg} strokeWidth="2.4" strokeLinecap="round"><path d="M3 3l6 6M9 3l-6 6"/></svg>
              </div>
            </Pressable>
          )}
        </div>
        <Pressable onClick={onClose} scale={0.95}>
          <div style={{ fontSize: 15, color: t.accent, fontWeight: 500 }}>Fertig</div>
        </Pressable>
      </div>

      <div style={{ flex: 1, overflow: 'auto', paddingBottom: 30 }}>
        {!query && (
          <div style={{ padding: '60px 40px', textAlign: 'center' }}>
            <div style={{ fontSize: 40, marginBottom: 12 }}>🔎</div>
            <div style={{ fontSize: 14, color: t.textSec, lineHeight: 1.5 }}>
              Suche nach <strong style={{ color: t.text }}>Mietern</strong>, <strong style={{ color: t.text }}>Equipment</strong> oder Verwendungszweck.
            </div>
          </div>
        )}

        {empty && (
          <div style={{ padding: '60px 40px', textAlign: 'center', color: t.textSec, fontSize: 14 }}>
            Keine Treffer für „{q}“.
          </div>
        )}

        {/* Tenants */}
        {tenantHits.length > 0 && <Section title="Mieter" count={tenantHits.length}/>}
        <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {tenantHits.map(x => {
            const rentalForTenant = rentals.find(r => r.tenantName === x.name);
            return (
              <Pressable key={x.name} onClick={() => nav(() => go('doc', { rentalId: rentalForTenant ? rentalForTenant.id : null }))} scale={0.98}>
                <div style={{ background: t.card, borderRadius: 16, padding: 12, display: 'flex', gap: 12, alignItems: 'center', boxShadow: t.shadowCard }}>
                  <div style={{ width: 44, height: 44, borderRadius: 22, background: t.accentSoft, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontWeight: 700, color: t.accent, flexShrink: 0 }}>
                    {x.name.split(' ').map(w => w[0]).slice(0, 2).join('')}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 15, fontWeight: 600, color: t.text }}>{x.name}</div>
                    <div style={{ fontSize: 12, color: t.textSec, marginTop: 1 }}>
                      {x.count} Miete{x.count > 1 ? 'n' : ''}{x.count > 1 ? ' · Stammkunde' : ''}
                    </div>
                  </div>
                  {x.count > 1 && <div style={{ fontSize: 16 }}>⭐</div>}
                  <Icon d={icons.chev} color={t.textTer} size={14} sw={2}/>
                </div>
              </Pressable>
            );
          })}
        </div>

        {/* Equipment */}
        {eqHits.length > 0 && <Section title="Equipment" count={eqHits.length}/>}
        <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {eqHits.map(e => (
            <Pressable key={e.id} onClick={() => nav(() => go('detail', { id: e.id }))} scale={0.98}>
              <div style={{ background: t.card, borderRadius: 16, padding: 12, display: 'flex', gap: 12, alignItems: 'center', boxShadow: t.shadowCard }}>
                <EqAvatar item={e} size={44} radius={11}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 600, color: t.text }}>{e.name}</div>
                  <div style={{ fontSize: 12, color: t.textSec, marginTop: 1 }}>{e.cat} · {e.price} €/Tag</div>
                </div>
                <Icon d={icons.chev} color={t.textTer} size={14} sw={2}/>
              </div>
            </Pressable>
          ))}
        </div>

        {/* Rentals by purpose */}
        {rentalHits.length > 0 && <Section title="Mietvorgänge" count={rentalHits.length}/>}
        <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {rentalHits.map(r => {
            const m = statusMeta(r.status);
            return (
              <Pressable key={r.id} onClick={() => nav(() => go('doc', { rentalId: r.id }))} scale={0.98}>
                <div style={{ background: t.card, borderRadius: 16, padding: '12px 14px', display: 'flex', gap: 12, alignItems: 'center', boxShadow: t.shadowCard }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{r.purpose || '—'}</div>
                    <div style={{ fontSize: 12, color: t.textSec, marginTop: 1 }}>{r.tenantName} · {r.equipmentName}</div>
                  </div>
                  <div style={{ fontSize: 9, fontWeight: 700, padding: '3px 7px', borderRadius: 100, background: m.color + '22', color: m.color, letterSpacing: 0.4 }}>● {m.label}</div>
                </div>
              </Pressable>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SearchOverlay });
