// Posteingang — E-Mail inbox: read mail, convert rental requests, link to tenants, reply.
// Two view styles (Liste / Karten) so the look can be compared.
const { useState, useEffect } = React;

// Icons
const ICON_ENVELOPE = 'M3 6a1 1 0 011-1h16a1 1 0 011 1v12a1 1 0 01-1 1H4a1 1 0 01-1-1V6zM3 7l9 6 9-6';
const ICON_REPLY    = 'M9 17l-5-5 5-5M4 12h11a4 4 0 014 4v2';
const ICON_LINK     = 'M10 13a5 5 0 007 0l2-2a5 5 0 00-7-7l-1 1M14 11a5 5 0 00-7 0l-2 2a5 5 0 007 7l1-1';
const ICON_ARCHIVE  = 'M3 6h18v3H3zM5 9v10a1 1 0 001 1h12a1 1 0 001-1V9M9 13h6';
const ICON_TRASH    = 'M3 6h18M8 6V4a1 1 0 011-1h6a1 1 0 011 1v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6M10 11v6M14 11v6';
const ICON_BOLT     = 'M13 2L3 14h8l-1 8 10-12h-8l1-8z';
const ICON_STAR     = 'M12 2.5l2.9 6 6.6.9-4.8 4.6 1.2 6.5L12 18.2 6.1 20.5l1.2-6.5L2.5 9.4l6.6-.9z';

// Map a free-text equipment hint to an actual equipment id (best effort).
function matchEquipmentId(hint, equipment) {
  if (!equipment || !equipment.length) return '';
  if (!hint) return equipment[0].id;
  const h = hint.toLowerCase();
  const direct = equipment.find(e => h.includes(e.name.toLowerCase()) || e.name.toLowerCase().includes(h));
  if (direct) return direct.id;
  const byKind = (re) => { const e = equipment.find(x => re.test((x.name + ' ' + x.cat + ' ' + x.kind).toLowerCase())); return e && e.id; };
  if (/funk/.test(h))                              return byKind(/funk|ew100|sennheiser/) || equipment[0].id;
  if (/mikro|mic|gesang/.test(h))                  return byKind(/sm58|mikro|shure/) || equipment[0].id;
  if (/lautsprech|box|^pa\b|pa |beschall|sound|musik|anlage/.test(h)) return byKind(/jbl|lautsprech|eon/) || equipment[0].id;
  if (/misch|mixer|pult/.test(h))                  return byKind(/mg10|yamaha|misch/) || equipment[0].id;
  if (/anh\u00e4ng|trailer|umzug|transport|kasten/.test(h)) return byKind(/anh\u00e4nger/) || equipment[0].id;
  return equipment[0].id;
}

// Relative date label vs the app's fixed today.
function mailDate(dateISO, time) {
  const today = todayISO();
  if (dateISO === today) return time || 'Heute';
  const d = fromISO(dateISO), tdy = fromISO(today);
  const diff = Math.round((tdy - d) / 86400000);
  if (diff === 1) return 'Gestern';
  if (diff > 1 && diff < 7) return DE_DAYS[d.getDay()].slice(0, 2);
  return `${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}.`;
}

const initials = (name) => name.split(/\s+/).filter(Boolean).slice(0, 2).map(w => w[0]).join('').toUpperCase();
// Stable-ish avatar tint from name
const AVATAR_TINTS = ['#007AFF', '#34C759', '#FF9500', '#AF52DE', '#FF2D55', '#5856D6', '#30B0C7'];
const tintFor = (s) => AVATAR_TINTS[[...s].reduce((a, c) => a + c.charCodeAt(0), 0) % AVATAR_TINTS.length];

function Avatar({ name, size = 42 }) {
  const c = tintFor(name);
  return (
    <div style={{
      width: size, height: size, borderRadius: size / 2, flexShrink: 0,
      background: c + '22', color: c,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.36, fontWeight: 700, letterSpacing: 0.2,
    }}>{initials(name)}</div>
  );
}

// ─────────────────────────────────────────────────────────────
// Inbox list — two visual styles
// ─────────────────────────────────────────────────────────────
function InboxList({ emails, rentals, style, onOpen }) {
  const t = useTheme();
  if (emails.length === 0) {
    return <div style={{ textAlign: 'center', padding: '50px 24px', color: t.textSec, fontSize: 13 }}>Keine E-Mails in diesem Filter.</div>;
  }

  // ── Apple-Mail-style list ──
  if (style === 'liste') {
    return (
      <div style={{ padding: '0 16px' }}>
        <div style={{ background: t.card, borderRadius: 16, overflow: 'hidden', boxShadow: t.shadowCard }}>
          {emails.map((m, i) => {
            const linked = m.linkedRentalId && rentals.find(r => r.id === m.linkedRentalId);
            return (
              <Pressable key={m.id} onClick={() => onOpen(m)} scale={0.99}>
                <div style={{
                  display: 'flex', gap: 12, padding: '13px 14px',
                  borderBottom: i < emails.length - 1 ? `0.5px solid ${t.sep}` : 'none',
                  position: 'relative',
                }}>
                  {/* unread dot */}
                  <div style={{ width: 9, display: 'flex', justifyContent: 'center', paddingTop: 6, flexShrink: 0 }}>
                    {m.unread && <div style={{ width: 8, height: 8, borderRadius: 4, background: t.accent }}/>}
                  </div>
                  <Avatar name={m.from} size={40}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                      <div style={{ flex: 1, minWidth: 0, fontSize: 14, fontWeight: m.unread ? 700 : 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.from}</div>
                      <div style={{ fontSize: 11, color: t.textSec, flexShrink: 0 }}>{mailDate(m.dateISO, m.time)}</div>
                    </div>
                    <div style={{ fontSize: 13, fontWeight: m.unread ? 600 : 500, color: t.text, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.subject}</div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
                      <div style={{ flex: 1, minWidth: 0, fontSize: 12, color: t.textSec, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.body.split('\n')[0]}</div>
                    </div>
                    <div style={{ display: 'flex', gap: 5, marginTop: 6, flexWrap: 'wrap' }}>
                      {m.kind === 'request' && !m.linkedRentalId && (
                        <Tag color={t.accent} soft><Icon d={ICON_BOLT} color={t.accent} size={9} sw={2.4}/> Anfrage</Tag>
                      )}
                      {linked && <Tag color={t.green} soft>✓ {linked.tenantName.split(' ')[0]}</Tag>}
                      {m.replied && <Tag color={t.textSec} soft>Beantwortet</Tag>}
                      {m.starred && <Icon d={ICON_STAR} color={t.orange} size={12} fill sw={1.5}/>}
                    </div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center' }}><Icon d={icons.chev} color={t.textTer} size={14} sw={2}/></div>
                </div>
              </Pressable>
            );
          })}
        </div>
      </div>
    );
  }

  // ── Request-focused cards ──
  return (
    <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
      {emails.map(m => {
        const isReq = m.kind === 'request' && !m.linkedRentalId;
        const linked = m.linkedRentalId && rentals.find(r => r.id === m.linkedRentalId);
        return (
          <Pressable key={m.id} onClick={() => onOpen(m)} scale={0.98}>
            <div style={{
              background: t.card, borderRadius: 18, overflow: 'hidden', boxShadow: t.shadowCard,
              border: isReq ? `1px solid ${t.accent}33` : `0.5px solid ${t.sep}`,
            }}>
              {isReq && (
                <div style={{ background: t.accentSoft, padding: '7px 14px', display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Icon d={ICON_BOLT} color={t.accent} size={12} sw={2.2}/>
                  <span style={{ fontSize: 11, fontWeight: 700, color: t.accent, letterSpacing: 0.3 }}>NEUE MIET-ANFRAGE</span>
                  {m.unread && <span style={{ marginLeft: 'auto', width: 8, height: 8, borderRadius: 4, background: t.accent }}/>}
                </div>
              )}
              <div style={{ padding: 14 }}>
                <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                  <Avatar name={m.from} size={42}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                      <div style={{ flex: 1, minWidth: 0, fontSize: 15, fontWeight: m.unread ? 700 : 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.from}</div>
                      <div style={{ fontSize: 11, color: t.textSec, flexShrink: 0 }}>{mailDate(m.dateISO, m.time)}</div>
                    </div>
                    <div style={{ fontSize: 13, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.subject}</div>
                  </div>
                </div>

                {isReq && m.parsed ? (
                  <div style={{ marginTop: 12, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {m.parsed.equipmentHint && <Chip icon="🎛">{m.parsed.equipmentHint}</Chip>}
                    {m.parsed.startISO && <Chip icon="📅">{fmtRange(m.parsed.startISO, m.parsed.endISO)}</Chip>}
                    {m.parsed.deliveryAddress && <Chip icon="🚚">Lieferung</Chip>}
                  </div>
                ) : (
                  <div style={{ marginTop: 10, fontSize: 13, color: t.textSec, lineHeight: 1.45,
                    display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                    {m.body.split('\n').filter(Boolean)[0]}
                  </div>
                )}

                <div style={{ display: 'flex', gap: 6, marginTop: 12, alignItems: 'center' }}>
                  {linked && <Tag color={t.green} soft>✓ Verknüpft · {linked.tenantName.split(' ')[0]}</Tag>}
                  {m.replied && <Tag color={t.textSec} soft>Beantwortet</Tag>}
                  <div style={{ flex: 1 }}/>
                  <div style={{ fontSize: 12, fontWeight: 600, color: t.accent, display: 'flex', alignItems: 'center', gap: 3 }}>
                    {isReq ? 'Bearbeiten' : 'Lesen'} <Icon d={icons.chev} color={t.accent} size={12} sw={2.4}/>
                  </div>
                </div>
              </div>
            </div>
          </Pressable>
        );
      })}
    </div>
  );
}

function Tag({ children, color, soft }) {
  const t = useTheme();
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 3,
      fontSize: 10, fontWeight: 700, padding: '2px 7px', borderRadius: 100,
      background: soft ? color + '1e' : color, color: soft ? color : '#fff',
      whiteSpace: 'nowrap',
    }}>{children}</span>
  );
}
function Chip({ children, icon }) {
  const t = useTheme();
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      fontSize: 11.5, fontWeight: 600, padding: '5px 10px', borderRadius: 9,
      background: t.chip, color: t.text, whiteSpace: 'nowrap',
    }}>{icon && <span style={{ fontSize: 12 }}>{icon}</span>}{children}</span>
  );
}

// ─────────────────────────────────────────────────────────────
// Email detail
// ─────────────────────────────────────────────────────────────
function EmailDetail({ email, equipment, rentals, onBack, onConvert, onReply, onLink, onArchive, onDelete, onToggleStar, toast }) {
  const t = useTheme();
  const m = email;
  const isReq = m.kind === 'request';
  const linked = m.linkedRentalId && rentals.find(r => r.id === m.linkedRentalId);
  const eqGuess = isReq && m.parsed ? equipment.find(e => e.id === matchEquipmentId(m.parsed.equipmentHint, equipment)) : null;

  return (
    <div style={{ minHeight: '100dvh', display: 'flex', flexDirection: 'column' }}>
      {/* top bar */}
      <div style={{ padding: '8px 12px 10px', display: 'flex', alignItems: 'center', gap: 6, position: 'sticky', top: 0, zIndex: 20, background: t.bg }}>
        <Pressable onClick={onBack} scale={0.88}>
          <div style={{ width: 36, height: 36, borderRadius: 18, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon d={icons.back} color={t.text} size={20} sw={2.2}/>
          </div>
        </Pressable>
        <div style={{ flex: 1 }}/>
        <Pressable onClick={() => onToggleStar(m)} scale={0.85}>
          <div style={{ width: 36, height: 36, borderRadius: 18, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon d={ICON_STAR} color={m.starred ? t.orange : t.textSec} size={17} fill={m.starred} sw={1.8}/>
          </div>
        </Pressable>
        <Pressable onClick={() => onArchive(m)} scale={0.85}>
          <div style={{ width: 36, height: 36, borderRadius: 18, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon d={ICON_ARCHIVE} color={t.text} size={17} sw={1.8}/>
          </div>
        </Pressable>
        <Pressable onClick={() => onDelete(m)} scale={0.85}>
          <div style={{ width: 36, height: 36, borderRadius: 18, background: t.redSoft || (t.dark ? 'rgba(255,69,58,0.18)' : 'rgba(255,59,48,0.10)'), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon d={ICON_TRASH} color={t.red} size={17} sw={1.8}/>
          </div>
        </Pressable>
      </div>

      <div style={{ flex: 1, padding: '0 20px 150px' }}>
        {/* subject + sender */}
        <div style={{ fontSize: 21, fontWeight: 700, color: t.text, letterSpacing: -0.4, lineHeight: 1.25 }}>{m.subject}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 14 }}>
          <Avatar name={m.from} size={44}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: t.text }}>{m.from}</div>
            <div style={{ fontSize: 12, color: t.textSec, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.fromEmail}</div>
          </div>
          <div style={{ fontSize: 12, color: t.textSec, flexShrink: 0 }}>{fmtDateDE(m.dateISO)}{m.time ? ' · ' + m.time : ''}</div>
        </div>

        {/* linked banner */}
        {linked && (
          <div style={{ marginTop: 14, padding: '10px 12px', background: t.greenSoft, borderRadius: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
            <Icon d={ICON_LINK} color={t.green} size={16} sw={2}/>
            <div style={{ flex: 1, minWidth: 0, fontSize: 12.5, color: t.text }}>
              Verknüpft mit <strong>{linked.tenantName}</strong> · {linked.equipmentName}
            </div>
          </div>
        )}

        {/* parsed request summary */}
        {isReq && m.parsed && (
          <div style={{ marginTop: 16, background: t.card, borderRadius: 16, overflow: 'hidden', boxShadow: t.shadowCard, border: `1px solid ${t.accent}26` }}>
            <div style={{ background: t.accentSoft, padding: '9px 14px', display: 'flex', alignItems: 'center', gap: 7 }}>
              <Icon d={ICON_BOLT} color={t.accent} size={13} sw={2.2}/>
              <span style={{ fontSize: 11.5, fontWeight: 700, color: t.accent, letterSpacing: 0.3 }}>ERKANNTE ANFRAGE</span>
            </div>
            <div style={{ padding: '4px 0' }}>
              <SummaryRow label="Equipment" value={eqGuess ? eqGuess.name : m.parsed.equipmentHint} hint={eqGuess ? null : 'kein genaues Match'}/>
              {m.parsed.startISO && <SummaryRow label="Zeitraum" value={fmtRange(m.parsed.startISO, m.parsed.endISO)} sub={`${daysBetween(m.parsed.startISO, m.parsed.endISO)} Tag${daysBetween(m.parsed.startISO, m.parsed.endISO) > 1 ? 'e' : ''}`}/>}
              {m.parsed.purpose && <SummaryRow label="Zweck" value={m.parsed.purpose}/>}
              {m.parsed.deliveryAddress && <SummaryRow label="Lieferung" value={m.parsed.deliveryAddress}/>}
              {m.parsed.phone && <SummaryRow label="Telefon" value={m.parsed.phone}/>}
            </div>
          </div>
        )}

        {/* body */}
        <div style={{ marginTop: 18, fontSize: 14.5, color: t.text, lineHeight: 1.6, whiteSpace: 'pre-wrap' }}>{m.body}</div>

        {m.replied && (
          <div style={{ marginTop: 18, padding: '12px 14px', background: t.cardAlt, borderRadius: 12, fontSize: 12.5, color: t.textSec, display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon d={icons.check} color={t.green} size={15} sw={2.4}/> Du hast auf diese E-Mail bereits geantwortet.
          </div>
        )}
      </div>

      {/* action bar */}
      <div style={{ position: 'absolute', bottom: 90, left: 16, right: 16, zIndex: 25 }}>
        {isReq && !m.linkedRentalId && (
          <Pressable onClick={() => onConvert(m)} scale={0.98} style={{ marginBottom: 8 }}>
            <div style={{
              background: t.accent, color: '#fff', borderRadius: 14, padding: '14px 0', textAlign: 'center',
              fontSize: 15, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              boxShadow: '0 6px 18px rgba(0,122,255,0.34)',
            }}>
              <Icon d={ICON_BOLT} color="#fff" size={16} sw={2.2}/> In Vermietung umwandeln
            </div>
          </Pressable>
        )}
        <div style={{ display: 'flex', gap: 8 }}>
          <Pressable onClick={() => onReply(m)} scale={0.97} style={{ flex: 1 }}>
            <div style={{
              background: t.solidBg, color: t.solidFg, borderRadius: 14, padding: '13px 0', textAlign: 'center',
              fontSize: 14, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
              boxShadow: '0 6px 16px rgba(0,0,0,0.22)',
            }}>
              <Icon d={ICON_REPLY} color={t.solidFg} size={15} sw={2}/> Antworten
            </div>
          </Pressable>
          <Pressable onClick={() => onLink(m)} scale={0.95}>
            <div style={{
              background: t.card, color: t.text, borderRadius: 14, padding: '13px 18px', textAlign: 'center',
              fontSize: 14, fontWeight: 600, border: `0.5px solid ${t.sep}`, display: 'flex', alignItems: 'center', gap: 7,
            }}>
              <Icon d={ICON_LINK} color={t.text} size={15} sw={2}/> {linked ? 'Ändern' : 'Verknüpfen'}
            </div>
          </Pressable>
        </div>
      </div>
    </div>
  );
}

function SummaryRow({ label, value, sub, hint }) {
  const t = useTheme();
  return (
    <div style={{ padding: '9px 14px', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
      <div style={{ fontSize: 12, color: t.textSec, fontWeight: 500, minWidth: 78, flexShrink: 0 }}>{label}</div>
      <div style={{ flex: 1, textAlign: 'right' }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text }}>{value}</div>
        {sub && <div style={{ fontSize: 11, color: t.textSec, marginTop: 1 }}>{sub}</div>}
        {hint && <div style={{ fontSize: 10.5, color: t.orange, marginTop: 1 }}>{hint}</div>}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Reply composer sheet
// ─────────────────────────────────────────────────────────────
function ReplySheet({ open, email, onClose, onSend }) {
  const t = useTheme();
  const [text, setText] = useState('');
  useEffect(() => {
    if (open && email) {
      const first = email.from.split(' ')[0];
      setText(`Hallo ${first},\n\nvielen Dank für Ihre Nachricht.\n\n\n\nViele Grüße\nRentFlow Manager`);
    }
  }, [open, email && email.id]);
  if (!email) return null;

  const quick = [
    'Gerne — der Termin ist bei uns frei. ✅',
    'Leider ist das Equipment in dem Zeitraum schon vergeben.',
    'Anbei unser Angebot. Bei Fragen melden Sie sich gerne.',
  ];

  return (
    <Sheet open={open} onClose={onClose}>
      <div style={{ padding: '4px 20px 24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <div style={{ fontSize: 20, fontWeight: 700, color: t.text, letterSpacing: -0.4 }}>Antwort</div>
          <Pressable onClick={onClose}><div style={{ fontSize: 14, color: t.textSec, fontWeight: 500 }}>Abbrechen</div></Pressable>
        </div>

        <div style={{ marginTop: 14, background: t.cardAlt, borderRadius: 12, padding: '10px 12px' }}>
          <Row label="An" value={`${email.from} · ${email.fromEmail}`}/>
          <div style={{ height: 0.5, background: t.sep, margin: '8px 0' }}/>
          <Row label="Betreff" value={email.subject.startsWith('Re:') ? email.subject : 'Re: ' + email.subject}/>
        </div>

        {/* quick replies */}
        <div style={{ display: 'flex', gap: 6, overflowX: 'auto', marginTop: 12, paddingBottom: 4 }}>
          {quick.map((q, i) => (
            <Pressable key={i} onClick={() => setText(prev => {
              const sig = '\n\nViele Grüße\nRentFlow Manager';
              const base = prev.replace(sig, '');
              return base.replace(/\n+$/, '') + '\n\n' + q + sig;
            })} scale={0.96}>
              <div style={{ padding: '7px 11px', borderRadius: 9, background: t.chip, color: t.text, fontSize: 11.5, fontWeight: 600, whiteSpace: 'nowrap' }}>{q.length > 28 ? q.slice(0, 26) + '…' : q}</div>
            </Pressable>
          ))}
        </div>

        <textarea value={text} onChange={e => setText(e.target.value)} rows={9}
          style={{
            width: '100%', marginTop: 12, padding: '14px', borderRadius: 14,
            border: `0.5px solid ${t.inputBorder}`, background: t.inputBg,
            fontSize: 14.5, color: t.text, outline: 'none', fontFamily: 'inherit',
            lineHeight: 1.55, resize: 'vertical', boxSizing: 'border-box',
          }}/>

        <Pressable onClick={() => { onSend(email, text); onClose(); }} scale={0.97} style={{ marginTop: 14 }}>
          <div style={{
            padding: '15px 0', textAlign: 'center', borderRadius: 14,
            background: t.accent, color: '#fff', fontSize: 16, fontWeight: 600,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            <Icon d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" color="#fff" size={17} sw={2}/> Senden
          </div>
        </Pressable>
      </div>
    </Sheet>
  );
}

function Row({ label, value }) {
  const t = useTheme();
  return (
    <div style={{ display: 'flex', gap: 10, alignItems: 'baseline' }}>
      <div style={{ fontSize: 12, color: t.textSec, minWidth: 50, fontWeight: 500 }}>{label}</div>
      <div style={{ flex: 1, fontSize: 13, color: t.text, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{value}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Link-to-tenant sheet
// ─────────────────────────────────────────────────────────────
function LinkSheet({ open, email, rentals, equipment, onClose, onPick, onUnlink }) {
  const t = useTheme();
  if (!email) return null;
  // Suggest rentals whose email matches
  const suggested = rentals.filter(r => r.email && email.fromEmail && r.email.toLowerCase() === email.fromEmail.toLowerCase());
  const rest = rentals.filter(r => !suggested.includes(r));
  const ordered = [...suggested, ...rest];

  return (
    <Sheet open={open} onClose={onClose}>
      <div style={{ padding: '4px 20px 24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <div>
            <div style={{ fontSize: 20, fontWeight: 700, color: t.text, letterSpacing: -0.4 }}>Mit Mieter verknüpfen</div>
            <div style={{ fontSize: 13, color: t.textSec, marginTop: 3 }}>E-Mail einem bestehenden Mietvertrag zuordnen.</div>
          </div>
          <Pressable onClick={onClose}><div style={{ fontSize: 14, color: t.textSec, fontWeight: 500 }}>Fertig</div></Pressable>
        </div>

        {email.linkedRentalId && (
          <Pressable onClick={() => { onUnlink(email); onClose(); }} scale={0.98} style={{ marginTop: 14 }}>
            <div style={{ padding: '11px 0', textAlign: 'center', borderRadius: 12, background: t.redSoft, color: t.red, fontSize: 13, fontWeight: 600 }}>
              Verknüpfung aufheben
            </div>
          </Pressable>
        )}

        <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
          {ordered.map(r => {
            const eq = equipment.find(e => e.id === r.equipmentId);
            const isSug = suggested.includes(r);
            const isCur = email.linkedRentalId === r.id;
            const m = statusMeta(r.status);
            return (
              <Pressable key={r.id} onClick={() => { onPick(email, r); onClose(); }} scale={0.98}>
                <div style={{
                  background: t.card, borderRadius: 14, padding: '11px 13px', display: 'flex', alignItems: 'center', gap: 11,
                  border: isCur ? `1.5px solid ${t.accent}` : (isSug ? `1px solid ${t.green}55` : `0.5px solid ${t.sep}`),
                }}>
                  <Avatar name={r.tenantName} size={36}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.tenantName}</div>
                      {isSug && <span style={{ fontSize: 9, fontWeight: 700, color: t.green, background: t.greenSoft, padding: '1px 6px', borderRadius: 100, whiteSpace: 'nowrap' }}>passt</span>}
                    </div>
                    <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{eq ? eq.name : r.equipmentName} · {fmtRange(r.start, r.end)}</div>
                  </div>
                  <div style={{ fontSize: 9, fontWeight: 700, color: m.color, flexShrink: 0 }}>● {m.label}</div>
                </div>
              </Pressable>
            );
          })}
        </div>
      </div>
    </Sheet>
  );
}

// ─────────────────────────────────────────────────────────────
// Main inbox screen (rendered inside the Akten "Posteingang" tab)
// ─────────────────────────────────────────────────────────────
function Posteingang({ emails, setEmails, equipment, rentals, onConvert, toast }) {
  const t = useTheme();
  const [viewStyle, setViewStyle] = useLocal('rf-inbox-style', 'karten'); // 'liste' | 'karten'
  const [filter, setFilter] = useState('alle'); // alle | anfragen | verknuepft
  const [selected, setSelected] = useState(null);
  const [reply, setReply] = useState(null);
  const [link, setLink] = useState(null);

  const visible = emails.filter(m => !m.archived).filter(m => {
    if (filter === 'anfragen') return m.kind === 'request' && !m.linkedRentalId;
    if (filter === 'verknuepft') return !!m.linkedRentalId;
    return true;
  });
  const unreadCount = emails.filter(m => !m.archived && m.unread).length;
  const reqCount = emails.filter(m => !m.archived && m.kind === 'request' && !m.linkedRentalId).length;

  const open = (m) => {
    setEmails(prev => prev.map(x => x.id === m.id ? { ...x, unread: false } : x));
    setSelected({ ...m, unread: false });
  };
  const sendReply = (m, text) => {
    setEmails(prev => prev.map(x => x.id === m.id ? { ...x, replied: true } : x));
    setSelected(s => s && s.id === m.id ? { ...s, replied: true } : s);
    toast('Antwort gesendet');
  };
  const doLink = (m, r) => {
    setEmails(prev => prev.map(x => x.id === m.id ? { ...x, linkedRentalId: r.id } : x));
    setSelected(s => s && s.id === m.id ? { ...s, linkedRentalId: r.id } : s);
    toast(`Verknüpft mit ${r.tenantName}`);
  };
  const doUnlink = (m) => {
    setEmails(prev => prev.map(x => x.id === m.id ? { ...x, linkedRentalId: null } : x));
    setSelected(s => s && s.id === m.id ? { ...s, linkedRentalId: null } : s);
    toast('Verknüpfung aufgehoben');
  };
  const archive = (m) => {
    setEmails(prev => prev.map(x => x.id === m.id ? { ...x, archived: true } : x));
    setSelected(null);
    toast('Archiviert');
  };
  const [confirmDel, setConfirmDel] = useState(null);
  const del = (m) => setConfirmDel(m);
  const doDelete = (m) => {
    setEmails(prev => prev.filter(x => x.id !== m.id));
    setConfirmDel(null);
    setSelected(null);
    toast('Gelöscht');
  };
  const toggleStar = (m) => {
    setEmails(prev => prev.map(x => x.id === m.id ? { ...x, starred: !x.starred } : x));
    setSelected(s => s && s.id === m.id ? { ...s, starred: !s.starred } : s);
  };

  // Detail view replaces the list
  if (selected) {
    const live = emails.find(e => e.id === selected.id) || selected;
    return (
      <>
        <EmailDetail email={live} equipment={equipment} rentals={rentals}
          onBack={() => setSelected(null)}
          onConvert={(m) => { onConvert(m); }}
          onReply={(m) => setReply(m)} onLink={(m) => setLink(m)}
          onArchive={archive} onDelete={del} onToggleStar={toggleStar} toast={toast}/>
        <ReplySheet open={!!reply} email={reply} onClose={() => setReply(null)} onSend={sendReply}/>
        <LinkSheet open={!!link} email={link} rentals={rentals} equipment={equipment}
          onClose={() => setLink(null)} onPick={doLink} onUnlink={doUnlink}/>
        <DeleteEmailSheet open={!!confirmDel} email={confirmDel} onClose={() => setConfirmDel(null)} onConfirm={doDelete}/>
      </>
    );
  }

  return (
    <div>
      {/* filter + view-style controls */}
      <div style={{ padding: '0 16px 12px', display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ flex: 1, display: 'flex', gap: 6, overflowX: 'auto' }}>
          {[['alle', 'Alle'], ['anfragen', `Anfragen${reqCount ? ' · ' + reqCount : ''}`], ['verknuepft', 'Verknüpft']].map(([id, label]) => (
            <Pressable key={id} onClick={() => setFilter(id)} scale={0.95}>
              <div style={{
                padding: '7px 13px', borderRadius: 100, fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap',
                background: filter === id ? t.solidBg : t.chip, color: filter === id ? t.solidFg : t.text,
              }}>{label}</div>
            </Pressable>
          ))}
        </div>
        {/* view-style toggle */}
        <div style={{ display: 'flex', padding: 2, borderRadius: 9, background: t.chipStrong, flexShrink: 0 }}>
          {[['karten', 'M9 4h11M9 9h11M9 14h11M4 4.5v0M4 9.5v0M4 14.5v0'], ['liste', 'M4 6h16M4 12h16M4 18h16']].map(([id, d]) => (
            <Pressable key={id} onClick={() => setViewStyle(id)} scale={0.92}>
              <div style={{
                width: 32, height: 28, borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: viewStyle === id ? (t.dark ? '#48484A' : '#fff') : 'transparent',
                boxShadow: viewStyle === id ? '0 1px 3px rgba(0,0,0,0.1)' : 'none',
              }}>
                <Icon d={d} color={viewStyle === id ? t.text : t.textSec} size={16} sw={2}/>
              </div>
            </Pressable>
          ))}
        </div>
      </div>

      <InboxList emails={visible} rentals={rentals} style={viewStyle} onOpen={open}/>

      <ReplySheet open={!!reply} email={reply} onClose={() => setReply(null)} onSend={sendReply}/>
      <LinkSheet open={!!link} email={link} rentals={rentals} equipment={equipment}
        onClose={() => setLink(null)} onPick={doLink} onUnlink={doUnlink}/>
      <DeleteEmailSheet open={!!confirmDel} email={confirmDel} onClose={() => setConfirmDel(null)} onConfirm={doDelete}/>
    </div>
  );
}

// ────────────────────────────────────────────────────────
// Delete confirm sheet (iOS-style action sheet)
// ────────────────────────────────────────────────────────
function DeleteEmailSheet({ open, email, onClose, onConfirm }) {
  const t = useTheme();
  if (!open || !email) return null;
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.45)',
      display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
      animation: 'fadeIn 0.18s ease-out',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{ padding: '0 8px 8px' }}>
        <div style={{ background: t.card, borderRadius: 14, overflow: 'hidden', marginBottom: 8 }}>
          <div style={{ padding: '16px 18px 14px', textAlign: 'center', borderBottom: `0.5px solid ${t.sep}` }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: t.text, marginBottom: 4 }}>E-Mail löschen?</div>
            <div style={{ fontSize: 12, color: t.textSec, lineHeight: 1.4 }}>
              „{email.subject}“ von <strong>{email.from}</strong> wird endgültig entfernt.
            </div>
          </div>
          <Pressable onClick={() => onConfirm(email)} scale={0.99}>
            <div style={{ padding: '14px 0', textAlign: 'center', fontSize: 16, fontWeight: 600, color: t.red }}>
              Löschen
            </div>
          </Pressable>
        </div>
        <Pressable onClick={onClose} scale={0.99}>
          <div style={{ background: t.card, borderRadius: 14, padding: '14px 0', textAlign: 'center', fontSize: 16, fontWeight: 700, color: t.accent }}>
            Abbrechen
          </div>
        </Pressable>
      </div>
    </div>
  );
}

Object.assign(window, { Posteingang, matchEquipmentId });
