// Forecasting module with 5 tabs
const Forecasting = () => {
  const [tab, setTab] = React.useState('cashflow');
  const [scenarioVars, setScenarioVars] = React.useState({ revenues: 0, costs: 0, rates: 3.8 });
  const F = window.REGULA_EXT.forecasting;

  const tabs = [
    { id: 'cashflow', label: 'Cash Flow' },
    { id: 'bva', label: 'Budget vs Actual' },
    { id: 'whatif', label: 'What-If Scenario' },
    { id: 'roi', label: 'ROI Simulator' },
    { id: 'stress', label: 'Stress Test Covenant' }
  ];

  // Line chart helper
  const LineChart = ({ data, w = 860, h = 180, label = "M€" }) => {
    const padL = 28, padR = 12, padT = 12, padB = 24;
    const cw = w - padL - padR, ch = h - padT - padB;
    const min = Math.min(...data) * 0.95, max = Math.max(...data) * 1.05;
    const step = cw / (data.length - 1);
    const y = v => padT + ch - ((v - min) / (max - min)) * ch;
    const pts = data.map((v, i) => [padL + i * step, y(v)]);
    const d = pts.map((p, i) => (i === 0 ? 'M' : 'L') + p[0] + ',' + p[1]).join(' ');
    const areaD = d + ` L${padL + cw},${padT + ch} L${padL},${padT + ch} Z`;
    return (
      <svg width={w} height={h}>
        {[min, (min+max)/2, max].map((t, i) => (
          <g key={i}>
            <line x1={padL} x2={w-padR} y1={y(t)} y2={y(t)} className="grid-line" />
            <text x={padL-4} y={y(t)+3} textAnchor="end" className="axis-label">{t.toFixed(1)}</text>
          </g>
        ))}
        <path d={areaD} fill="var(--accent)" opacity="0.12" />
        <path d={d} stroke="var(--accent)" strokeWidth="1.5" fill="none" />
        {pts.map((p, i) => i % 2 === 0 && <circle key={i} cx={p[0]} cy={p[1]} r="2" fill="var(--accent)" />)}
        {data.map((v, i) => i % 2 === 0 && (
          <text key={i} x={padL + i*step} y={h-6} textAnchor="middle" className="axis-label">W{i+1}</text>
        ))}
      </svg>
    );
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Forecasting</h1>
          <div className="page-subtitle">Proiezioni AI · rolling 13 settimane · 12 mesi · 3-5 anni</div>
        </div>
        <div className="page-meta">
          <button className="pill-select">Base · aggiornato 14:22 <Icon name="down" size={10} /></button>
          <button className="btn btn-primary"><Icon name="download" size={12} /> Report</button>
        </div>
      </div>

      <div className="tabs" style={{ marginTop: 16 }}>
        {tabs.map(t => (
          <div key={t.id} className={`tab ${tab === t.id ? 'active' : ''}`} onClick={() => setTab(t.id)}>{t.label}</div>
        ))}
      </div>

      {tab === 'cashflow' && (
        <>
          <div className="section">
            <div className="panel">
              <div className="panel-head">
                <div className="panel-title">Cash flow rolling · 13 settimane</div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <button className="pill-select">Consolidato <Icon name="down" size={10} /></button>
                  <span className="chip green">Min 39.6 M€</span>
                  <span className="chip">Max 44.8 M€</span>
                </div>
              </div>
              <div className="panel-body">
                <LineChart data={F.cashFlow13w} />
              </div>
            </div>
          </div>
          <div className="section cols-2">
            <div className="panel">
              <div className="panel-head"><div className="panel-title">Cash in · principali flussi in ingresso</div></div>
              <table className="data">
                <thead><tr><th>Fonte</th><th>Società</th><th className="n">13w</th><th className="n">12m</th></tr></thead>
                <tbody>
                  <tr><td>Incassi clienti commerciali</td><td>MetalTech</td><td className="n">12.4</td><td className="n">48.6</td></tr>
                  <tr><td>Ticket parco stagionali</td><td>Aqua World</td><td className="n">4.8</td><td className="n">18.6</td></tr>
                  <tr><td>Incassi serate + bar</td><td>Club Lumière</td><td className="n">1.6</td><td className="n">6.4</td></tr>
                  <tr><td>Donazioni + 5×1000</td><td>Fondazione</td><td className="n">0.9</td><td className="n">3.8</td></tr>
                  <tr className="total-row"><td colSpan="2">Totale</td><td className="n">19.7</td><td className="n">77.4</td></tr>
                </tbody>
              </table>
            </div>
            <div className="panel">
              <div className="panel-head"><div className="panel-title">Cash out · principali flussi in uscita</div></div>
              <table className="data">
                <thead><tr><th>Categoria</th><th>Società</th><th className="n">13w</th><th className="n">12m</th></tr></thead>
                <tbody>
                  <tr><td>Stipendi e contributi</td><td>Tutte</td><td className="n">−6.2</td><td className="n">−24.8</td></tr>
                  <tr><td>Fornitori materie prime</td><td>MetalTech</td><td className="n">−5.4</td><td className="n">−21.6</td></tr>
                  <tr><td>Rate mutui e oneri fin.</td><td>Tutte</td><td className="n">−2.1</td><td className="n">−8.0</td></tr>
                  <tr><td>F24 e imposte</td><td>Tutte</td><td className="n">−1.8</td><td className="n">−16.0</td></tr>
                  <tr className="total-row"><td colSpan="2">Totale</td><td className="n">−15.5</td><td className="n">−70.4</td></tr>
                </tbody>
              </table>
            </div>
          </div>
        </>
      )}

      {tab === 'bva' && (
        <div className="section">
          <div className="panel">
            <div className="panel-head">
              <div className="panel-title">Scostamenti YTD con proiezione FY</div>
              <span className="chip accent">Proiezione automatica</span>
            </div>
            <table className="data">
              <thead>
                <tr>
                  <th>Categoria</th>
                  <th className="n">Actual YTD</th>
                  <th className="n">Budget YTD</th>
                  <th className="n">Δ YTD</th>
                  <th className="n">Proiezione FY</th>
                  <th className="n">Budget FY</th>
                  <th className="n">Δ FY attesa</th>
                </tr>
              </thead>
              <tbody>
                {F.bva.map((row, i) => {
                  const dytd = ((row.actual - row.budget) / row.budget) * 100;
                  const dfy = ((row.fy - row.fyBudget) / row.fyBudget) * 100;
                  return (
                    <tr key={i}>
                      <td style={{ fontWeight: 500 }}>{row.category}</td>
                      <td className="n">{row.actual.toFixed(1)}</td>
                      <td className="n" style={{ color: 'var(--muted)' }}>{row.budget.toFixed(1)}</td>
                      <td className="n" style={{ color: dytd > 0 ? 'var(--green)' : 'var(--red)' }}>{dytd > 0 ? '+' : ''}{dytd.toFixed(1)}%</td>
                      <td className="n">{row.fy.toFixed(1)}</td>
                      <td className="n" style={{ color: 'var(--muted)' }}>{row.fyBudget.toFixed(1)}</td>
                      <td className="n" style={{ color: dfy > 0 ? 'var(--green)' : 'var(--red)' }}>{dfy > 0 ? '+' : ''}{dfy.toFixed(1)}%</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'whatif' && (
        <div className="section cols-2-3">
          <div className="panel">
            <div className="panel-head"><div className="panel-title">Variabili</div></div>
            <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              {[
                { key: 'revenues', label: 'Ricavi', unit: '%', min: -20, max: 20 },
                { key: 'costs', label: 'Costi variabili', unit: '%', min: -10, max: 20 },
                { key: 'rates', label: 'Tasso medio debito', unit: '%', min: 2, max: 7, step: 0.1 }
              ].map(v => (
                <div key={v.key}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 6 }}>
                    <span>{v.label}</span>
                    <span className="mono" style={{ fontWeight: 500 }}>{scenarioVars[v.key]}{v.unit}</span>
                  </div>
                  <input type="range" min={v.min} max={v.max} step={v.step || 1}
                    value={scenarioVars[v.key]}
                    onChange={e => setScenarioVars({ ...scenarioVars, [v.key]: parseFloat(e.target.value) })}
                    style={{ width: '100%' }}
                  />
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--f-mono)', fontSize: 10, color: 'var(--muted-2)', textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: 2 }}>
                    <span>{v.min}{v.unit}</span><span>{v.max}{v.unit}</span>
                  </div>
                </div>
              ))}
              <button className="btn btn-primary" style={{ marginTop: 6 }}><Icon name="plus" size={12} /> Aggiungi scenario</button>
            </div>
          </div>
          <div className="panel">
            <div className="panel-head"><div className="panel-title">Confronto scenari</div></div>
            <table className="data">
              <thead>
                <tr>
                  <th>Scenario</th>
                  <th className="n">Ricavi</th><th className="n">Costi</th><th className="n">Tassi</th>
                  <th className="n">EBITDA</th><th className="n">Utile netto</th><th className="n">Cash EoY</th>
                </tr>
              </thead>
              <tbody>
                {F.scenarios.map((s, i) => (
                  <tr key={i} style={s.name === 'Base' ? { fontWeight: 500 } : {}}>
                    <td><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: 2, background: s.color, marginRight: 6 }} />{s.name}</td>
                    <td className="n" style={{ color: s.revenues > 0 ? 'var(--green)' : s.revenues < 0 ? 'var(--red)' : 'var(--muted)' }}>{s.revenues > 0 ? '+' : ''}{s.revenues}%</td>
                    <td className="n" style={{ color: s.costs > 0 ? 'var(--red)' : 'var(--muted)' }}>{s.costs > 0 ? '+' : ''}{s.costs}%</td>
                    <td className="n">{s.rates}%</td>
                    <td className="n">{s.ebitda.toFixed(1)}</td>
                    <td className="n">{s.netIncome.toFixed(1)}</td>
                    <td className="n">{s.cash.toFixed(1)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'roi' && (
        <div className="section cols-2-3">
          <div className="panel">
            <div className="panel-head"><div className="panel-title">Input investimento</div></div>
            <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {[
                ['Importo investimento', '3.5 M€'],
                ['Cash flow annuale atteso', '820 k€'],
                ['Durata', '8 anni'],
                ['WACC', '6.2%'],
                ['Valore terminale', '1.2 M€']
              ].map(([l, v]) => (
                <div key={l} style={{ display: 'flex', justifyContent: 'space-between', paddingBottom: 8, borderBottom: '1px solid var(--border)' }}>
                  <span style={{ fontSize: 12, color: 'var(--ink-2)' }}>{l}</span>
                  <span className="mono" style={{ fontSize: 12, fontWeight: 500 }}>{v}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="panel">
            <div className="panel-head"><div className="panel-title">Risultati</div></div>
            <div className="panel-body" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
              {[
                ['Payback', '5.2 anni'], ['IRR', '11.4%'], ['NPV', '+1.82 M€']
              ].map(([l, v]) => (
                <div key={l}>
                  <div style={{ fontFamily: 'var(--f-mono)', fontSize: 9, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{l}</div>
                  <div className="mono" style={{ fontSize: 22, fontWeight: 500 }}>{v}</div>
                </div>
              ))}
            </div>
            <div className="panel-head" style={{ borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)' }}>
              <div className="panel-title">Sensitivity · NPV (M€)</div>
            </div>
            <table className="data">
              <thead>
                <tr><th>CF atteso \ WACC</th><th className="n">5.0%</th><th className="n">6.2%</th><th className="n">7.5%</th><th className="n">9.0%</th></tr>
              </thead>
              <tbody>
                <tr><td>700 k€</td><td className="n">0.88</td><td className="n">0.24</td><td className="n">−0.40</td><td className="n" style={{ color: 'var(--red)' }}>−1.08</td></tr>
                <tr><td>820 k€</td><td className="n" style={{ color: 'var(--green)', fontWeight: 500 }}>2.62</td><td className="n" style={{ fontWeight: 500 }}>1.82</td><td className="n">1.04</td><td className="n">0.22</td></tr>
                <tr><td>950 k€</td><td className="n" style={{ color: 'var(--green)' }}>4.50</td><td className="n" style={{ color: 'var(--green)' }}>3.50</td><td className="n">2.58</td><td className="n">1.62</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'stress' && (
        <div className="section">
          <div className="panel">
            <div className="panel-head">
              <div className="panel-title">Monitoraggio covenant bancari</div>
              <div style={{ display: 'flex', gap: 4 }}>
                <span className="chip green">2 OK</span>
                <span className="chip amber">2 Attenzione</span>
                <span className="chip red">2 Sforati</span>
              </div>
            </div>
            <table className="data">
              <thead>
                <tr><th>Covenant</th><th>Società</th><th>Soglia</th><th className="n">Valore</th><th className="n">Margine</th><th>Rating</th></tr>
              </thead>
              <tbody>
                {F.covenants.map((c, i) => (
                  <tr key={i}>
                    <td style={{ fontWeight: 500 }}>{c.name}</td>
                    <td>{c.company}</td>
                    <td className="mono" style={{ color: 'var(--muted)' }}>{c.threshold}</td>
                    <td className="n" style={{ fontWeight: 500 }}>{c.actual}</td>
                    <td className="n" style={{ color: c.status === 'green' ? 'var(--green)' : c.status === 'amber' ? 'var(--amber)' : 'var(--red)' }}>{c.margin}</td>
                    <td><span className={`chip ${c.status}`}>● {c.status === 'green' ? 'OK' : c.status === 'amber' ? 'Attenzione' : 'Sforato'}</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { Forecasting });
