/* spočítAIto.cz — Historie page */

const { useState, useMemo } = React;

function HistoryPage({ properties, viewMode }) {
  const [range, setRange] = useState('12m'); // '6m' | '12m' | '24m'
  const [highlightId, setHighlightId] = useState('all');

  const months = range === '6m' ? 6 : range === '24m' ? 24 : 12;

  // Generate plausible history with seasonal & vacancy variation per property
  const history = useMemo(() => {
    const now = new Date(2026, 3, 1); // April 2026
    const data = [];
    for (let i = months - 1; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const monthIdx = d.getMonth();
      const seasonal = 1 + Math.sin((monthIdx / 12) * Math.PI * 2) * 0.03;
      const row = { date: d, label: monthLabel(d), gross: 0, costs: 0, net: 0, byProp: {} };
      for (const p of properties) {
        // Pure seasonal variation — no vacancy/spike noise so totals match dashboard baseline.
        const rent = Math.round(p.rent * seasonal);
        const costs = sumCosts(p.costs);
        const totalCosts = costs;
        const net = rent - totalCosts;
        const vacant = false;
        const spike = 0;
        row.gross += rent;
        row.costs += totalCosts;
        row.net += net;
        row.byProp[p.id] = { rent, costs: totalCosts, net, vacant, spike };
      }
      data.push(row);
    }
    return data;
  }, [properties, months]);

  const stats = useMemo(() => {
    const totalNet = history.reduce((a, r) => a + r.net, 0);
    const avgNet = totalNet / Math.max(1, history.length);
    const bestMonth = history.reduce((a, r) => (!a || r.net > a.net) ? r : a, null);
    const worstMonth = history.reduce((a, r) => (!a || r.net < a.net) ? r : a, null);
    const totalGross = history.reduce((a, r) => a + r.gross, 0);
    const totalCosts = history.reduce((a, r) => a + r.costs, 0);
    return { totalNet, avgNet, bestMonth, worstMonth, totalGross, totalCosts };
  }, [history]);

  return (
    <div className="page">
      <div className="page-toolbar">
        <div className="toolbar-left">
          <h1 className="page-title">Historie výnosů</h1>
          <span className="page-sub">Měsíční vývoj čistého příjmu z {properties.length} {properties.length < 5 ? 'nemovitostí' : 'nemovitostí'}</span>
        </div>
        <div className="toolbar-right">
          <div className="view-toggle" role="tablist">
            <button className={range === '6m' ? 'active' : ''} onClick={() => setRange('6m')} type="button">6 měs.</button>
            <button className={range === '12m' ? 'active' : ''} onClick={() => setRange('12m')} type="button">12 měs.</button>
            <button className={range === '24m' ? 'active' : ''} onClick={() => setRange('24m')} type="button">24 měs.</button>
          </div>
          <label className="select-wrap">
            <span className="caption">Nemovitost</span>
            <select value={highlightId} onChange={(e) => setHighlightId(e.target.value)}>
              <option value="all">Celé portfolio</option>
              {properties.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
          </label>
        </div>
      </div>

      <div className="stat-grid">
        <StatCard label="Čistý příjem celkem" value={fmtCZK(stats.totalNet)} sub={`${history.length} měsíců`} tone="pos" />
        <StatCard label="Průměrně měsíčně" value={fmtCZK(stats.avgNet)} sub="čistý výnos" />
        <StatCard label="Nejlepší měsíc" value={fmtCZK(stats.bestMonth?.net || 0)} sub={stats.bestMonth?.label || ''} tone="pos" />
        <StatCard label="Nejhorší měsíc" value={fmtCZK(stats.worstMonth?.net || 0)} sub={stats.worstMonth?.label || ''} tone={stats.worstMonth && stats.worstMonth.net < 0 ? 'neg' : ''} />
      </div>

      <div className="card chart-card">
        <div className="chart-head">
          <h2 className="card-title">Měsíční čistý výnos</h2>
          <div className="legend">
            <span className="legend-item"><span className="swatch sw-net" /> Čistý výnos</span>
            <span className="legend-item"><span className="swatch sw-gross" /> Hrubý příjem</span>
            <span className="legend-item"><span className="swatch sw-costs" /> Náklady</span>
          </div>
        </div>
        <HistoryChart history={history} highlightId={highlightId} />
      </div>

      <div className="card table-card">
        <div className="table-head">
          <h2 className="card-title">Měsíční přehled</h2>
        </div>
        <div className="history-table">
          <div className="ht-row ht-head">
            <span>Měsíc</span>
            <span className="ht-num">Hrubý</span>
            <span className="ht-num">Náklady</span>
            <span className="ht-num">Čistý</span>
            <span className="ht-note">Poznámka</span>
          </div>
          {[...history].reverse().map((r) => {
            const note = noteFor(r, properties);
            return (
              <div className="ht-row" key={r.label}>
                <span className="ht-month">{r.label}</span>
                <span className="ht-num num">{fmtCZK(r.gross)}</span>
                <span className="ht-num num">{fmtCZK(r.costs)}</span>
                <span className={`ht-num num ${r.net >= 0 ? 'pos' : 'neg'}`}>{r.net >= 0 ? '+' : ''}{fmtCZK(r.net)}</span>
                <span className="ht-note">{note}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function StatCard({ label, value, sub, tone }) {
  return (
    <div className="card stat-card">
      <span className="caption">{label}</span>
      <span className={`stat-value num ${tone || ''}`}>{value}</span>
      <span className="stat-sub">{sub}</span>
    </div>
  );
}

function noteFor(row, properties) {
  const notes = [];
  for (const pid in row.byProp) {
    const x = row.byProp[pid];
    const p = properties.find(pp => String(pp.id) === String(pid));
    if (!p) continue;
    if (x.vacant) notes.push(`${p.name.split(' ').slice(0, 2).join(' ')} — neobsazeno`);
    if (x.spike > 0) notes.push(`${p.name.split(' ').slice(0, 2).join(' ')} — oprava ${fmtCZK(x.spike)}`);
  }
  return notes.length ? notes.join(' · ') : '—';
}

function monthLabel(d) {
  const months = ['led', 'úno', 'bře', 'dub', 'kvě', 'čvn', 'čvc', 'srp', 'zář', 'říj', 'lis', 'pro'];
  return `${months[d.getMonth()]} ${String(d.getFullYear()).slice(-2)}`;
}

function HistoryChart({ history, highlightId }) {
  const W = 1180, H = 320, padL = 56, padR = 24, padT = 24, padB = 40;
  const innerW = W - padL - padR;
  const innerH = H - padT - padB;
  const n = history.length;

  const barW = (innerW / n) * 0.6;
  const step = innerW / n;

  const allValues = history.flatMap(r => [r.gross, r.net]);
  const max = Math.max(...allValues, 0);
  const min = Math.min(...history.map(r => r.net), 0);
  const range = max - min || 1;
  const yScale = (v) => padT + innerH - ((v - min) / range) * innerH;
  const zeroY = yScale(0);

  // gridlines (5)
  const ticks = 5;
  const gridLines = Array.from({ length: ticks + 1 }, (_, i) => {
    const v = min + (range / ticks) * i;
    return { v, y: yScale(v) };
  });

  // line for net
  const linePath = history.map((r, i) => {
    const x = padL + step * i + step / 2;
    const y = yScale(r.net);
    return `${i === 0 ? 'M' : 'L'} ${x} ${y}`;
  }).join(' ');

  return (
    <svg className="history-chart" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Měsíční vývoj">
      {/* gridlines */}
      {gridLines.map((g, i) => (
        <g key={i}>
          <line x1={padL} y1={g.y} x2={W - padR} y2={g.y} stroke="var(--border)" strokeWidth="1" strokeDasharray={g.v === 0 ? '0' : '2 4'} />
          <text x={padL - 8} y={g.y + 4} textAnchor="end" className="chart-tick">{fmtCZK(g.v)}</text>
        </g>
      ))}
      {/* zero baseline emphasis */}
      <line x1={padL} y1={zeroY} x2={W - padR} y2={zeroY} stroke="var(--text-muted)" strokeWidth="1" />

      {/* bars: gross (light), costs (subtle red), net (green/red) */}
      {history.map((r, i) => {
        const cx = padL + step * i + step / 2;
        const grossY = yScale(r.gross);
        const grossH = zeroY - grossY;
        const costH = (r.costs / range) * innerH;
        const netY = yScale(Math.max(r.net, 0));
        const netH = Math.abs(yScale(r.net) - zeroY);
        const isNeg = r.net < 0;

        return (
          <g key={i} className="bar-group">
            {/* gross bar (background) */}
            <rect x={cx - barW / 2} y={grossY} width={barW} height={Math.max(0, grossH)} fill="var(--green-50)" rx="2" />
            {/* cost overlay (top portion) */}
            <rect x={cx - barW / 2} y={grossY} width={barW} height={Math.min(grossH, costH)} fill="var(--bg-secondary)" rx="2" opacity="0.8" />
            {/* net bar */}
            <rect
              x={cx - barW / 2 + 2}
              y={isNeg ? zeroY : netY}
              width={barW - 4}
              height={Math.max(2, netH)}
              fill={isNeg ? 'var(--red-500)' : 'var(--green-500)'}
              rx="2"
            />
            <title>{`${r.label}\nHrubý: ${fmtCZK(r.gross)}\nNáklady: ${fmtCZK(r.costs)}\nČistý: ${r.net >= 0 ? '+' : ''}${fmtCZK(r.net)}`}</title>
          </g>
        );
      })}

      {/* trend line */}
      <path d={linePath} fill="none" stroke="var(--green-700)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" opacity="0.6" />
      {history.map((r, i) => {
        const x = padL + step * i + step / 2;
        const y = yScale(r.net);
        return <circle key={i} cx={x} cy={y} r="3" fill="white" stroke="var(--green-700)" strokeWidth="1.5" />;
      })}

      {/* x labels */}
      {history.map((r, i) => {
        if (n > 18 && i % 2 !== 0) return null;
        const x = padL + step * i + step / 2;
        return <text key={i} x={x} y={H - 14} textAnchor="middle" className="chart-tick">{r.label}</text>;
      })}
    </svg>
  );
}

window.HistoryPage = HistoryPage;
