// Dashboard + Properties list pages

function Dashboard({ data, setRoute }) {
  const { properties, transactions, reminders, tenants, store, settings } = data;
  const [showPropertyForm, setShowPropertyForm] = React.useState(false);
  const [showTxForm, setShowTxForm] = React.useState(false);
  const [showImport, setShowImport] = React.useState(false);
  const [catJob, setCatJob] = React.useState(null); // { jobId, total, done, categorized, finished, error }
  const uncategorizedCount = transactions.filter(t => !t.category).length;
  const categorizing = catJob && !catJob.finished;
  const runCategorize = async () => {
    try {
      const r = await window.categorizeTransactions();
      setCatJob(r);
    } catch (e) {
      setCatJob({ error: e.message, finished: true });
    }
  };
  // Poll while job is running
  React.useEffect(() => {
    if (!catJob?.jobId || catJob.finished) return;
    let cancelled = false;
    const tick = async () => {
      try {
        const s = await window.getCategorizeStatus(catJob.jobId);
        if (cancelled) return;
        setCatJob(s);
        if (!s.finished) setTimeout(tick, 1500);
        else await store.reload();
      } catch (e) {
        if (!cancelled) setCatJob(p => ({ ...(p || {}), error: e.message, finished: true }));
      }
    };
    setTimeout(tick, 1000);
    return () => { cancelled = true; };
  }, [catJob?.jobId, catJob?.finished, store]);
  const ownerFirstName = (settings?.ownerName || '').trim().split(/\s+/)[0] || '';
  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 11) return 'Guten Morgen';
    if (h < 18) return 'Guten Tag';
    return 'Guten Abend';
  })();

  const totalUnits = properties.reduce((s, p) => s + p.units.length, 0);
  const occupiedUnits = properties.reduce((s, p) => s + p.units.filter(u => u.status === 'vermietet').length, 0);
  const occupancyRate = totalUnits > 0 ? Math.round((occupiedUnits / totalUnits) * 100) : 0;

  // Onboarding empty state — no properties yet
  if (properties.length === 0) {
    return (
      <div className="page">
        <div className="page-header">
          <div>
            <h1 className="page-title">Willkommen bei Hausgut.</h1>
            <div className="page-subtitle">Lege dein erstes Objekt an, um zu starten.</div>
          </div>
        </div>
        <div className="empty" style={{ padding: '60px 20px', textAlign: 'center' }}>
          <div style={{ fontSize: 48, marginBottom: 12 }}>🏠</div>
          <div className="empty-title" style={{ marginBottom: 8 }}>Noch keine Immobilien angelegt</div>
          <div style={{ color: 'var(--ink-3)', maxWidth: 420, margin: '0 auto 24px' }}>
            Trage deine Immobilien ein, dann kannst du Wohnungen, Mieter, Buchungen und Dokumente verwalten.
          </div>
          <button className="btn btn-primary" onClick={() => setShowPropertyForm(true)}>
            <Icon.Plus /> Erstes Objekt anlegen
          </button>
        </div>
        <PropertyForm open={showPropertyForm} onClose={() => setShowPropertyForm(false)} store={store} />
      </div>
    );
  }

  // Last 12 months
  const now = new Date(2026, 4, 1);
  const monthKey = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
  const months = [];
  for (let i = 11; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    months.push({ key: monthKey(d), label: d.toLocaleDateString('de-DE', { month: 'short' }), date: d });
  }

  const monthData = months.map(m => {
    const inc = transactions.filter(t => t.date.startsWith(m.key) && t.type === 'einnahme').reduce((s, t) => s + t.amount, 0);
    const exp = transactions.filter(t => t.date.startsWith(m.key) && t.type === 'ausgabe').reduce((s, t) => s + Math.abs(t.amount), 0);
    return { ...m, income: inc, expense: exp, net: inc - exp };
  });

  const ytdIncome = transactions.filter(t => t.date.startsWith('2026') && t.type === 'einnahme').reduce((s, t) => s + t.amount, 0);
  const ytdExpense = transactions.filter(t => t.date.startsWith('2026') && t.type === 'ausgabe').reduce((s, t) => s + Math.abs(t.amount), 0);
  const ytdNet = ytdIncome - ytdExpense;

  const recentTxns = [...transactions].slice(0, 6);

  const upcoming = [...reminders].sort((a, b) => a.date.localeCompare(b.date)).slice(0, 4);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">{greeting}{ownerFirstName ? `, ${ownerFirstName}` : ''}.</h1>
          <div className="page-subtitle">Mai 2026 · {properties.length} Objekte · {totalUnits} Einheiten</div>
        </div>
        <div className="page-actions">
          <button className="btn" onClick={() => setShowImport(true)}>📊 CSV importieren</button>
          <button className="btn" onClick={() => setShowPropertyForm(true)}><Icon.Plus /> Objekt</button>
          <button className="btn btn-primary" onClick={() => setShowTxForm(true)}><Icon.Plus /> Buchung erfassen</button>
        </div>
      </div>
      <PropertyForm open={showPropertyForm} onClose={() => setShowPropertyForm(false)} store={store} />
      <TransactionForm open={showTxForm} onClose={() => setShowTxForm(false)} store={store} properties={properties} />
      <CsvImportModal open={showImport} onClose={() => setShowImport(false)} store={store} properties={properties} />

      <div className="kpi-grid">
        <div className="kpi">
          <div className="kpi-label">Mieteinnahmen YTD</div>
          <div className="kpi-value">{fmtEUR(ytdIncome)}</div>
          <div className="kpi-meta">{transactions.length === 0 ? 'noch keine Buchungen' : `${new Date().getFullYear()}`}</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Ausgaben YTD</div>
          <div className="kpi-value">{fmtEUR(ytdExpense)}</div>
          <div className="kpi-meta">{transactions.length === 0 ? '—' : `${new Date().getFullYear()}`}</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Netto-Cashflow</div>
          <div className="kpi-value">{fmtEUR(ytdNet)}</div>
          <div className="kpi-meta">{transactions.length === 0 ? '—' : 'lfd. Jahr'}</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Auslastung</div>
          <div className="kpi-value">{totalUnits === 0 ? '—' : `${occupancyRate} %`}</div>
          <div className="kpi-meta">{totalUnits === 0 ? 'keine Einheiten' : `${occupiedUnits} / ${totalUnits} Einheiten`}</div>
        </div>
      </div>

      <div className="section">
        <div className="section-header">
          <h2 className="section-title">Cashflow · letzte 12 Monate</h2>
          <button className="section-link" onClick={() => setRoute({ page: 'reports' })}>Alle Berichte →</button>
        </div>
        {transactions.length === 0 ? (
          <div className="empty"><div className="empty-title">Noch keine Buchungen</div><div>Erfasse deine erste Buchung — der Chart füllt sich mit der Zeit.</div></div>
        ) : (
          <CashflowChart data={monthData} />
        )}
      </div>

      <div className="section" style={{ marginBottom: 32 }}>
        <div className="section-header">
          <h2 className="section-title">Schnell-Upload</h2>
          <span className="muted" style={{ fontSize: 11.5 }}>PDFs, Belege, Fotos — Objekt wird im nächsten Schritt zugeordnet</span>
        </div>
        <DropZone
          compact
          properties={properties}
          onUpload={() => store.reload()}
          label="Datei hierher ziehen oder klicken zum Auswählen"
          subLabel="KI versucht, Kategorie + Objekt automatisch zu erkennen"
        />
      </div>

      {(uncategorizedCount > 0 || categorizing) && (
        <div className="section" style={{ marginBottom: 32 }}>
          <div style={{ padding: '14px 18px', background: 'var(--accent-soft)', border: '1px solid var(--accent)', borderRadius: 'var(--radius)' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>
                  🤖 {categorizing
                    ? `KI kategorisiert ${catJob.done} von ${catJob.total} Buchungen…`
                    : catJob?.finished && !catJob?.error
                      ? `✓ ${catJob.categorized} von ${catJob.total} Buchungen kategorisiert · ${uncategorizedCount} verbleibend`
                      : `${uncategorizedCount} ${uncategorizedCount === 1 ? 'Buchung ohne Kategorie' : 'Buchungen ohne Kategorie'}`}
                </div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>
                  {categorizing
                    ? 'Läuft im Hintergrund — das Dashboard aktualisiert sich automatisch wenn fertig.'
                    : 'Lass die KI Kategorien vorschlagen anhand Empfänger + Verwendungszweck.'}
                </div>
                {catJob?.error && <div style={{ fontSize: 12, marginTop: 6, color: 'var(--neg)' }}>⚠ {catJob.error}</div>}
              </div>
              {!categorizing && uncategorizedCount > 0 && (
                <button className="btn btn-primary" onClick={runCategorize}>
                  Jetzt kategorisieren
                </button>
              )}
            </div>
            {categorizing && (
              <div style={{ height: 6, background: 'var(--line-2)', borderRadius: 999, overflow: 'hidden', marginTop: 10 }}>
                <div style={{
                  height: '100%',
                  width: `${(catJob.done / Math.max(1, catJob.total)) * 100}%`,
                  background: 'var(--accent)',
                  transition: 'width 200ms',
                }} />
              </div>
            )}
          </div>
        </div>
      )}

      <div className="two-col">
        <div className="section" style={{ marginBottom: 0 }}>
          <div className="section-header">
            <h2 className="section-title">Letzte Buchungen</h2>
            <button className="section-link">Alle anzeigen →</button>
          </div>
          {recentTxns.length === 0 ? (
            <div className="empty" style={{ padding: '24px 16px' }}><div style={{ color: 'var(--ink-3)' }}>Noch keine Buchungen erfasst.</div></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>
                  {recentTxns.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 || tx.category || '—'}</td>
                        <td className="muted">{prop ? prop.name : '—'}</td>
                        <td className="num strong" style={{ color: tx.amount > 0 ? 'var(--pos)' : 'var(--neg)' }}>
                          {tx.amount > 0 ? '+' : ''}{fmtEUR(tx.amount)}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        <div className="section" style={{ marginBottom: 0 }}>
          <div className="section-header">
            <h2 className="section-title">Anstehende Fristen</h2>
            <button className="section-link" onClick={() => setRoute({ page: 'calendar' })}>Kalender →</button>
          </div>
          {upcoming.length === 0 ? (
            <div className="empty" style={{ padding: '24px 16px' }}><div style={{ color: 'var(--ink-3)' }}>Keine anstehenden Termine.</div></div>
          ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 0, borderTop: '1px solid var(--line)' }}>
            {upcoming.map(r => {
              const d = new Date(r.date);
              const day = d.getDate();
              const month = d.toLocaleDateString('de-DE', { month: 'short' });
              return (
                <div key={r.id} style={{ display: 'flex', gap: 14, padding: '14px 4px', borderBottom: '1px solid var(--line)', alignItems: 'flex-start' }}>
                  <div style={{ textAlign: 'center', minWidth: 36 }}>
                    <div style={{ fontFamily: 'var(--font-serif)', fontSize: 22, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>{day}</div>
                    <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--ink-4)', marginTop: 2 }}>{month}</div>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 500, marginBottom: 3 }}>{r.title}</div>
                    <Pill tone={r.priority === 'hoch' ? 'warn' : 'default'}>{r.category}</Pill>
                  </div>
                </div>
              );
            })}
          </div>
          )}
        </div>
      </div>
    </div>
  );
}

function CashflowChart({ data }) {
  const W = 1100, H = 280;
  const pad = { l: 50, r: 20, t: 10, b: 30 };
  const cw = W - pad.l - pad.r, ch = H - pad.t - pad.b;
  const max = Math.max(...data.map(d => Math.max(d.income, d.expense))) * 1.1;
  const niceMax = Math.ceil(max / 5000) * 5000;

  const bw = cw / data.length;
  const barW = bw * 0.32;

  const ticks = [0, 0.25, 0.5, 0.75, 1].map(t => Math.round(niceMax * t));

  const netPath = data.map((d, i) => {
    const x = pad.l + bw * i + bw / 2;
    const y = pad.t + ch - (d.net / niceMax) * ch;
    return `${i === 0 ? 'M' : 'L'} ${x} ${y}`;
  }).join(' ');

  return (
    <div className="chart-frame">
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
        <g className="chart-grid">
          {ticks.map((t, i) => {
            const y = pad.t + ch - (t / niceMax) * ch;
            return <line key={i} x1={pad.l} x2={W - pad.r} y1={y} y2={y} />;
          })}
        </g>
        <g className="chart-axis">
          {ticks.map((t, i) => {
            const y = pad.t + ch - (t / niceMax) * ch;
            return <text key={i} x={pad.l - 8} y={y + 3} textAnchor="end">{(t / 1000).toFixed(0)}k</text>;
          })}
          {data.map((d, i) => (
            <text key={i} x={pad.l + bw * i + bw / 2} y={H - 10} textAnchor="middle">{d.label}</text>
          ))}
        </g>
        {data.map((d, i) => {
          const xCenter = pad.l + bw * i + bw / 2;
          const incH = (d.income / niceMax) * ch;
          const expH = (d.expense / niceMax) * ch;
          return (
            <g key={i}>
              <rect className="chart-bar income" x={xCenter - barW - 2} y={pad.t + ch - incH} width={barW} height={incH} rx="1"/>
              <rect className="chart-bar expense" x={xCenter + 2} y={pad.t + ch - expH} width={barW} height={expH} rx="1"/>
            </g>
          );
        })}
        <path className="chart-line" d={netPath} />
        {data.map((d, i) => {
          const x = pad.l + bw * i + bw / 2;
          const y = pad.t + ch - (d.net / niceMax) * ch;
          return <circle key={i} cx={x} cy={y} r="2.5" fill="var(--ink)" />;
        })}
      </svg>
      <div className="chart-legend">
        <span className="chart-legend-item"><span className="chart-legend-swatch" style={{ background: 'var(--accent)' }}></span> Einnahmen</span>
        <span className="chart-legend-item"><span className="chart-legend-swatch" style={{ background: 'var(--ink-5)' }}></span> Ausgaben</span>
        <span className="chart-legend-item"><span className="chart-legend-swatch" style={{ background: 'var(--ink)', height: 2, borderRadius: 0, marginTop: 4 }}></span> Netto</span>
      </div>
    </div>
  );
}

function PropertiesList({ data, setRoute }) {
  const { properties, tenants, transactions, store } = data;
  const [showForm, setShowForm] = React.useState(false);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Objekte</h1>
          <div className="page-subtitle">{properties.length} {properties.length === 1 ? 'Hauptimmobilie' : 'Hauptimmobilien'} · {properties.reduce((s, p) => s + p.units.length, 0)} Einheiten</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-primary" onClick={() => setShowForm(true)}><Icon.Plus /> Objekt anlegen</button>
        </div>
      </div>
      <PropertyForm open={showForm} onClose={() => setShowForm(false)} store={store} />

      {properties.length === 0 && (
        <div className="empty" style={{ padding: '60px 20px', textAlign: 'center' }}>
          <div style={{ fontSize: 40, marginBottom: 12 }}>🏠</div>
          <div className="empty-title">Noch keine Objekte</div>
          <div style={{ color: 'var(--ink-3)', maxWidth: 360, margin: '0 auto 20px' }}>Lege deine erste Immobilie an, um Wohnungen, Mieter und Buchungen zu verwalten.</div>
          <button className="btn btn-primary" onClick={() => setShowForm(true)}><Icon.Plus /> Erstes Objekt anlegen</button>
        </div>
      )}

      <div className="prop-grid">
        {properties.map(prop => {
          const occupied = prop.units.filter(u => u.status === 'vermietet').length;
          const total = prop.units.length;
          const monthlyRent = prop.units.reduce((s, u) => s + (u.rent || 0), 0);
          const totalSize = prop.units.reduce((s, u) => s + (u.size || 0), 0);
          const occRatio = total > 0 ? occupied / total : 0;

          return (
            <button key={prop.id} className="prop-card" onClick={() => setRoute({ page: 'properties', propertyId: prop.id })}>
              <div className="prop-card-header">
                <div className="prop-card-name">{prop.name}</div>
                <div className="prop-card-addr">{prop.address}</div>
              </div>

              <div className="occ-bar">
                <div className="occ-bar-fill" style={{ width: `${occRatio * 100}%` }}></div>
                <div className="occ-bar-vacant" style={{ width: `${(1 - occRatio) * 100}%` }}></div>
              </div>

              <div className="prop-card-stats">
                <div className="prop-card-stat">
                  <div className="v">{occupied}<span style={{ color: 'var(--ink-4)' }}>/{total}</span></div>
                  <div className="l">Einheiten</div>
                </div>
                <div className="prop-card-stat">
                  <div className="v">{fmtEUR(monthlyRent)}</div>
                  <div className="l">Soll/Monat</div>
                </div>
                <div className="prop-card-stat">
                  <div className="v">{totalSize} m²</div>
                  <div className="l">Wohnfläche</div>
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard, PropertiesList, CashflowChart });
