// Dashboard.jsx — painel interativo · AAE BR-319
// SVG puro (sem dependências extras) integrado ao design system existente
const { useState, useMemo } = React;

const CADEIA_META = {
  acai:     { rotulo: 'Açaí',     cor: '#08632D', unidade: 't' },
  castanha: { rotulo: 'Castanha', cor: '#1A573E', unidade: 't' },
  borracha: { rotulo: 'Borracha', cor: '#48836A', unidade: 't' },
  madeira:  { rotulo: 'Madeira',  cor: '#CD5D1C', unidade: 'm³' },
  palmito:  { rotulo: 'Palmito',  cor: '#D79F77', unidade: 't' },
  copaiba:  { rotulo: 'Copaíba', cor: '#0F3D1F', unidade: 't' },
  sorva:    { rotulo: 'Sorva',    cor: '#054229', unidade: 't' },
};

const YEARS = [2021, 2022, 2023, 2024];

function fmtN(n) {
  if (!n || n === 0) return '0';
  if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
  if (n >= 1e3) return (n / 1e3).toFixed(1) + 'k';
  return Math.round(n).toLocaleString('pt-BR');
}

// ---- Gráfico de barras horizontais (SVG) ----
function HBarChart({ data, unit, color, onHover, hoveredNome, onClickMun }) {
  const PAD_L = 108, PAD_R = 72, ROW_H = 32, BAR_H = 18;
  const W = 500;
  const svgH = data.length * ROW_H + 12;
  const max = Math.max(...data.map(d => d.value), 1);

  return (
    <svg viewBox={`0 0 ${W} ${svgH}`} width="100%" style={{ overflow: 'visible', display: 'block' }}>
      {data.map((d, i) => {
        const y = i * ROW_H + 6;
        const barW = Math.max(3, (d.value / max) * (W - PAD_L - PAD_R));
        const hot = hoveredNome === d.nome;

        return (
          <g key={d.nome}
            onMouseEnter={() => onHover(d.nome)}
            onMouseLeave={() => onHover(null)}
            onClick={() => onClickMun(d.nome)}
            style={{ cursor: 'pointer' }}
          >
            {/* UF pill */}
            <rect x={0} y={y + 2} width={26} height={16} rx={3}
              fill={hot ? 'var(--g0)' : 'var(--bg2)'}
              stroke={hot ? 'var(--g0)' : 'var(--border)'}
            />
            <text x={13} y={y + 14} fontSize={9} textAnchor="middle"
              fill={hot ? '#fff' : 'var(--t3)'}
              fontFamily="var(--font-mono)" fontWeight={600}
            >{d.uf}</text>

            {/* Nome do município */}
            <text x={PAD_L - 8} y={y + 13}
              fontSize={11} textAnchor="end"
              fill={hot ? 'var(--g0)' : 'var(--t2)'}
              fontWeight={hot ? 600 : 400}
              fontFamily="var(--font-body)"
            >{d.nome.length > 14 ? d.nome.slice(0, 13) + '…' : d.nome}</text>

            {/* Track */}
            <rect x={PAD_L} y={y} width={W - PAD_L - PAD_R} height={BAR_H} rx={3}
              fill="var(--bg2)" stroke="var(--border)" strokeWidth={0.5}
            />
            {/* Fill */}
            <rect x={PAD_L} y={y} width={barW} height={BAR_H} rx={3}
              fill={hot ? 'var(--g0)' : color}
              opacity={hot ? 1 : Math.max(0.5, 1 - i * 0.055)}
            />
            {/* Rank badge top-3 */}
            {i < 3 && barW > 22 && (
              <text x={PAD_L + barW - 10} y={y + 13} fontSize={9}
                fill="#fff" fontWeight={700} textAnchor="middle"
                fontFamily="var(--font-display)"
              >{i + 1}°</text>
            )}
            {/* Valor */}
            <text x={PAD_L + barW + 7} y={y + 13}
              fontSize={10}
              fill={hot ? 'var(--g0)' : 'var(--t3)'}
              fontFamily="var(--font-mono)"
              fontWeight={hot ? 600 : 400}
            >{fmtN(d.value)} {unit}</text>
          </g>
        );
      })}
    </svg>
  );
}

// ---- Gráfico de linhas/área (SVG) ----
function TrendChart({ trendData, activeCadeias }) {
  const [hovered, setHovered] = useState(null);
  const W = 500, H = 190;
  const PAD = { top: 12, right: 16, bottom: 28, left: 52 };
  const iW = W - PAD.left - PAD.right;
  const iH = H - PAD.top - PAD.bottom;

  const allV = trendData.flatMap(d => activeCadeias.map(k => d[k] || 0));
  const maxV = Math.max(...allV, 1);

  const px = i => PAD.left + (i / (YEARS.length - 1)) * iW;
  const py = v => PAD.top + iH - (v / maxV) * iH;

  const linePath = key =>
    trendData.map((d, i) => `${i === 0 ? 'M' : 'L'}${px(i)},${py(d[key] || 0)}`).join(' ');

  const areaPath = key =>
    `${linePath(key)} L${px(trendData.length - 1)},${PAD.top + iH} L${px(0)},${PAD.top + iH} Z`;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ overflow: 'visible', display: 'block' }}>
      {/* Grid horizontal */}
      {[0.25, 0.5, 0.75, 1].map(t => (
        <line key={t}
          x1={PAD.left} x2={W - PAD.right}
          y1={PAD.top + iH * (1 - t)} y2={PAD.top + iH * (1 - t)}
          stroke="var(--border)" strokeWidth={0.5} strokeDasharray="3,3"
        />
      ))}

      {/* Eixo X — anos */}
      {YEARS.map((y, i) => (
        <text key={y} x={px(i)} y={H - 4} textAnchor="middle"
          fontSize={10} fill="var(--t3)" fontFamily="var(--font-mono)"
        >{y}</text>
      ))}

      {/* Eixo Y */}
      {[0, 0.5, 1].map(t => (
        <text key={t}
          x={PAD.left - 6} y={PAD.top + iH * (1 - t) + 4}
          textAnchor="end" fontSize={9}
          fill="var(--t4)" fontFamily="var(--font-mono)"
        >{fmtN(maxV * t)}</text>
      ))}

      {/* Áreas (fundo, baixa opacidade) */}
      {activeCadeias.map(k => (
        <path key={'a' + k} d={areaPath(k)}
          fill={CADEIA_META[k]?.cor || '#08632D'} opacity={0.08}
        />
      ))}

      {/* Linhas */}
      {activeCadeias.map(k => (
        <path key={'l' + k} d={linePath(k)}
          fill="none"
          stroke={CADEIA_META[k]?.cor || '#08632D'}
          strokeWidth={hovered === k ? 2.8 : 1.8}
          strokeLinecap="round" strokeLinejoin="round"
          style={{ cursor: 'pointer', transition: 'stroke-width 0.15s' }}
          onMouseEnter={() => setHovered(k)}
          onMouseLeave={() => setHovered(null)}
        />
      ))}

      {/* Pontos */}
      {activeCadeias.map(k =>
        trendData.map((d, i) => (
          <circle key={k + i}
            cx={px(i)} cy={py(d[k] || 0)}
            r={hovered === k ? 4.5 : 3}
            fill={CADEIA_META[k]?.cor || '#08632D'}
            stroke="#fff" strokeWidth={1}
            style={{ transition: 'r 0.15s' }}
          />
        ))
      )}

      {/* Tooltip da linha hovered */}
      {hovered && (() => {
        const meta = CADEIA_META[hovered];
        const last = trendData[trendData.length - 1];
        const val = last?.[hovered] || 0;
        return (
          <text
            x={px(trendData.length - 1) + 8}
            y={py(val) + 4}
            fontSize={10} fill={meta?.cor}
            fontFamily="var(--font-mono)" fontWeight={600}
          >{meta?.rotulo}: {fmtN(val)}</text>
        );
      })()}
    </svg>
  );
}

// ---- Dashboard principal ----
function Dashboard({ data, year, onSelectMun }) {
  const [rankChain, setRankChain] = useState('acai');
  const [hoveredMun, setHoveredMun] = useState(null);
  const [activeCadeias, setActiveCadeias] = useState(['acai', 'castanha', 'borracha']);

  const cadeiaOpts = Object.entries(CADEIA_META).map(([id, m]) => ({ id, ...m }));

  const rankingData = useMemo(() =>
    [...data.municipios]
      .map(m => ({
        nome: m.nome,
        uf: m.uf,
        regiao: m.regiao,
        value: Number(m.pevs[year]?.[rankChain]) || 0,
      }))
      .filter(d => d.value > 0)
      .sort((a, b) => b.value - a.value)
      .slice(0, 10),
    [data, year, rankChain]
  );

  const trendData = useMemo(() =>
    YEARS.map(y => {
      const row = { year: y };
      Object.keys(CADEIA_META).forEach(k => {
        row[k] = data.municipios.reduce((s, m) => s + (Number(m.pevs[y]?.[k]) || 0), 0);
      });
      return row;
    }),
    [data]
  );

  const toggleCadeia = id =>
    setActiveCadeias(prev =>
      prev.includes(id)
        ? prev.length > 1 ? prev.filter(c => c !== id) : prev
        : [...prev, id]
    );

  const chain = CADEIA_META[rankChain];

  return (
    <section className="dash-section">
      <div className="section-head">
        <span className="panel-tag">00 · painel</span>
        <h2>Visão geral · {year}</h2>
        <p className="section-lede">
          Ranking municipal por cadeia produtiva e evolução 2021–2024.
          Clique numa barra para abrir o detalhe do município no painel lateral.
        </p>
      </div>
      <div className="dash-grid">

        {/* Ranking */}
        <div className="dash-card">
          <div className="dash-card-head">
            <div>
              <div className="dash-card-title">Ranking municipal</div>
              <div className="dash-card-sub">Top 10 produtores · {year}</div>
            </div>
            <select className="select" value={rankChain}
              onChange={e => setRankChain(e.target.value)}>
              {cadeiaOpts.map(c => (
                <option key={c.id} value={c.id}>{c.rotulo} ({c.unidade})</option>
              ))}
            </select>
          </div>
          {rankingData.length === 0
            ? <div className="dash-empty">Sem produção registrada para {chain?.rotulo} em {year}.</div>
            : <HBarChart
                data={rankingData}
                unit={chain?.unidade}
                color={chain?.cor}
                onHover={setHoveredMun}
                hoveredNome={hoveredMun}
                onClickMun={onSelectMun}
              />
          }
        </div>

        {/* Tendência */}
        <div className="dash-card">
          <div className="dash-card-head">
            <div>
              <div className="dash-card-title">Evolução temporal 2021–2024</div>
              <div className="dash-card-sub">Total da área de influência · IBGE/PEVS</div>
            </div>
          </div>
          <div className="cadeia-toggles">
            {cadeiaOpts.map(c => (
              <button key={c.id}
                className={'cadeia-toggle ' + (activeCadeias.includes(c.id) ? 'on' : '')}
                onClick={() => toggleCadeia(c.id)}
                title={activeCadeias.includes(c.id) ? 'Ocultar' : 'Mostrar'}
              >
                <span className="ct-dot"
                  style={{ background: activeCadeias.includes(c.id) ? c.cor : 'var(--border)' }}
                />
                {c.rotulo}
              </button>
            ))}
          </div>
          <TrendChart trendData={trendData} activeCadeias={activeCadeias} />
        </div>

      </div>
    </section>
  );
}

window.Dashboard = Dashboard;
window.CADEIA_META = CADEIA_META;
