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

const { useState: useStateExport } = React;

function ExportPage({ properties, taxMode }) {
  const [format, setFormat] = useStateExport('pdf');
  const [period, setPeriod] = useStateExport('year');
  const [includeCosts, setIncludeCosts] = useStateExport(true);
  const [includeTax, setIncludeTax] = useStateExport(true);
  const [includeChart, setIncludeChart] = useStateExport(true);
  const [recipient, setRecipient] = useStateExport('Pro vlastní potřebu');
  const [generating, setGenerating] = useStateExport(false);
  const [generated, setGenerated] = useStateExport(false);

  const monthMul = period === 'year' ? 12 : 1;
  const grossM = properties.reduce((a, p) => a + p.rent, 0);
  const costsM = properties.reduce((a, p) => a + sumCosts(p.costs), 0);
  const netM = grossM - costsM;
  const taxRate = taxMode === 'tax15' ? 0.15 : 0;
  const taxBase = taxMode === 'flat30' ? grossM * 0.7 : netM;
  const tax = taxMode !== 'none' ? Math.max(0, taxBase) * 0.15 : 0;
  const afterTax = netM - tax;

  const handleGenerate = () => {
    setGenerating(true);
    setGenerated(false);
    setTimeout(() => { setGenerating(false); setGenerated(true); }, 900);
  };

  return (
    <div className="page">
      <div className="page-toolbar">
        <div className="toolbar-left">
          <h1 className="page-title">Export</h1>
          <span className="page-sub">Vygenerujte přehled portfolia pro účetního, banku nebo vlastní potřebu.</span>
        </div>
      </div>

      <div className="export-layout">
        {/* Left: configurator */}
        <div className="export-config">
          <div className="card config-card">
            <h2 className="card-title">Formát</h2>
            <div className="format-grid">
              {[
                { id: 'pdf', label: 'PDF', desc: 'Tisknutelný přehled', icon: 'M6 2h7l5 5v11a2 2 0 01-2 2H6a2 2 0 01-2-2V4a2 2 0 012-2zM13 2v5h5' },
                { id: 'csv', label: 'CSV', desc: 'Pro Excel / účetní', icon: 'M4 4h16v16H4zM4 9h16M4 14h16M9 4v16M15 4v16' },
                { id: 'json', label: 'JSON', desc: 'Pro integrace', icon: 'M8 4l-2 2v4l-2 2 2 2v4l2 2M16 4l2 2v4l2 2-2 2v4l-2 2' },
              ].map(f => (
                <button key={f.id} className={`format-btn ${format === f.id ? 'active' : ''}`} onClick={() => { setFormat(f.id); setGenerated(false); }} type="button">
                  <span className="format-icon">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d={f.icon} /></svg>
                  </span>
                  <span className="format-label">{f.label}</span>
                  <span className="format-desc">{f.desc}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="card config-card">
            <h2 className="card-title">Období</h2>
            <div className="view-toggle wide" role="tablist">
              <button className={period === 'month' ? 'active' : ''} onClick={() => setPeriod('month')} type="button">Měsíčně</button>
              <button className={period === 'year' ? 'active' : ''} onClick={() => setPeriod('year')} type="button">Ročně</button>
              <button className={period === 'ytd' ? 'active' : ''} onClick={() => setPeriod('ytd')} type="button">Od ledna 2026</button>
            </div>
          </div>

          <div className="card config-card">
            <h2 className="card-title">Co zahrnout</h2>
            <div className="check-list">
              <Check checked={includeCosts} onChange={setIncludeCosts} label="Detailní rozpis nákladů" desc="Hypotéka, fond, pojištění..." />
              <Check checked={includeTax} onChange={setIncludeTax} label="Daňový souhrn" desc={taxMode === 'none' ? 'Daň není v dashboardu zapnutá' : 'Včetně daňového režimu z přehledu'} disabled={taxMode === 'none'} />
              <Check checked={includeChart} onChange={setIncludeChart} label="Graf flow diagramu" desc="Vizualizace toku peněz" />
            </div>
          </div>

          <div className="card config-card">
            <h2 className="card-title">Adresát</h2>
            <input className="text-input" value={recipient} onChange={(e) => { setRecipient(e.target.value); setGenerated(false); }} placeholder="Účetní, banka, vlastní..." />
          </div>

          <button className="btn btn-primary btn-lg" onClick={handleGenerate} type="button" disabled={generating}>
            {generating ? (
              <>
                <span className="spinner" /> Generuji…
              </>
            ) : generated ? (
              <>
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7l3 3 5-7"/></svg>
                Stáhnout {format.toUpperCase()}
              </>
            ) : (
              <>
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M7 2v8M3 7l4 3 4-3M2 12h10"/></svg>
                Vygenerovat {format.toUpperCase()}
              </>
            )}
          </button>

          {generated && (
            <div className="export-success">
              <span className="caption">Připraveno</span>
              <div className="success-row">
                <div className="success-file">
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 2h7l5 5v13a2 2 0 01-2 2H6a2 2 0 01-2-2V4a2 2 0 012-2z"/><path d="M13 2v5h5"/></svg>
                  <div>
                    <span className="success-name">spocitaito-prehled-{period}-04-2026.{format}</span>
                    <span className="success-meta">{format === 'pdf' ? '2 stránky · ' : ''}{Math.round(48 + Math.random() * 12)} kB</span>
                  </div>
                </div>
                <button className="btn btn-ghost" type="button">Otevřít</button>
              </div>
            </div>
          )}
        </div>

        {/* Right: preview */}
        <div className="export-preview-wrap">
          <span className="caption preview-label">Náhled</span>
          <div className={`pdf-preview ${format !== 'pdf' ? 'dim' : ''}`}>
            <div className="pdf-page">
              <div className="pdf-head">
                <div className="pdf-logo">
                  <span className="logo-a">spočít</span><span className="logo-ai">AI</span><span className="logo-a">to</span><span className="logo-cz">.cz</span>
                </div>
                <div className="pdf-meta">
                  <span className="caption">Přehled portfolia</span>
                  <span className="pdf-date">{period === 'year' ? 'Ročně · 2026' : period === 'month' ? 'Duben 2026' : 'Leden – Duben 2026'}</span>
                </div>
              </div>
              <div className="pdf-recipient">
                <span className="caption">Adresát</span>
                <span className="pdf-recipient-name">{recipient || '—'}</span>
              </div>

              <div className="pdf-headline">
                <div>
                  <span className="caption">Čistý {period === 'year' ? 'roční' : 'měsíční'} výnos</span>
                  <div className={`pdf-headline-num num ${netM >= 0 ? 'pos' : 'neg'}`}>{netM >= 0 ? '+' : ''}{fmtCZK(netM * monthMul)}</div>
                </div>
                <div className="pdf-summary-grid">
                  <div><span className="caption">Hrubý</span><span className="num">{fmtCZK(grossM * monthMul)}</span></div>
                  <div><span className="caption">Náklady</span><span className="num">{fmtCZK(costsM * monthMul)}</span></div>
                  <div><span className="caption">Marže</span><span className="num">{grossM > 0 ? fmtPct(((netM / grossM) * 100).toFixed(1)) : '—'}</span></div>
                </div>
              </div>

              <table className="pdf-table">
                <thead>
                  <tr>
                    <th>Nemovitost</th>
                    <th className="ta-r">Nájem</th>
                    {includeCosts && <th className="ta-r">Náklady</th>}
                    <th className="ta-r">Čistý</th>
                  </tr>
                </thead>
                <tbody>
                  {properties.map(p => {
                    const c = sumCosts(p.costs);
                    const n = (p.rent - c) * monthMul;
                    return (
                      <tr key={p.id}>
                        <td>{p.name}</td>
                        <td className="ta-r num">{fmtCZK(p.rent * monthMul)}</td>
                        {includeCosts && <td className="ta-r num">{fmtCZK(c * monthMul)}</td>}
                        <td className={`ta-r num ${n >= 0 ? 'pos' : 'neg'}`}>{n >= 0 ? '+' : ''}{fmtCZK(n)}</td>
                      </tr>
                    );
                  })}
                  <tr className="pdf-total">
                    <td>Celkem</td>
                    <td className="ta-r num">{fmtCZK(grossM * monthMul)}</td>
                    {includeCosts && <td className="ta-r num">{fmtCZK(costsM * monthMul)}</td>}
                    <td className={`ta-r num ${netM >= 0 ? 'pos' : 'neg'}`}>{netM >= 0 ? '+' : ''}{fmtCZK(netM * monthMul)}</td>
                  </tr>
                </tbody>
              </table>

              {includeChart && (
                <div className="pdf-chart">
                  <span className="caption">Tok peněz</span>
                  <MiniFlow properties={properties} netM={netM} />
                </div>
              )}

              {includeTax && taxMode !== 'none' && (
                <div className="pdf-tax">
                  <span className="caption">Daňový souhrn</span>
                  <div className="pdf-tax-grid">
                    <div><span>Režim</span><span>{taxMode === 'tax15' ? 'Daň 15 %' : 'Paušální výdaje 30 %'}</span></div>
                    <div><span>Daň</span><span className="num">{fmtCZK(tax * monthMul)}</span></div>
                    <div><span>Po zdanění</span><span className="num pos">{fmtCZK(afterTax * monthMul)}</span></div>
                  </div>
                </div>
              )}

              <div className="pdf-foot">
                <span>Vygenerováno spočítAIto.cz · 26. dubna 2026</span>
                <span>Strana 1 / {includeChart ? 2 : 1}</span>
              </div>
            </div>
          </div>
          {format !== 'pdf' && (
            <div className="format-overlay">
              <div className="overlay-card">
                <span className="caption">{format.toUpperCase()} výstup</span>
                <pre className="format-sample">{format === 'csv' ? csvSample(properties) : jsonSample(properties)}</pre>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function MiniFlow({ properties, netM }) {
  const W = 520, H = 130;
  const n = properties.length;
  const stepX = (W - 80) / Math.max(1, n);
  const cy = 90;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="mini-flow" role="img">
      {properties.map((p, i) => {
        const x = 40 + stepX * i + stepX / 2;
        const net = p.rent - sumCosts(p.costs);
        const isPos = net >= 0;
        const stroke = isPos ? '#16A34A' : '#EF4444';
        const d = `M ${x} 36 C ${x} 60, ${W/2} 60, ${W/2} ${cy}`;
        return (
          <g key={p.id}>
            <rect x={x - 38} y={12} width={76} height={28} rx={6} fill="white" stroke="#E2E8F0" />
            <text x={x} y={30} textAnchor="middle" className="mf-text">{p.name.split(' ').slice(0, 2).join(' ')}</text>
            <path d={d} stroke={stroke} strokeWidth="2" fill="none" strokeDasharray="4 4" opacity="0.7" />
          </g>
        );
      })}
      <rect x={W/2 - 70} y={cy - 10} width={140} height={32} rx={6} fill={netM >= 0 ? '#F0FAF4' : '#FEF2F2'} stroke={netM >= 0 ? '#BBF7D0' : '#FECACA'} />
      <text x={W/2} y={cy + 11} textAnchor="middle" className="mf-text-strong">Vaše kapsa</text>
    </svg>
  );
}

function Check({ checked, onChange, label, desc, disabled }) {
  return (
    <label className={`check ${disabled ? 'disabled' : ''}`}>
      <input type="checkbox" checked={!!checked && !disabled} onChange={(e) => onChange(e.target.checked)} disabled={disabled} />
      <span className="check-box" aria-hidden="true">
        {checked && !disabled && <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M2 5l2 2 4-5"/></svg>}
      </span>
      <span className="check-body">
        <span className="check-label">{label}</span>
        <span className="check-desc">{desc}</span>
      </span>
    </label>
  );
}

function csvSample(properties) {
  const head = 'nazev,najem,naklady,cisty';
  const rows = properties.map(p => {
    const c = sumCosts(p.costs);
    return `"${p.name}",${p.rent},${c},${p.rent - c}`;
  });
  return [head, ...rows].join('\n');
}

function jsonSample(properties) {
  return JSON.stringify({
    generated: '2026-04-26',
    portfolio: properties.slice(0, 2).map(p => ({
      name: p.name, rent: p.rent, costs: p.costs, net: p.rent - sumCosts(p.costs),
    })),
  }, null, 2);
}

window.ExportPage = ExportPage;
