// Contacts (Kontakte) — suppliers, tradespeople, advisors

function ContactsPage({ data, setRoute, route, setContactRoute }) {
  const { contacts, properties, transactions, store } = data;
  const [filter, setFilter] = React.useState('alle');
  const [search, setSearch] = React.useState('');
  const [showForm, setShowForm] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const [deleting, setDeleting] = React.useState(null);

  if (route.contactId) {
    return <ContactDetail data={data} contactId={route.contactId} setRoute={setRoute} />;
  }

  const categories = ['alle', 'Favoriten', 'Handwerk', 'Service', 'Beratung', 'Versicherung', 'Verwaltung'];

  let filtered = contacts || [];
  if (filter === 'Favoriten') filtered = filtered.filter(c => c.favorite);
  else if (filter !== 'alle') filtered = filtered.filter(c => c.category === filter);
  if (search) {
    const q = search.toLowerCase();
    filtered = filtered.filter(c =>
      (c.company || '').toLowerCase().includes(q) ||
      (c.contactPerson || '').toLowerCase().includes(q) ||
      (c.trade || '').toLowerCase().includes(q)
    );
  }

  const openAdd = () => { setEditing(null); setShowForm(true); };
  const openEdit = (c) => { setEditing(c); setShowForm(true); };

  // Empty state — no contacts at all
  if ((contacts || []).length === 0) {
    return (
      <div className="page">
        <div className="page-header">
          <div>
            <h1 className="page-title">Kontakte</h1>
            <div className="page-subtitle">Handwerker · Lieferanten · Berater</div>
          </div>
          <div className="page-actions">
            <button className="btn btn-primary" onClick={openAdd}><Icon.Plus /> Kontakt anlegen</button>
          </div>
        </div>
        <ContactForm open={showForm} onClose={() => setShowForm(false)} store={store} initial={editing} />
        <div className="empty" style={{ padding: '60px 20px', textAlign: 'center' }}>
          <div style={{ fontSize: 40, marginBottom: 12 }}>👤</div>
          <div className="empty-title">Noch keine Kontakte</div>
          <div style={{ color: 'var(--ink-3)', maxWidth: 380, margin: '0 auto 20px' }}>Lege Handwerker, Steuerberater, Versicherungen oder andere Lieferanten an — einmal eingetragen, kannst du Aufträge mit ihnen verknüpfen.</div>
          <button className="btn btn-primary" onClick={openAdd}><Icon.Plus /> Erster Kontakt</button>
        </div>
      </div>
    );
  }

  // Spend per contact YTD (transactions linked via contact_id)
  const spendByContact = {};
  const yr = String(new Date().getFullYear());
  transactions.filter(t => t.date.startsWith(yr) && t.type === 'ausgabe' && t.contactId).forEach(t => {
    spendByContact[t.contactId] = (spendByContact[t.contactId] || 0) + Math.abs(t.amount);
  });

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Kontakte</h1>
          <div className="page-subtitle">{contacts.length} {contacts.length === 1 ? 'Kontakt' : 'Kontakte'}</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-primary" onClick={openAdd}><Icon.Plus /> Kontakt anlegen</button>
        </div>
      </div>
      <ContactForm open={showForm} onClose={() => setShowForm(false)} store={store} initial={editing} />
      <ConfirmDialog
        open={!!deleting}
        onClose={() => setDeleting(null)}
        onConfirm={async () => { await store.deleteContact(deleting.id); }}
        title="Kontakt löschen"
        message={`„${deleting?.company}" endgültig löschen?`}
        confirmLabel="Endgültig löschen"
      />

      <div style={{ display: 'flex', gap: 24, marginBottom: 32, alignItems: 'center', flexWrap: 'wrap' }}>
        <div className="search" style={{ width: 320 }}>
          <Icon.Search />
          <input placeholder="Suche nach Firma, Person, Gewerk…" value={search} onChange={e => setSearch(e.target.value)} />
        </div>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {categories.map(c => (
            <button
              key={c}
              onClick={() => setFilter(c)}
              className={`btn ${filter === c ? 'btn-primary' : 'btn-ghost'} btn-sm`}
              style={{ textTransform: 'capitalize' }}
            >
              {c}
            </button>
          ))}
        </div>
      </div>

      <div className="contacts-grid">
        {filtered.map(c => {
          const spend = spendByContact[c.id] || 0;
          return (
            <div key={c.id} className="contact-card" onClick={() => setRoute({ page: 'contacts', contactId: c.id })} style={{ cursor: 'pointer', textAlign: 'left' }}>
              <div className="contact-card-head">
                <div className="contact-avatar">
                  {c.company.split(' ').map(s => s[0]).filter(Boolean).slice(0, 2).join('')}
                </div>
                {c.favorite ? <span className="fav-star" title="Favorit">★</span> : null}
              </div>
              <div className="contact-card-body">
                {c.trade && <div className="contact-trade">{c.trade}</div>}
                <div className="contact-company">{c.company}</div>
                {c.contactPerson && <div className="contact-person">{c.contactPerson}</div>}
              </div>
              <div className="contact-card-stats">
                <div>
                  <div className="contact-stat-l">YTD Umsatz</div>
                  <div className="contact-stat-v">{spend ? fmtEUR(spend) : '—'}</div>
                </div>
                <div>
                  <div className="contact-stat-l">Kategorie</div>
                  <div className="contact-stat-v">{c.category || '—'}</div>
                </div>
              </div>
              <div className="contact-card-actions">
                {c.phone && (
                  <a className="contact-action" href={`tel:${c.phone}`} onClick={e => e.stopPropagation()} title="Anrufen"><ContactIcon.Phone /></a>
                )}
                {c.mobile && (
                  <a className="contact-action" href={`sms:${c.mobile}`} onClick={e => e.stopPropagation()} title="SMS"><ContactIcon.Chat /></a>
                )}
                {c.email && (
                  <a className="contact-action" href={`mailto:${c.email}`} onClick={e => e.stopPropagation()} title="E-Mail"><ContactIcon.Mail /></a>
                )}
                {c.website && (
                  <a className="contact-action" href={c.website.startsWith('http') ? c.website : `https://${c.website}`} target="_blank" rel="noreferrer" onClick={e => e.stopPropagation()} title="Webseite"><ContactIcon.Web /></a>
                )}
                <button className="contact-action" onClick={e => { e.stopPropagation(); openEdit(c); }} title="Bearbeiten" style={{ marginLeft: 'auto' }}>✎</button>
                <button className="contact-action" onClick={e => { e.stopPropagation(); setDeleting(c); }} title="Löschen" style={{ color: 'var(--neg)' }}>✕</button>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function ContactDetail({ data, contactId, setRoute }) {
  const { contacts, properties, transactions, maintenance, store } = data;
  const c = contacts.find(x => x.id === contactId);
  const [showEdit, setShowEdit] = React.useState(false);
  const [showDelete, setShowDelete] = React.useState(false);
  if (!c) return <div className="page"><div className="empty">Kontakt nicht gefunden.</div></div>;

  const linkedTxns = transactions.filter(t => t.contactId === c.id);
  const linkedMaint = (maintenance || []).filter(m => m.contactId === c.id);
  const yr = String(new Date().getFullYear());
  const spendYTD = linkedTxns.filter(t => t.date.startsWith(yr)).reduce((s, t) => s + Math.abs(t.amount), 0);
  const spendTotal = linkedTxns.reduce((s, t) => s + Math.abs(t.amount), 0);

  // Properties used in via linked maintenance + transactions
  const linkedPropIds = new Set([
    ...linkedTxns.map(t => t.propertyId).filter(Boolean),
    ...linkedMaint.map(m => m.propertyId).filter(Boolean),
  ]);
  const linkedProps = properties.filter(p => linkedPropIds.has(p.id));

  // Spend by month for sparkline (12 months back)
  const months = [];
  const now = new Date();
  for (let i = 11; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
    const v = linkedTxns.filter(t => t.date.startsWith(key)).reduce((s, t) => s + Math.abs(t.amount), 0);
    months.push({ key, label: d.toLocaleDateString('de-DE', { month: 'short' }), value: v });
  }

  return (
    <div className="page">
      <ContactForm open={showEdit} onClose={() => setShowEdit(false)} store={store} initial={c} />
      <ConfirmDialog
        open={showDelete}
        onClose={() => setShowDelete(false)}
        onConfirm={async () => { await store.deleteContact(c.id); setRoute({ page: 'contacts' }); }}
        title="Kontakt löschen"
        message={`„${c.company}" endgültig löschen? Verknüpfte Buchungen / Wartungsaufträge bleiben erhalten (Verknüpfung wird gelöst).`}
        confirmLabel="Endgültig löschen"
      />
      <div className="detail-hero">
        <div>
          <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--ink-4)', marginBottom: 12 }}>{[c.category, c.trade].filter(Boolean).join(' · ') || 'Kontakt'}</div>
          <h1>{c.company}{c.favorite ? ' ★' : ''}</h1>
          <div className="addr">{c.contactPerson || '—'}</div>

          <div style={{ display: 'flex', gap: 8, marginTop: 24, flexWrap: 'wrap' }}>
            {c.phone && <a className="btn btn-primary" href={`tel:${c.phone}`}><ContactIcon.Phone /> Anrufen</a>}
            {c.email && <a className="btn" href={`mailto:${c.email}`}><ContactIcon.Mail /> E-Mail</a>}
            {c.mobile && <a className="btn" href={`sms:${c.mobile}`}><ContactIcon.Chat /> SMS</a>}
            {c.website && <a className="btn" href={c.website.startsWith('http') ? c.website : `https://${c.website}`} target="_blank" rel="noreferrer"><ContactIcon.Web /> Webseite</a>}
            <button className="btn btn-ghost" onClick={() => setShowEdit(true)}>Bearbeiten</button>
            <button className="btn btn-ghost" onClick={() => setShowDelete(true)} style={{ color: 'var(--neg)' }}>Löschen</button>
          </div>

          <div className="detail-hero-meta">
            {c.phone && <div className="detail-meta-item"><div className="l">Telefon</div><div className="v">{c.phone}</div></div>}
            {c.mobile && <div className="detail-meta-item"><div className="l">Mobil</div><div className="v">{c.mobile}</div></div>}
            {c.email && <div className="detail-meta-item"><div className="l">E-Mail</div><div className="v" style={{ fontVariantNumeric: 'normal' }}>{c.email}</div></div>}
            {c.website && <div className="detail-meta-item"><div className="l">Webseite</div><div className="v" style={{ fontVariantNumeric: 'normal' }}>{c.website}</div></div>}
            {c.address && <div className="detail-meta-item" style={{ gridColumn: '1 / -1' }}><div className="l">Adresse</div><div className="v" style={{ fontVariantNumeric: 'normal' }}>{c.address}</div></div>}
            {c.iban && <div className="detail-meta-item" style={{ gridColumn: '1 / -1' }}><div className="l">IBAN</div><div className="v">{c.iban}</div></div>}
            {c.ustId && <div className="detail-meta-item"><div className="l">USt-IdNr.</div><div className="v">{c.ustId}</div></div>}
          </div>
        </div>

        <aside className="detail-hero-side">
          <div className="mini-stat">
            <div className="l">Umsatz YTD 2026</div>
            <div className="v">{fmtEUR(spendYTD)}</div>
          </div>
          <div className="mini-stat">
            <div className="l">Gesamtumsatz</div>
            <div className="v">{fmtEUR(spendTotal)}</div>
          </div>
          <div className="mini-stat">
            <div className="l">Aufträge</div>
            <div className="v">{linkedTxns.length}</div>
          </div>

          {c.rating && (
            <div style={{ borderTop: '1px solid var(--line)', paddingTop: 16 }}>
              <div className="contact-rating">
                <div className="l" style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--ink-3)', marginBottom: 6 }}>Bewertung</div>
                <div style={{ fontSize: 18, letterSpacing: 2 }}>
                  {[1, 2, 3, 4, 5].map(n => (
                    <span key={n} style={{ color: n <= (c.rating || 0) ? 'var(--ink)' : 'var(--ink-5)' }}>★</span>
                  ))}
                </div>
              </div>
            </div>
          )}

          {linkedTxns.length > 0 && <Sparkline data={months} />}
        </aside>
      </div>

      {c.notes && (
        <div className="section">
          <div className="section-header"><h2 className="section-title">Notiz</h2></div>
          <div style={{ fontFamily: 'var(--font-serif)', fontSize: 17, fontStyle: 'italic', color: 'var(--ink-2)', maxWidth: 720, lineHeight: 1.6 }}>
            „{c.notes}"
          </div>
        </div>
      )}

      <div className="two-col">
        <div className="section" style={{ marginBottom: 0 }}>
          <div className="section-header">
            <h2 className="section-title">Buchungshistorie</h2>
            <span className="text-muted" style={{ fontSize: 12 }}>{linkedTxns.length} Einträge</span>
          </div>
          {linkedTxns.length === 0 ? (
            <div className="text-muted" style={{ fontSize: 13, padding: 16 }}>Noch keine Buchungen verknüpft.</div>
          ) : (
            <div className="table-wrap">
              <table className="table">
                <thead><tr><th>Datum</th><th>Beschreibung</th><th>Objekt</th><th className="num">Betrag</th></tr></thead>
                <tbody>
                  {linkedTxns.map(tx => {
                    const prop = properties.find(p => p.id === tx.propertyId);
                    return (
                      <tr key={tx.id}>
                        <td className="muted">{fmtDateShort(tx.date)}</td>
                        <td className="strong">{tx.description}</td>
                        <td className="muted">{prop ? prop.name : '—'}</td>
                        <td className="num strong" style={{ color: 'var(--neg)' }}>−{fmtEUR(Math.abs(tx.amount))}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          {linkedProps.length > 0 && (
            <div className="side-card">
              <h3>Eingesetzt bei</h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {linkedProps.map(p => (
                  <button
                    key={p.id}
                    className="link-row"
                    onClick={() => setRoute({ page: 'properties', propertyId: p.id })}
                  >
                    <div>
                      <div style={{ fontWeight: 500 }}>{p.name}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{p.address}</div>
                    </div>
                    <Icon.ChevronRight />
                  </button>
                ))}
              </div>
            </div>
          )}

          {linkedMaint.length > 0 && (
            <div className="side-card">
              <h3>Wartungsaufträge</h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {linkedMaint.slice(0, 5).map(m => (
                  <div key={m.id} style={{ fontSize: 12.5, padding: 6 }}>
                    <div style={{ fontWeight: 500, color: 'var(--ink)' }}>{m.title}</div>
                    <div style={{ color: 'var(--ink-3)' }}>{m.status} · {m.dueDate ? fmtDateShort(m.dueDate) : 'kein Datum'}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function Sparkline({ data }) {
  const W = 240, H = 56;
  const max = Math.max(...data.map(d => d.value), 1);
  const bw = W / data.length;
  return (
    <div>
      <div className="l" style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--ink-3)', marginBottom: 8 }}>Umsatz · 12 Monate</div>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
        {data.map((d, i) => {
          const h = (d.value / max) * (H - 8);
          return <rect key={i} x={i * bw + 1} y={H - h} width={bw - 2} height={h} fill={d.value ? 'var(--accent)' : 'var(--ink-5)'} rx="1"/>;
        })}
      </svg>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--ink-4)', marginTop: 4 }}>
        <span>{data[0]?.label}</span>
        <span>{data[data.length - 1]?.label}</span>
      </div>
    </div>
  );
}

const ContactIcon = {
  Phone: () => <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" width="13" height="13"><path d="M3 3.5a1 1 0 011-1h2l1.5 3-1.5 1c.7 1.7 2.3 3.3 4 4l1-1.5 3 1.5v2a1 1 0 01-1 1C6.5 13.5 2.5 9.5 2.5 4.5c0-.4 0-.7.5-1z" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  Mail: () => <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" width="13" height="13"><rect x="2" y="3.5" width="12" height="9" rx="0.5"/><path d="M2.5 4l5.5 4 5.5-4" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  Chat: () => <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" width="13" height="13"><path d="M2.5 3.5h11v7h-7l-3 2.5v-2.5h-1v-7z" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  Web: () => <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" width="13" height="13"><circle cx="8" cy="8" r="5.5"/><path d="M2.5 8h11M8 2.5c1.7 2 2.5 3.7 2.5 5.5s-.8 3.5-2.5 5.5c-1.7-2-2.5-3.7-2.5-5.5s.8-3.5 2.5-5.5z" strokeLinecap="round" strokeLinejoin="round"/></svg>,
};

Object.assign(window, { ContactsPage, ContactDetail, ContactIcon });
