// Company detail view

// Forecast chart with confidence band
const ForecastChart = ({ history, forecast, w = 680, h = 220 }) => {
  const all = [...history.map(h => ({ ...h, type: 'actual' })), ...forecast.map(f => ({ ...f, type: 'forecast' }))];
  const padL = 32, padR = 16, padT = 12, padB = 24;
  const cw = w - padL - padR, ch = h - padT - padB;
  const vals = [...history.map(h => h.actual), ...forecast.map(f => f.upper)];
  const min = 0, max = Math.max(...vals) * 1.1;
  const step = cw / (all.length - 1);
  const y = v => padT + ch - ((v - min) / (max - min)) * ch;
  const x = i => padL + i * step;

  // Confidence band
  const splitIdx = history.length;
  const bandUpper = forecast.map((f, i) => [x(splitIdx + i), y(f.upper)]);
  const bandLower = forecast.map((f, i) => [x(splitIdx + i), y(f.lower)]);
  // Connect to last actual point
  const lastActual = history[history.length - 1].actual;
  const connectX = x(splitIdx - 1), connectY = y(lastActual);
  const bandD = `M${connectX},${connectY} ` +
    bandUpper.map(p => `L${p[0]},${p[1]}`).join(' ') +
    ' ' +
    bandLower.slice().reverse().map(p => `L${p[0]},${p[1]}`).join(' ') +
    ` L${connectX},${connectY} Z`;

  const actualLine = 'M' + history.map((d, i) => `${x(i)},${y(d.actual)}`).join(' L');
  const forecastLine = `M${connectX},${connectY} ` + forecast.map((d, i) => `L${x(splitIdx + i)},${y(d.forecast)}`).join(' ');

  const yTicks = [0, max * 0.25, max * 0.5, max * 0.75, max].map(v => Math.round(v * 10) / 10);

  return (
    <svg width={w} height={h}>
      {yTicks.map((t, i) => (
        <g key={i}>
          <line x1={padL} x2={w - padR} y1={y(t)} y2={y(t)} className="grid-line" />
          <text x={padL - 6} y={y(t) + 3} textAnchor="end" className="axis-label">{t}</text>
        </g>
      ))}
      <path d={bandD} fill="var(--accent)" opacity="0.12" />
      <path d={actualLine} fill="none" stroke="var(--ink)" strokeWidth="1.5" />
      <path d={forecastLine} fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeDasharray="3 3" />
      {history.map((d, i) => (
        <circle key={i} cx={x(i)} cy={y(d.actual)} r="2" fill="var(--ink)" />
      ))}
      <line x1={connectX} x2={connectX} y1={padT} y2={padT + ch} stroke="var(--border-strong)" strokeDasharray="2 3" strokeWidth="1" />
      <text x={connectX + 4} y={padT + 10} className="axis-label" style={{ fill: 'var(--accent)' }}>previsione</text>
      {all.map((d, i) => i % 2 === 0 && (
        <text key={i} x={x(i)} y={h - 6} textAnchor="middle" className="axis-label">{d.month}</text>
      ))}
      <line x1={padL} x2={padL} y1={padT} y2={padT + ch} className="axis-line" />
      <line x1={padL} x2={w - padR} y1={padT + ch} y2={padT + ch} className="axis-line" />
    </svg>
  );
};

// Revenue bar chart
const RevenueBars = ({ data, w = 340, h = 180 }) => {
  const padL = 28, padR = 8, padT = 8, padB = 22;
  const cw = w - padL - padR, ch = h - padT - padB;
  const max = Math.max(...data.map(d => Math.max(d.actual, d.budget))) * 1.1;
  const bw = cw / data.length * 0.6;
  const step = cw / data.length;
  const y = v => padT + ch - (v / max) * ch;
  return (
    <svg width={w} height={h}>
      {[0, 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(0)}</text>
        </g>
      ))}
      {data.map((d, i) => {
        const cx = padL + i * step + step/2;
        return (
          <g key={i}>
            <rect x={cx - bw/2} y={y(d.budget)} width={bw/2 - 1} height={ch - (y(d.budget) - padT)} fill="var(--surface-3)" />
            <rect x={cx + 1} y={y(d.actual)} width={bw/2 - 1} height={ch - (y(d.actual) - padT)} fill="var(--ink)" />
            {i % 2 === 0 && <text x={cx} y={h - 6} textAnchor="middle" className="axis-label">{d.month}</text>}
          </g>
        );
      })}
    </svg>
  );
};

const CompanyDetail = ({ company, onBack }) => {
  const [tab, setTab] = React.useState('panoramica');
  const D = window.REGULA_DATA;
  // Use MetalTech detail data as the canonical detail view (demo)
  const det = D.metaltech;
  // Context-aware KPIs
  const contextKPIs = {
    metaltech: [
      { label: "Ricavo medio mensile", value: "4.02 M€", delta: "+6.3%" },
      { label: "Margine EBITDA", value: "14.8%", delta: "+0.9 p.p." },
      { label: "DSO", value: "62 gg", delta: "−4 gg" },
      { label: "PFN / EBITDA", value: "1.82×", delta: "−0.14×" }
    ],
    aquaworld: [
      { label: "Ricavo per visitatore", value: "28.40 €", delta: "+4.2%" },
      { label: "Visitatori YTD", value: "654.900", delta: "+6.8%" },
      { label: "Occupazione media", value: "68%", delta: "+3 p.p." },
      { label: "DSCR", value: "1.24×", delta: "−0.08×", bad: true }
    ],
    lumiere: [
      { label: "Ricavo per serata", value: "12.8 k€", delta: "−8.1%", bad: true },
      { label: "Presenze medie", value: "412", delta: "−11%", bad: true },
      { label: "Scontrino medio", value: "31.10 €", delta: "+2.4%" },
      { label: "Serate aperte", value: "138", delta: "+4" }
    ],
    fondazione: [
      { label: "Copertura da donazioni", value: "108%", delta: "+6 p.p." },
      { label: "Donatori attivi", value: "1.284", delta: "+14%" },
      { label: "Visitatori mostre", value: "42.100", delta: "+9%" },
      { label: "Rapporto costi / entrate", value: "0.94", delta: "−0.04" }
    ]
  };
  const kpis = contextKPIs[company.id] || contextKPIs.metaltech;

  return (
    <div className="page">
      <div style={{ fontSize: 11, color: 'var(--muted)', fontFamily: 'var(--f-mono)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 10, cursor: 'pointer' }} onClick={onBack}>
        ← Dashboard gruppo
      </div>

      <div className="page-header" style={{ alignItems: 'flex-start' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div className="company-logo" style={{ width: 48, height: 48, borderRadius: 10, background: company.color + '15', color: company.color, border: `1px solid ${company.color}30`, fontSize: 16 }}>{company.short}</div>
          <div>
            <h1 className="page-title">{company.name}</h1>
            <div className="page-subtitle">
              {company.sectorTag} · P.IVA {company.pivat} · {company.headquarter} · {company.employees} dipendenti
            </div>
            <div style={{ marginTop: 8, display: 'flex', gap: 6 }}>
              <span className={`chip ${company.status === 'green' ? 'green' : company.status === 'amber' ? 'amber' : 'red'}`}>
                ● {company.statusNote}
              </span>
              <span className="chip">Controllata 100%</span>
              <span className="chip">Consolidamento integrale</span>
            </div>
          </div>
        </div>
        <div className="page-meta">
          <button className="pill-select">Apr 2026 — YTD <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} /> Chiedi a Regula</button>
        </div>
      </div>

      <div className="tabs">
        {['Panoramica', 'Economico', 'Finanziario', 'KPI', 'Documenti', 'Normative'].map(t => {
          const k = t.toLowerCase();
          return (
            <div key={t} className={`tab ${tab === k ? 'active' : ''}`} onClick={() => setTab(k)}>
              {t}
              {t === 'Documenti' && <span className="tab-count">18</span>}
              {t === 'Normative' && <span className="tab-count">7</span>}
            </div>
          );
        })}
      </div>

      {tab === 'panoramica' && (
        <>
          <div className="section">
            <div className="kpi-hero-grid">
              <KpiHero label="Fatturato YTD" value={company.fatturato.value} unit="M€" delta={company.fatturato.delta} deltaAbs="" spark={company.spark} />
              <KpiHero label="Margine" value={company.margine.value} unit="%" delta={company.margine.delta} deltaAbs="" spark={[10, 11, 12, 13, 13.5, 14, 14.2, 14.5, company.margine.value]} />
              <KpiHero label="Cash position" value={company.cash.value} unit="M€" delta={company.cash.delta} deltaAbs="" spark={[14, 13.5, 13, 13.2, 12.9, 12.6, 12.5, 12.4, company.cash.value]} />
              <KpiHero label="PFN" value={38.2} unit="M€" delta={-3.2} deltaAbs="−1.3 M€" spark={[42, 41.5, 41, 40.5, 40, 39.5, 39, 38.5, 38.2]} invert={true} />
            </div>
          </div>

          <div className="section cols-3-2">
            <div className="panel">
              <div className="panel-head">
                <div className="panel-title">Conto economico riclassificato</div>
                <span className="chip">Apr 2026 YTD · M€</span>
              </div>
              <table className="data">
                <thead>
                  <tr>
                    <th style={{ width: '40%' }}>Voce</th>
                    <th className="n" style={{ textAlign: 'right' }}>Actual</th>
                    <th className="n" style={{ textAlign: 'right' }}>Budget</th>
                    <th className="n" style={{ textAlign: 'right' }}>Prev.</th>
                    <th className="n" style={{ textAlign: 'right' }}>Δ vs Bdg</th>
                  </tr>
                </thead>
                <tbody>
                  {det.conto.map((row, i) => {
                    const delta = ((row.actual - row.budget) / Math.abs(row.budget)) * 100;
                    return (
                      <tr key={i} className={row.total ? 'total-row' : ''} style={row.bold ? { fontWeight: 600 } : {}}>
                        <td>{row.label}</td>
                        <td className="n">{row.actual > 0 ? '' : '−'}{Math.abs(row.actual).toFixed(1)}</td>
                        <td className="n" style={{ color: 'var(--muted)' }}>{row.budget > 0 ? '' : '−'}{Math.abs(row.budget).toFixed(1)}</td>
                        <td className="n" style={{ color: 'var(--muted)' }}>{row.prev > 0 ? '' : '−'}{Math.abs(row.prev).toFixed(1)}</td>
                        <td className="n" style={{ color: delta > 0 ? 'var(--green)' : delta < 0 ? 'var(--red)' : 'var(--muted)' }}>
                          {delta > 0 ? '+' : ''}{delta.toFixed(1)}%
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div className="panel">
                <div className="panel-head">
                  <div className="panel-title">Ricavi mensili · actual vs budget</div>
                </div>
                <div className="panel-body">
                  <RevenueBars data={det.history} />
                  <div style={{ display: 'flex', gap: 14, marginTop: 6, fontFamily: 'var(--f-mono)', fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                    <span><span style={{ display: 'inline-block', width: 8, height: 8, background: 'var(--surface-3)', marginRight: 5 }} />Budget</span>
                    <span><span style={{ display: 'inline-block', width: 8, height: 8, background: 'var(--ink)', marginRight: 5 }} />Actual</span>
                  </div>
                </div>
              </div>

              <div className="panel">
                <div className="panel-head">
                  <div className="panel-title">Stato patrimoniale sintetico</div>
                </div>
                <div className="panel-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
                  <div>
                    <div style={{ fontFamily: 'var(--f-mono)', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--muted)', marginBottom: 8 }}>Attivo</div>
                    {[
                      ['Immobilizzazioni', 58.4],
                      ['Rimanenze', 12.1],
                      ['Crediti', 14.8],
                      ['Liquidità', 12.4]
                    ].map(([l, v]) => (
                      <div key={l} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '4px 0', borderBottom: '1px solid var(--border)' }}>
                        <span style={{ color: 'var(--ink-2)' }}>{l}</span>
                        <span className="mono">{v.toFixed(1)}</span>
                      </div>
                    ))}
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '6px 0', fontWeight: 600 }}>
                      <span>Totale</span><span className="mono">97.7</span>
                    </div>
                  </div>
                  <div>
                    <div style={{ fontFamily: 'var(--f-mono)', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--muted)', marginBottom: 8 }}>Passivo</div>
                    {[
                      ['Patrimonio netto', 42.1],
                      ['Debito M/L termine', 32.0],
                      ['Debito B/T', 6.2],
                      ['Altri debiti', 17.4]
                    ].map(([l, v]) => (
                      <div key={l} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '4px 0', borderBottom: '1px solid var(--border)' }}>
                        <span style={{ color: 'var(--ink-2)' }}>{l}</span>
                        <span className="mono">{v.toFixed(1)}</span>
                      </div>
                    ))}
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '6px 0', fontWeight: 600 }}>
                      <span>Totale</span><span className="mono">97.7</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="section">
            <div className="panel">
              <div className="panel-head">
                <div>
                  <div className="panel-title">Forecast ricavi · 12 mesi</div>
                </div>
                <div style={{ display: 'flex', gap: 14, fontFamily: 'var(--f-mono)', fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                  <span><span style={{ display: 'inline-block', width: 12, height: 2, background: 'var(--ink)', marginRight: 5, verticalAlign: 'middle' }} />Actual</span>
                  <span><span style={{ display: 'inline-block', width: 12, height: 2, background: 'var(--accent)', marginRight: 5, verticalAlign: 'middle' }} />Forecast</span>
                  <span><span style={{ display: 'inline-block', width: 12, height: 6, background: 'var(--accent)', opacity: 0.15, marginRight: 5, verticalAlign: 'middle' }} />Banda 80%</span>
                </div>
              </div>
              <div className="panel-body">
                <ForecastChart history={det.history} forecast={det.forecast} w={940} h={240} />
              </div>
            </div>
          </div>

          <div className="section">
            <div className="section-head">
              <div>
                <div className="section-title">KPI contestuali — {company.sector}</div>
                <div className="section-sub">Drag & drop per riordinare · Aggiungi KPI con formula custom</div>
              </div>
              <button className="btn"><Icon name="plus" size={12} /> Nuovo KPI</button>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
              {kpis.map((kpi, i) => (
                <div key={i} className="kpi-tile">
                  <div className="drag-handle"><Icon name="drag" size={10} /></div>
                  <div style={{ fontFamily: 'var(--f-mono)', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--muted)', marginBottom: 6 }}>{kpi.label}</div>
                  <div style={{ fontFamily: 'var(--f-mono)', fontSize: 20, fontWeight: 500, letterSpacing: '-0.01em' }}>{kpi.value}</div>
                  <div style={{ fontFamily: 'var(--f-mono)', fontSize: 11, marginTop: 4, color: kpi.bad ? 'var(--red)' : 'var(--green)' }}>{kpi.delta}</div>
                </div>
              ))}
              <div className="kpi-tile add-new" style={{ minHeight: 0 }}>
                <div style={{ textAlign: 'center' }}>
                  <Icon name="plus" size={14} />
                  <div style={{ fontFamily: 'var(--f-mono)', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', marginTop: 4 }}>Aggiungi KPI</div>
                </div>
              </div>
            </div>
          </div>
        </>
      )}

      {tab !== 'panoramica' && (
        <div className="section" style={{ textAlign: 'center', padding: '80px 0', color: 'var(--muted)' }}>
          <div style={{ fontFamily: 'var(--f-mono)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
            Tab "{tab}" — demo
          </div>
          <div style={{ marginTop: 8, fontSize: 13 }}>In questo prototipo la Panoramica è completamente funzionale.</div>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { CompanyDetail });
