// Tax + Rent + Tasks pages — neue Module für Steuer, Mieten-Status, Aufgaben

// ────────────────────────────────────────────────────────────────────
// AfA-Sektion: wird auf PropertyDetail eingebunden + auf TaxPage
// ────────────────────────────────────────────────────────────────────
function AfaSection({ data, propertyId }) {
  const { assets, properties, store } = data;
  const [year, setYear] = React.useState(new Date().getFullYear());
  const [showForm, setShowForm] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const [deleting, setDeleting] = React.useState(null);
  const [summary, setSummary] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;
    window.getAfaSummary({ year, propertyId })
      .then(s => { if (!cancelled) setSummary(s); })
      .catch(() => {});
    return () => { cancelled = true; };
  }, [year, propertyId, assets]);

  const propAssets = (assets || []).filter(a => !propertyId || a.propertyId === propertyId);
  const openAdd = () => { setEditing(null); setShowForm(true); };

  return (
    <div className="section">
      <div className="section-header">
        <h2 className="section-title">Anlagenverzeichnis & AfA</h2>
        <div style={{ display: 'flex', gap: 8 }}>
          <select className="form-input" style={{ width: 100 }} value={year} onChange={e => setYear(Number(e.target.value))}>
            {Array.from({ length: 8 }, (_, i) => new Date().getFullYear() - 5 + i).map(y => <option key={y} value={y}>{y}</option>)}
          </select>
          <button className="btn btn-primary" onClick={openAdd}><Icon.Plus /> Anlage hinzufügen</button>
        </div>
      </div>
      <AssetForm open={showForm} onClose={() => setShowForm(false)} store={store} properties={properties} initial={editing} defaultPropertyId={propertyId} />
      <ConfirmDialog
        open={!!deleting}
        onClose={() => setDeleting(null)}
        onConfirm={async () => { await store.deleteAsset(deleting.id); }}
        title="Anlage löschen"
        message={`„${deleting?.label}" endgültig löschen?`}
        confirmLabel="Endgültig löschen"
      />

      {propAssets.length === 0 ? (
        <div className="empty" style={{ padding: 32 }}>
          <div className="empty-title">Noch keine Anlagen erfasst</div>
          <div style={{ color: 'var(--ink-3)', maxWidth: 460, margin: '8px auto' }}>
            Lege dein Gebäude (Anschaffungskosten × 80 % Gebäudeanteil) und Modernisierungen über 4.000 € als Anlagen an — Hausgut berechnet automatisch die jährliche AfA für die Steuererklärung.
          </div>
          <button className="btn btn-primary" onClick={openAdd} style={{ marginTop: 12 }}>Erste Anlage anlegen</button>
        </div>
      ) : (
        <>
          {summary && (
            <div className="kpi-grid" style={{ marginBottom: 16 }}>
              <div className="kpi">
                <div className="kpi-label">AfA {year}</div>
                <div className="kpi-value" style={{ color: 'var(--accent)' }}>{fmtEUR(summary.total.afaThisYear)}</div>
                <div className="kpi-meta">linear, abziehbare Werbungskosten</div>
              </div>
              <div className="kpi">
                <div className="kpi-label">Bisher abgeschrieben</div>
                <div className="kpi-value">{fmtEUR(summary.total.afaAccumulated)}</div>
                <div className="kpi-meta">kumuliert bis Ende {year}</div>
              </div>
              <div className="kpi">
                <div className="kpi-label">Buchwert</div>
                <div className="kpi-value">{fmtEUR(summary.total.bookValue)}</div>
                <div className="kpi-meta">verbleibender Wert {year}</div>
              </div>
              <div className="kpi">
                <div className="kpi-label">Anschaffung</div>
                <div className="kpi-value">{fmtEUR(summary.total.acquisitionCost)}</div>
                <div className="kpi-meta">{propAssets.length} Anlagen</div>
              </div>
            </div>
          )}
          <div className="table-wrap">
            <table className="table">
              <thead><tr><th>Bezeichnung</th><th>Typ</th><th>Anschaffung</th><th className="num">Kosten</th><th className="num">AfA-Satz</th><th className="num">AfA {year}</th><th className="num">Buchwert</th><th></th></tr></thead>
              <tbody>
                {(summary?.assets || []).filter(a => !propertyId || a.propertyId === propertyId).map(a => {
                  const orig = propAssets.find(x => x.id === a.id) || a;
                  const typeLabel = (window.ASSET_TYPES || []).find(t => t.value === a.type)?.label || a.type;
                  return (
                    <tr key={a.id} style={{ cursor: 'pointer' }} onClick={() => { setEditing(orig); setShowForm(true); }}>
                      <td className="strong">{a.label}</td>
                      <td className="muted">{typeLabel}</td>
                      <td className="muted" style={{ whiteSpace: 'nowrap' }}>{fmtDateShort(a.acquisitionDate)}</td>
                      <td className="num">{fmtEUR(a.acquisitionCost)}</td>
                      <td className="num muted">{a.afaRate.toFixed(1)} %</td>
                      <td className="num strong" style={{ color: 'var(--accent)' }}>{fmtEUR(a.afaThisYear)}</td>
                      <td className="num muted">{fmtEUR(a.bookValue)}</td>
                      <td onClick={e => e.stopPropagation()} style={{ whiteSpace: 'nowrap' }}>
                        <button className="btn-link" onClick={() => { setEditing(orig); setShowForm(true); }} title="Bearbeiten">✎</button>
                        <button className="btn-link" style={{ marginLeft: 8, color: 'var(--neg)' }} onClick={() => setDeleting(orig)} title="Löschen">✕</button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────
// TaxPage: Anlage V Vorbereitung
// ────────────────────────────────────────────────────────────────────
function TaxPage({ data, setRoute }) {
  const { properties, store } = data;
  const [year, setYear] = React.useState(new Date().getFullYear() - 1);
  const [propertyId, setPropertyId] = React.useState('');
  const [anlageV, setAnlageV] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState(null);

  const load = React.useCallback(async () => {
    setLoading(true); setErr(null);
    try {
      const r = await window.getAnlageV({ year, propertyId: propertyId || undefined });
      setAnlageV(r);
    } catch (e) { setErr(e.message); }
    finally { setLoading(false); }
  }, [year, propertyId]);

  React.useEffect(() => { load(); }, [load]);

  const datevUrl = window.datevExportUrl({ year, propertyId: propertyId || undefined });
  const printAnlageV = () => { window.print(); };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Steuer</h1>
          <div className="page-subtitle">Anlagenverzeichnis (AfA), Anlage V Vorbereitung & DATEV-Export</div>
        </div>
        <div className="page-actions">
          <select className="form-input" style={{ width: 110 }} value={year} onChange={e => setYear(Number(e.target.value))}>
            {Array.from({ length: 8 }, (_, i) => new Date().getFullYear() - 5 + i).map(y => <option key={y} value={y}>{y}</option>)}
          </select>
          <select className="form-input" style={{ width: 200 }} value={propertyId} onChange={e => setPropertyId(e.target.value)}>
            <option value="">Alle Objekte</option>
            {properties.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          <a className="btn" href={datevUrl} download>📊 DATEV-CSV</a>
          <button className="btn btn-primary" onClick={printAnlageV}>🖨 Anlage V drucken</button>
        </div>
      </div>

      {/* AfA-Sektion */}
      <AfaSection data={data} propertyId={propertyId || null} />

      {/* Anlage V */}
      <div className="section">
        <div className="section-header">
          <h2 className="section-title">Anlage V — Einkünfte aus Vermietung und Verpachtung {year}</h2>
        </div>
        {loading && <div className="empty" style={{ padding: 32 }}>Lade…</div>}
        {err && <div className="empty" style={{ padding: 32, color: 'var(--neg)' }}>⚠ {err}</div>}
        {!loading && anlageV && anlageV.properties.length === 0 && (
          <div className="empty" style={{ padding: 32 }}>Keine Daten für diesen Filter.</div>
        )}
        {!loading && anlageV && anlageV.properties.map(p => (
          <div key={p.propertyId} style={{ marginBottom: 32, padding: 16, border: '1px solid var(--line)', borderRadius: 'var(--radius)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
              <div>
                <h3 style={{ margin: 0, fontSize: 16 }}>{p.propertyName}</h3>
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{p.propertyAddress}{p.legalOwnerName ? ` · ${p.legalOwnerName}` : ''}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Ergebnis {year}</div>
                <div style={{ fontSize: 22, fontWeight: 500, color: p.result >= 0 ? 'var(--pos)' : 'var(--neg)' }}>
                  {fmtEUR(p.result)}
                </div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{p.result >= 0 ? 'Überschuss' : 'Verlust'}</div>
              </div>
            </div>

            {/* Einnahmen */}
            <div className="form-card" style={{ marginBottom: 12 }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 8 }}>Einnahmen (Zeilen 8–14)</div>
              <div className="kv-list">
                <div className="kv"><span className="k">Kaltmiete</span><span className="v">{fmtEUR(p.income.kaltmiete)}</span></div>
                <div className="kv"><span className="k">Nebenkostenvorauszahlungen</span><span className="v">{fmtEUR(p.income.nebenkosten)}</span></div>
                {p.income.kaution > 0 && <div className="kv"><span className="k">Kaution (nicht steuerbar)</span><span className="v" style={{ color: 'var(--ink-4)' }}>{fmtEUR(p.income.kaution)}</span></div>}
                {p.income.sonstiges > 0 && <div className="kv"><span className="k">Sonstige Einnahmen</span><span className="v">{fmtEUR(p.income.sonstiges)}</span></div>}
                <div className="kv" style={{ borderTop: '1px solid var(--line)', marginTop: 4, paddingTop: 8, fontWeight: 600 }}>
                  <span className="k">Summe Einnahmen</span><span className="v" style={{ color: 'var(--pos)' }}>{fmtEUR(p.totalIncome)}</span>
                </div>
              </div>
            </div>

            {/* Werbungskosten */}
            <div className="form-card">
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 8 }}>Werbungskosten (Zeilen 33–49)</div>
              <div className="kv-list">
                {p.expenseLines.map((l, i) => (
                  <div key={i} className="kv">
                    <span className="k">Z. {l.line} · {l.label}</span>
                    <span className="v">{fmtEUR(l.amount)}<span style={{ color: 'var(--ink-4)', fontSize: 11, marginLeft: 6 }}>({l.count})</span></span>
                  </div>
                ))}
                {p.afa.thisYear > 0 && (
                  <div className="kv" style={{ background: 'var(--accent-soft)', padding: '4px 8px', borderRadius: 4 }}>
                    <span className="k">Z. 33 · AfA Gebäude / Modernisierung</span>
                    <span className="v">{fmtEUR(p.afa.thisYear)}<span style={{ color: 'var(--ink-4)', fontSize: 11, marginLeft: 6 }}>({p.afa.assets} Anlagen)</span></span>
                  </div>
                )}
                <div className="kv" style={{ borderTop: '1px solid var(--line)', marginTop: 4, paddingTop: 8, fontWeight: 600 }}>
                  <span className="k">Summe Werbungskosten</span><span className="v" style={{ color: 'var(--neg)' }}>{fmtEUR(p.totalExpense)}</span>
                </div>
              </div>
            </div>
          </div>
        ))}

        {!loading && anlageV && anlageV.properties.length > 0 && (
          <div className="form-card" style={{ background: 'var(--accent-soft)', border: '1px solid var(--accent)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontWeight: 500, fontSize: 15 }}>Gesamtergebnis {year}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>
                  Summe aller Objekte · ohne Sonderfälle (Verluste &lt;1 J, Liebhaberei etc.)
                </div>
              </div>
              <div style={{ fontSize: 28, fontWeight: 500, color: anlageV.total.result >= 0 ? 'var(--pos)' : 'var(--neg)' }}>
                {fmtEUR(anlageV.total.result)}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 24, marginTop: 12, fontSize: 13, flexWrap: 'wrap' }}>
              <div>Einnahmen gesamt: <strong>{fmtEUR(anlageV.total.totalIncome)}</strong></div>
              <div>Werbungskosten gesamt: <strong>{fmtEUR(anlageV.total.totalExpense)}</strong></div>
              <div>davon AfA: <strong>{fmtEUR(anlageV.total.afa)}</strong></div>
            </div>
          </div>
        )}

        <div style={{ marginTop: 12, fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>
          ⚠ Diese Aufstellung ist eine <strong>Vorbereitungshilfe</strong> für deine Steuererklärung. Lass die Werte vor Einreichung
          immer von deinem Steuerberater prüfen — Hausgut ersetzt keine steuerliche Beratung. Sonderfälle (zeitanteilige Vermietung,
          Werbungskostenüberschuss-Verteilung, Modernisierungsregelung §82b EStDV) musst du ggf. manuell anpassen.
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────
// RentStatusPage: Soll vs. Ist + Mahn-Liste
// ────────────────────────────────────────────────────────────────────
function RentStatusPage({ data, setRoute }) {
  const { properties } = data;
  const [year, setYear] = React.useState(new Date().getFullYear());
  const [status, setStatus] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState(null);

  const load = React.useCallback(async () => {
    setLoading(true); setErr(null);
    try { setStatus(await window.getRentStatus({ year })); }
    catch (e) { setErr(e.message); }
    finally { setLoading(false); }
  }, [year]);

  React.useEffect(() => { load(); }, [load]);

  const goMahnung = (t) => {
    setRoute({ page: 'contracts', contractWizard: 'mahnung', propertyId: t.propertyId, unitId: t.unitId, tenantId: t.tenantId });
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Mieten-Status</h1>
          <div className="page-subtitle">Soll vs. Ist · Schuldner · Mahn-Aktionen</div>
        </div>
        <div className="page-actions">
          <select className="form-input" style={{ width: 110 }} value={year} onChange={e => setYear(Number(e.target.value))}>
            {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - 2 + i).map(y => <option key={y} value={y}>{y}</option>)}
          </select>
          <button className="btn" onClick={load}>↻ Neu berechnen</button>
        </div>
      </div>

      {loading && <div className="empty" style={{ padding: 40 }}>Lade…</div>}
      {err && <div className="empty" style={{ padding: 40, color: 'var(--neg)' }}>⚠ {err}</div>}

      {status && (
        <>
          <div className="kpi-grid">
            <div className="kpi">
              <div className="kpi-label">Soll {year}</div>
              <div className="kpi-value">{fmtEUR(status.summary.expectedTotal)}</div>
              <div className="kpi-meta">erwartete Mieteinnahmen</div>
            </div>
            <div className="kpi">
              <div className="kpi-label">Ist</div>
              <div className="kpi-value" style={{ color: 'var(--pos)' }}>{fmtEUR(status.summary.receivedTotal)}</div>
              <div className="kpi-meta">tatsächlich eingegangen</div>
            </div>
            <div className="kpi">
              <div className="kpi-label">Saldo</div>
              <div className="kpi-value" style={{ color: status.summary.saldoTotal >= -50 ? 'var(--pos)' : 'var(--neg)' }}>
                {fmtEUR(status.summary.saldoTotal)}
              </div>
              <div className="kpi-meta">{status.summary.saldoTotal >= -50 ? '✓ Portfolio ausgeglichen' : 'offene Forderungen'}</div>
            </div>
            <div className="kpi">
              <div className="kpi-label">Schuldner</div>
              <div className="kpi-value" style={{ color: status.summary.debtorsCount > 0 ? 'var(--neg)' : 'var(--pos)' }}>
                {status.summary.debtorsCount}
              </div>
              <div className="kpi-meta">{status.summary.missedMonthsTotal} fehlende Monate</div>
            </div>
          </div>

          <div className="section" style={{ marginTop: 24 }}>
            <div className="section-header">
              <h2 className="section-title">Pro Mieter</h2>
              <span className="muted" style={{ fontSize: 12 }}>{status.tenants.length} aktive Mieter</span>
            </div>
            {status.tenants.length === 0 ? (
              <div className="empty" style={{ padding: 32 }}>Keine aktiven Mietverhältnisse im Jahr {year}.</div>
            ) : (
              <div className="table-wrap">
                <table className="table">
                  <thead><tr><th>Mieter</th><th>Wohnung</th><th className="num">Soll</th><th className="num">Ist</th><th className="num">Saldo</th><th>Fehlende Monate</th><th></th></tr></thead>
                  <tbody>
                    {status.tenants.map(t => {
                      const isDebtor = t.saldo < -50;
                      return (
                        <tr key={t.tenantId}>
                          <td>
                            <button className="btn-link" onClick={() => setRoute({ page: 'tenants', tenantId: t.tenantId })} style={{ textAlign: 'left' }}>
                              <div className="strong">{t.tenantName}</div>
                              <div className="muted" style={{ fontSize: 11 }}>{t.tenantEmail || t.tenantPhone || ''}</div>
                            </button>
                          </td>
                          <td>
                            <button className="btn-link" onClick={() => setRoute({ page: 'properties', propertyId: t.propertyId, unitId: t.unitId })} style={{ textAlign: 'left' }}>
                              <div className="strong">{t.propertyName}</div>
                              <div className="muted" style={{ fontSize: 11 }}>{t.unitLabel}</div>
                            </button>
                          </td>
                          <td className="num muted">{fmtEUR(t.expectedAmount)}</td>
                          <td className="num">{fmtEUR(t.receivedAmount)}</td>
                          <td className="num strong" style={{ color: isDebtor ? 'var(--neg)' : 'var(--pos)' }}>
                            {t.saldo >= 0 ? '+' : ''}{fmtEUR(t.saldo)}
                          </td>
                          <td>
                            {t.missedMonths.length === 0 ? (
                              <span className="pill pos"><span className="pill-dot"></span>vollständig</span>
                            ) : (
                              <span style={{ fontSize: 11.5, color: 'var(--neg)' }}>
                                {t.missedMonths.length} ({t.missedMonths.slice(0, 3).join(', ')}{t.missedMonths.length > 3 ? '…' : ''})
                              </span>
                            )}
                          </td>
                          <td style={{ whiteSpace: 'nowrap' }}>
                            {isDebtor && (
                              <button className="btn btn-sm btn-primary" onClick={() => goMahnung(t)} title="Mahnung erstellen">⚠ Mahnen</button>
                            )}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────
// TasksPage: Aufgaben mit Done-Status
// ────────────────────────────────────────────────────────────────────
function TasksPage({ data }) {
  const { tasks, properties, store } = data;
  const [showForm, setShowForm] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const [filter, setFilter] = React.useState('open');

  const filtered = (tasks || []).filter(t => {
    if (filter === 'open') return !t.completedAt;
    if (filter === 'done') return !!t.completedAt;
    return true;
  });

  const toggleDone = async (t) => {
    await store.updateTask(t.id, { ...t, completed: !t.completedAt });
  };

  const openCount = (tasks || []).filter(t => !t.completedAt).length;
  const doneCount = (tasks || []).filter(t => t.completedAt).length;

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Aufgaben</h1>
          <div className="page-subtitle">{openCount} offen · {doneCount} erledigt</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-primary" onClick={() => { setEditing(null); setShowForm(true); }}><Icon.Plus /> Aufgabe</button>
        </div>
      </div>
      <TaskForm open={showForm} onClose={() => setShowForm(false)} store={store} properties={properties} initial={editing} />

      <div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
        {['open', 'done', 'all'].map(f => (
          <button key={f} className={`btn btn-sm ${filter === f ? 'btn-primary' : 'btn-ghost'}`} onClick={() => setFilter(f)}>
            {f === 'open' ? `Offen (${openCount})` : f === 'done' ? `Erledigt (${doneCount})` : 'Alle'}
          </button>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div className="empty" style={{ padding: 50, textAlign: 'center' }}>
          <div style={{ fontSize: 36, marginBottom: 8 }}>{filter === 'done' ? '🎉' : '✓'}</div>
          <div className="empty-title">{filter === 'done' ? 'Noch keine erledigten Aufgaben' : filter === 'open' ? 'Keine offenen Aufgaben' : 'Noch keine Aufgaben'}</div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {filtered.map(t => {
            const prop = properties.find(p => p.id === t.propertyId);
            const overdue = !t.completedAt && t.dueDate && t.dueDate < new Date().toISOString().slice(0, 10);
            return (
              <div key={t.id} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: 14, border: '1px solid var(--line)', borderRadius: 'var(--radius)', background: t.completedAt ? 'var(--bg-sunken)' : 'var(--bg-elev)' }}>
                <input
                  type="checkbox"
                  checked={!!t.completedAt}
                  onChange={() => toggleDone(t)}
                  style={{ marginTop: 4, width: 18, height: 18, cursor: 'pointer', flexShrink: 0 }}
                />
                <div style={{ flex: 1, minWidth: 0, cursor: 'pointer' }} onClick={() => { setEditing(t); setShowForm(true); }}>
                  <div style={{ fontWeight: 500, color: t.completedAt ? 'var(--ink-4)' : 'var(--ink)', textDecoration: t.completedAt ? 'line-through' : 'none' }}>
                    {t.title}
                  </div>
                  {t.description && (
                    <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>{t.description}</div>
                  )}
                  <div style={{ display: 'flex', gap: 8, marginTop: 6, fontSize: 11.5, alignItems: 'center', flexWrap: 'wrap' }}>
                    {t.dueDate && <span style={{ color: overdue ? 'var(--neg)' : 'var(--ink-3)' }}>{overdue ? '⚠ ' : '📅 '}{fmtDate(t.dueDate)}</span>}
                    {t.priority === 'hoch' && <Pill tone="warn">Hoch</Pill>}
                    {prop && <span style={{ color: 'var(--ink-3)' }}>📍 {prop.name}</span>}
                  </div>
                </div>
                <button className="btn-link" onClick={() => { setEditing(t); setShowForm(true); }}>✎</button>
                <button className="btn-link" style={{ color: 'var(--neg)' }} onClick={() => store.deleteTask(t.id)}>✕</button>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AfaSection, TaxPage, RentStatusPage, TasksPage });
