// Dashboard di Gruppo

const KpiHero = ({ label, value, unit, delta, deltaAbs, spark, invert }) => (
  <div className="kpi-hero">
    <div className="kpi-hero-label">{label}</div>
    <div className="kpi-hero-value">
      <span>{value.toLocaleString('it-IT', { minimumFractionDigits: 1, maximumFractionDigits: 1 })}</span>
      <span className="unit">{unit}</span>
    </div>
    <div className="kpi-hero-foot">
      <Delta value={delta} abs={deltaAbs} invert={invert} />
      <div className="kpi-hero-spark">
        <Sparkline data={spark} color="var(--ink)" fill={true} />
      </div>
    </div>
  </div>
);

const CompanyCard = ({ c, onClick }) => {
  const revLabel = c.sector === 'Fondazione' ? 'Entrate YTD' : 'Fatturato YTD';
  const marLabel = c.sector === 'Fondazione' ? 'Copertura costi' : 'Margine %';
  return (
    <div className="company-card" onClick={onClick}>
      <div className="company-head">
        <div className="company-logo" style={{ background: c.color + '15', color: c.color, border: `1px solid ${c.color}30` }}>{c.short}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="company-name">{c.name}</div>
          <div className="company-meta">{c.sectorTag}</div>
        </div>
        <div className="company-status">
          <span className={`status-dot ${c.status}`} />
          <span className="status-label">{c.status === 'green' ? 'OK' : c.status === 'amber' ? 'Attenz.' : 'Critico'}</span>
        </div>
      </div>
      <div className="company-kpis">
        <div>
          <div className="mini-kpi-label">{revLabel}</div>
          <div className="mini-kpi-value">{c.fatturato.value.toFixed(1)} M€</div>
          <div className="mini-kpi-delta" style={{ color: c.fatturato.delta > 0 ? 'var(--green)' : 'var(--red)' }}>
            {c.fatturato.delta > 0 ? '+' : ''}{c.fatturato.delta.toFixed(1)}%
          </div>
        </div>
        <div>
          <div className="mini-kpi-label">{marLabel}</div>
          <div className="mini-kpi-value">{c.margine.value.toFixed(1)}%</div>
          <div className="mini-kpi-delta" style={{ color: c.margine.delta > 0 ? 'var(--green)' : 'var(--red)' }}>
            {c.margine.delta > 0 ? '+' : ''}{c.margine.delta.toFixed(1)} p.p.
          </div>
        </div>
        <div>
          <div className="mini-kpi-label">Cash position</div>
          <div className="mini-kpi-value">{c.cash.value.toFixed(1)} M€</div>
          <div className="mini-kpi-delta" style={{ color: c.cash.delta > 0 ? 'var(--green)' : 'var(--red)' }}>
            {c.cash.delta > 0 ? '+' : ''}{c.cash.delta.toFixed(1)}%
          </div>
        </div>
        <div>
          <Sparkline data={c.spark} color={c.color} w={68} h={32} fill={true} />
        </div>
      </div>
    </div>
  );
};

// Treemap (sector allocation, hand-computed squarified-ish layout)
const Treemap = ({ data }) => {
  // Simple row-based layout
  const total = data.reduce((s, d) => s + d.value, 0);
  // Row 1: first 2 items (large), Row 2: rest
  const [a, b, c, d] = data;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '52% 48%', gridTemplateRows: '64% 36%', gap: 3, height: 240 }}>
      <div className="treemap-cell" style={{ gridRow: '1 / 3', background: a.color, color: 'white' }}>
        <div>
          <div className="tm-label">{a.label}</div>
          <div className="tm-pct">{a.pct}%</div>
        </div>
        <div className="tm-value">{a.value.toFixed(1)} M€</div>
      </div>
      <div className="treemap-cell" style={{ background: b.color, color: 'white' }}>
        <div>
          <div className="tm-label">{b.label}</div>
          <div className="tm-pct">{b.pct}%</div>
        </div>
        <div className="tm-value">{b.value.toFixed(1)} M€</div>
      </div>
      <div className="treemap-cell" style={{ background: c.color, color: 'white' }}>
        <div>
          <div className="tm-label">{c.label}</div>
          <div className="tm-pct">{c.pct}%</div>
        </div>
        <div className="tm-value">{c.value.toFixed(1)}</div>
      </div>
      <div className="treemap-cell" style={{ background: d.color, color: 'var(--ink)' }}>
        <div>
          <div className="tm-label">{d.label}</div>
          <div className="tm-pct">{d.pct}%</div>
        </div>
        <div className="tm-value">{d.value.toFixed(1)}</div>
      </div>
    </div>
  );
};

// Donut / asset class
const AssetDonut = ({ data }) => {
  const total = data.reduce((s, d) => s + d.value, 0);
  const colors = ['#2A3B48', '#5B7A6B', '#A89468', '#C4BFB3'];
  let acc = 0;
  const r = 60, cx = 80, cy = 80;
  const segs = data.map((d, i) => {
    const startAngle = (acc / total) * 2 * Math.PI - Math.PI / 2;
    acc += d.value;
    const endAngle = (acc / total) * 2 * Math.PI - Math.PI / 2;
    const large = endAngle - startAngle > Math.PI ? 1 : 0;
    const x1 = cx + r * Math.cos(startAngle), y1 = cy + r * Math.sin(startAngle);
    const x2 = cx + r * Math.cos(endAngle), y2 = cy + r * Math.sin(endAngle);
    return { d: `M${cx},${cy} L${x1},${y1} A${r},${r} 0 ${large} 1 ${x2},${y2} Z`, color: colors[i] };
  });
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
      <svg width="160" height="160" style={{ flex: 'none' }}>
        {segs.map((s, i) => <path key={i} d={s.d} fill={s.color} stroke="white" strokeWidth="1.5" />)}
        <circle cx={cx} cy={cy} r="36" fill="white" />
        <text x={cx} y={cy - 4} textAnchor="middle" className="mono" style={{ fontSize: 18, fontWeight: 500, fill: 'var(--ink)' }}>{total.toFixed(0)}</text>
        <text x={cx} y={cy + 12} textAnchor="middle" className="axis-label">M€ totale</text>
      </svg>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 7 }}>
        {data.map((d, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
            <div style={{ width: 8, height: 8, background: colors[i], borderRadius: 2, flex: 'none' }} />
            <span style={{ flex: 1 }}>{d.label}</span>
            <span className="mono" style={{ color: 'var(--muted)', fontSize: 11 }}>{d.pct}%</span>
            <span className="mono" style={{ fontWeight: 500 }}>{d.value.toFixed(1)}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

const AlertsList = ({ alerts }) => (
  <div>
    {alerts.map((a, i) => (
      <div key={i} className="alert-row">
        <span className={`alert-severity sev-${a.severity}`}>
          {a.severity === 'critical' ? 'Critico' : a.severity === 'warning' ? 'Avviso' : 'Info'}
        </span>
        <span className="alert-text">{a.text}</span>
        <span className="alert-company">{a.company}</span>
        <span className="alert-date">
          {a.date}
          {a.days !== null && a.days !== undefined && <span style={{ marginLeft: 6, opacity: 0.7 }}>· {a.days}gg</span>}
        </span>
      </div>
    ))}
  </div>
);

const Dashboard = ({ onCompanyClick, horizon = 'tattico' }) => {
  const D = window.REGULA_DATA;
  const k = D.group.kpis;

  // Horizon-aware configuration
  const horizonConfig = {
    operativo: {
      subtitle: 'Vista operativa · settimana corrente · 4 società · refresh 14:22',
      periodLabel: 'Settimana 17 · 2026',
      compareLabel: 'vs. sett. precedente',
      briefLabel: 'Brief giornaliero',
      kpis: [
        { ...k.liquidita, label: 'Liquidità disponibile' },
        { label: 'Pagamenti prossimi 7gg', value: 3.24, unit: 'M€', delta: -1.2, deltaAbs: '−0.1 M€', spark: [2.8, 3.0, 3.1, 3.2, 3.1, 3.25, 3.24] },
        { label: 'Incassi attesi 7gg', value: 2.98, unit: 'M€', delta: 4.8, deltaAbs: '+0.14 M€', spark: [2.4, 2.5, 2.7, 2.8, 2.85, 2.9, 2.98] },
        { ...k.debito, label: 'Utilizzo linee B/T', value: 18.4, deltaAbs: '−0.8 M€', spark: [22,21,20,19.5,19,18.6,18.4] }
      ],
      sectionTitle: 'Cash position per società · oggi',
      showForecasts: false
    },
    tattico: {
      subtitle: 'Dashboard consolidata · ' + D.group.period + ' · 4 società · Ultimo refresh 14:22',
      periodLabel: 'Apr 2026 — YTD',
      compareLabel: 'vs. YTD 2025',
      briefLabel: 'Brief AI',
      kpis: [k.patrimonio, k.liquidita, k.ebitda, { ...k.debito }],
      sectionTitle: 'Società del gruppo',
      showForecasts: true
    },
    strategico: {
      subtitle: 'Orizzonte strategico · Piano industriale 2026–2030 · 4 società',
      periodLabel: 'Piano 2026–2030',
      compareLabel: 'vs. piano precedente',
      briefLabel: 'Proiezione piano',
      kpis: [
        { label: 'Patrimonio netto target 2030', value: 418.0, unit: 'M€', delta: 46.9, deltaAbs: '+133 M€', spark: [284, 300, 320, 345, 370, 395, 418] },
        { label: 'EBITDA target 2030', value: 58.6, unit: 'M€', delta: 52.6, deltaAbs: '+20.2 M€', spark: [38, 42, 46, 50, 53, 56, 58.6] },
        { label: 'Capex cumulato 5y', value: 142.0, unit: 'M€', delta: 0, deltaAbs: 'pianificato', spark: [0, 24, 52, 82, 108, 128, 142] },
        { label: 'IRR medio progetti', value: 11.8, unit: '%', delta: 1.8, deltaAbs: 'vs hurdle 10%', spark: [9, 9.5, 10.2, 10.8, 11.2, 11.5, 11.8] }
      ],
      sectionTitle: 'Società · traiettoria al 2030',
      showForecasts: true
    }
  };
  const H = horizonConfig[horizon] || horizonConfig.tattico;

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">{D.group.name}</h1>
          <div className="page-subtitle">{H.subtitle}</div>
        </div>
        <div className="page-meta">
          <button className="pill-select">{H.periodLabel} <Icon name="down" size={10} /></button>
          <button className="pill-select">{H.compareLabel} <Icon name="down" size={10} /></button>
          <button className="btn"><Icon name="download" size={12} /> Export</button>
          <button className="btn btn-primary"><Icon name="sparkle" size={12} /> {H.briefLabel}</button>
        </div>
      </div>

      <div className="kpi-hero-grid">
        {H.kpis.map((kpi, i) => <KpiHero key={i} {...kpi} invert={i === 3 && horizon === 'tattico'} />)}
      </div>

      <div className="section">
        <div className="section-head">
          <div>
            <div className="section-title">{H.sectionTitle}</div>
            <div className="section-sub">4 società · click per drill-down · orizzonte <strong>{horizon}</strong></div>
          </div>
          <div className="section-actions">
            <button className="btn"><Icon name="filter" size={12} /> Filtra</button>
            <button className="btn"><Icon name="plus" size={12} /> Aggiungi</button>
          </div>
        </div>
        <div className="company-grid">
          {D.companies.map(c => <CompanyCard key={c.id} c={c} onClick={() => onCompanyClick(c.id)} />)}
        </div>
      </div>

      <div className="section">
        <div className="cols-2-3">
          <div className="panel">
            <div className="panel-head">
              <div>
                <div className="panel-title">Allocazione per asset class</div>
              </div>
              <span className="chip">284.6 M€</span>
            </div>
            <div className="panel-body">
              <AssetDonut data={D.allocation.byAsset} />
            </div>
          </div>
          <div className="panel">
            <div className="panel-head">
              <div className="panel-title">Allocazione per settore</div>
              <span className="chip">4 settori</span>
            </div>
            <div className="panel-body">
              <Treemap data={D.allocation.bySector} />
            </div>
          </div>
        </div>
      </div>

      <div className="section">
        <div className="panel">
          <div className="panel-head">
            <div>
              <div className="panel-title">
                {horizon === 'operativo' ? 'Alert operativi · oggi e prossimi 7gg' : horizon === 'strategico' ? 'Milestone piano industriale' : 'Alert & Scadenze'}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <span className="chip red">{horizon === 'operativo' ? '1 Urgente' : '2 Critici'}</span>
              <span className="chip amber">3 Avvisi</span>
              <button className="btn">Vedi tutti</button>
            </div>
          </div>
          <AlertsList alerts={horizon === 'operativo' ? D.alerts.filter(a => a.days !== null && a.days <= 30) : D.alerts} />
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Dashboard });
