// site-jogador/js/meta-crowdfunding.jsx
//
// Meta de hardware em TIMELINE incremental (substitui modelo antigo de 3 fases).
// Itens são comprados um por um, com marcos visíveis no caminho.
// current_step_index aponta o item atual da timeline (0-indexed).

function fmtBRL(value) {
  return value.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL', minimumFractionDigits: 0, maximumFractionDigits: 0 });
}

function fmtBRLRange(min, max) {
  if (min === max) return fmtBRL(min);
  return `${fmtBRL(min)} a ${fmtBRL(max)}`;
}

const COLOR = {
  accent:    '#a8ff00',
  completed: '#22c55e',
  current:   '#f59e0b',
  pending:   'rgba(255,255,255,0.3)',
  meta:      '#a855f7',
  danger:    '#ef4444',
};

// ============================================================================
// HOST COMPARISON (situacao atual)
// ============================================================================
function HostComparison({ host, totalMin, totalMax }) {
  const yearsMin = totalMin / host.yearly_cost;
  const yearsMax = totalMax / host.yearly_cost;

  return (
    <div style={{
      background: 'rgba(20,20,20,0.6)',
      border: `1px solid ${COLOR.danger}40`,
      padding: '20px 24px',
      marginBottom: 32,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: COLOR.danger, boxShadow: `0 0 8px ${COLOR.danger}` }} />
        <span style={{ fontFamily: 'Share Tech Mono', fontSize: 10, color: COLOR.danger, letterSpacing: '0.18em' }}>
          SITUAÇÃO ATUAL
        </span>
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
        gap: 20,
        marginBottom: 16,
      }}>
        <HostStat label="HOST ALUGADO" value={fmtBRL(host.monthly_cost)} suffix="/mês" color={COLOR.danger} />
        <HostStat label="CAPACIDADE ATUAL" value={`~${host.max_players}+`} suffix="jogadores" color={COLOR.danger} />
        <HostStat label="CUSTO ANUAL" value={fmtBRL(host.yearly_cost)} color={COLOR.danger} />
        <HostStat label="HARDWARE PAGA EM" value={`~${yearsMin.toFixed(1)} a ${yearsMax.toFixed(1)}`} suffix="anos" color={COLOR.accent} />
      </div>

      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 6 }}>
        {host.limitations.map((l, i) => (
          <li key={i} style={{
            fontFamily: 'Rajdhani', fontWeight: 400,
            fontSize: 12, lineHeight: 1.5,
            color: 'rgba(255,255,255,0.5)',
            paddingLeft: 16, position: 'relative',
          }}>
            <span style={{ position: 'absolute', left: 0, color: COLOR.danger }}>x</span> {l}
          </li>
        ))}
      </ul>
    </div>
  );
}

function HostStat({ label, value, suffix, color }) {
  return (
    <div>
      <div style={{ fontFamily: 'Share Tech Mono', fontSize: 9, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.15em', marginBottom: 4 }}>
        {label}
      </div>
      <div style={{ fontFamily: 'Share Tech Mono', fontSize: 22, color }}>
        {value}
        {suffix && <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.5)', marginLeft: 4 }}>{suffix}</span>}
      </div>
    </div>
  );
}

// ============================================================================
// TIMELINE PROGRESS HEADER (barra superior + indicador do passo atual)
// ============================================================================
function TimelineProgress({ timeline, currentIndex, totalItems, completedItems }) {
  const pct = (completedItems / totalItems) * 100;
  const currentEntry = timeline[currentIndex];
  const itemEntries = timeline.filter(e => e.type === 'item');
  const currentItemNumber = itemEntries.findIndex(e => e.id === (currentEntry?.id)) + 1;

  return (
    <div style={{
      background: 'rgba(28,28,28,0.7)',
      border: '1px solid rgba(255,255,255,0.08)',
      padding: '18px 22px',
      marginBottom: 24,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12, marginBottom: 12 }}>
        <div>
          <div style={{ fontFamily: 'Share Tech Mono', fontSize: 9, color: COLOR.accent, letterSpacing: '0.18em', marginBottom: 4 }}>
            PROGRESSO DA META
          </div>
          <div style={{ fontFamily: 'Rajdhani', fontWeight: 700, fontSize: 18, color: '#fff' }}>
            {currentEntry?.type === 'item' ? (
              <>Adquirindo agora: <span style={{ color: COLOR.current }}>{currentEntry.name}</span></>
            ) : currentIndex >= timeline.length ? (
              <span style={{ color: COLOR.completed }}>Configuração final concluída</span>
            ) : (
              <span style={{ color: COLOR.current }}>Marco em celebração</span>
            )}
          </div>
        </div>
        <div style={{ fontFamily: 'Share Tech Mono', fontSize: 28, color: COLOR.accent, fontWeight: 700 }}>
          {pct.toFixed(0)}%
        </div>
      </div>

      <div style={{
        height: 8,
        background: 'rgba(255,255,255,0.05)',
        position: 'relative',
        overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: 0, left: 0, bottom: 0,
          width: `${pct}%`,
          background: `linear-gradient(90deg, ${COLOR.completed} 0%, ${COLOR.accent} 100%)`,
          boxShadow: `0 0 12px ${COLOR.accent}80`,
          transition: 'width 0.6s ease',
        }} />
      </div>

      <div style={{
        marginTop: 8,
        fontFamily: 'Share Tech Mono', fontSize: 10,
        color: 'rgba(255,255,255,0.4)',
        letterSpacing: '0.1em',
      }}>
        {completedItems} de {totalItems} itens adquiridos
      </div>
    </div>
  );
}

// ============================================================================
// TIMELINE ITEM (card de uma peca)
// ============================================================================
function TimelineItem({ item, status, isLast }) {
  const isCompleted = status === 'completed';
  const isCurrent = status === 'current';
  const accent = isCompleted ? COLOR.completed : isCurrent ? COLOR.current : COLOR.pending;
  const bg = isCompleted ? 'rgba(34,197,94,0.05)' : isCurrent ? 'rgba(245,158,11,0.07)' : 'rgba(28,28,28,0.5)';
  const opacity = isCompleted ? 0.85 : isCurrent ? 1 : 0.55;

  return (
    <div style={{ position: 'relative', display: 'flex', gap: 16, marginBottom: isLast ? 0 : 16 }}>
      {/* Coluna esquerda: badge de status + linha conectora */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
        <div style={{
          width: 36, height: 36,
          borderRadius: '50%',
          background: isCurrent ? accent : 'rgba(28,28,28,0.9)',
          border: `2px solid ${accent}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 18,
          boxShadow: isCurrent ? `0 0 16px ${accent}80` : 'none',
          animation: isCurrent ? 'pulse-step 1.8s ease-in-out infinite' : 'none',
          flexShrink: 0,
        }}>
          {isCompleted ? <span style={{ color: '#000', fontWeight: 700 }}>✓</span> : item.icon}
        </div>
        {!isLast && (
          <div style={{
            width: 2, flex: 1, minHeight: 24,
            marginTop: 4, marginBottom: 4,
            background: isCompleted
              ? `linear-gradient(180deg, ${COLOR.completed} 0%, ${COLOR.completed} 100%)`
              : `repeating-linear-gradient(180deg, ${COLOR.pending} 0, ${COLOR.pending} 4px, transparent 4px, transparent 8px)`,
          }} />
        )}
      </div>

      {/* Card */}
      <div style={{
        flex: 1,
        background: bg,
        border: `1px solid ${isCurrent ? accent : 'rgba(255,255,255,0.06)'}`,
        borderLeft: `3px solid ${accent}`,
        padding: '14px 18px',
        opacity,
        transition: 'opacity 0.3s, border-color 0.3s',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 8, marginBottom: 6 }}>
          <div style={{ minWidth: 200, flex: 1 }}>
            <div style={{ fontFamily: 'Share Tech Mono', fontSize: 9, color: accent, letterSpacing: '0.16em', marginBottom: 2 }}>
              {item.category.toUpperCase()}
              {isCurrent && <span style={{ marginLeft: 8, color: COLOR.current, fontWeight: 700 }}>EM ANDAMENTO</span>}
              {isCompleted && <span style={{ marginLeft: 8, color: COLOR.completed }}>CONCLUÍDO</span>}
            </div>
            <div style={{ fontFamily: 'Rajdhani', fontWeight: 700, fontSize: 17, color: '#fff', lineHeight: 1.2 }}>
              {item.name}
            </div>
          </div>
          <div style={{
            fontFamily: 'Share Tech Mono', fontSize: 14,
            color: accent,
            textAlign: 'right',
            whiteSpace: 'nowrap',
          }}>
            {fmtBRLRange(item.price_min, item.price_max)}
          </div>
        </div>

        <div style={{
          fontFamily: 'Rajdhani', fontWeight: 500, fontSize: 12,
          color: 'rgba(255,255,255,0.45)',
          marginBottom: 6,
          fontStyle: 'italic',
        }}>
          {item.spec}
        </div>

        <div style={{
          fontFamily: 'Rajdhani', fontWeight: 400, fontSize: 13,
          color: 'rgba(255,255,255,0.65)',
          lineHeight: 1.55,
        }}>
          {item.rationale}
        </div>

        {item.url && (
          <a href={item.url} target="_blank" rel="noopener noreferrer" style={{
            display: 'inline-block',
            marginTop: 8,
            fontFamily: 'Share Tech Mono', fontSize: 10,
            color: COLOR.accent, textDecoration: 'none',
            letterSpacing: '0.12em',
            borderBottom: `1px dashed ${COLOR.accent}80`,
          }}>
            VER NA LOJA &rarr;
          </a>
        )}
      </div>
    </div>
  );
}

// ============================================================================
// TIMELINE MILESTONE (marco intermediario)
// ============================================================================
function TimelineMilestone({ milestone, achieved, isLast }) {
  const accent = achieved ? COLOR.completed : COLOR.pending;
  const opacity = achieved ? 1 : 0.6;

  return (
    <div style={{ position: 'relative', display: 'flex', gap: 16, marginBottom: isLast ? 0 : 24, marginTop: 8 }}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
        <div style={{
          width: 36, height: 36,
          background: achieved ? accent : 'transparent',
          border: `2px solid ${accent}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 18,
          transform: 'rotate(45deg)',
          boxShadow: achieved ? `0 0 16px ${accent}80` : 'none',
        }}>
          <span style={{ transform: 'rotate(-45deg)' }}>{milestone.icon}</span>
        </div>
        {!isLast && (
          <div style={{
            width: 2, flex: 1, minHeight: 24,
            marginTop: 4, marginBottom: 4,
            background: achieved
              ? COLOR.completed
              : `repeating-linear-gradient(180deg, ${COLOR.pending} 0, ${COLOR.pending} 4px, transparent 4px, transparent 8px)`,
          }} />
        )}
      </div>

      <div style={{
        flex: 1,
        background: achieved ? `linear-gradient(90deg, ${accent}15 0%, transparent 60%)` : 'transparent',
        border: `1px dashed ${accent}80`,
        padding: '12px 18px',
        opacity,
      }}>
        <div style={{ fontFamily: 'Share Tech Mono', fontSize: 9, color: accent, letterSpacing: '0.18em', marginBottom: 4 }}>
          {achieved ? 'MARCO ATINGIDO' : 'PRÓXIMO MARCO'}
        </div>
        <div style={{ fontFamily: 'Rajdhani', fontWeight: 700, fontSize: 19, color: achieved ? '#fff' : 'rgba(255,255,255,0.7)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 4 }}>
          {milestone.label}
        </div>
        <div style={{ fontFamily: 'Share Tech Mono', fontSize: 11, color: accent, marginBottom: 6, letterSpacing: '0.1em' }}>
          {milestone.players_estimate}
        </div>
        <div style={{ fontFamily: 'Rajdhani', fontSize: 13, color: 'rgba(255,255,255,0.55)', lineHeight: 1.55 }}>
          {milestone.description}
        </div>
      </div>
    </div>
  );
}

// ============================================================================
// TIMELINE (renderizador da lista completa, com modo colapsado)
// ============================================================================
function Timeline({ timeline, currentIndex, collapsed }) {
  if (collapsed) {
    let entry = timeline[currentIndex];
    if (!entry || entry.type !== 'item') {
      entry = timeline.slice(currentIndex).find(e => e.type === 'item')
           || timeline.find(e => e.type === 'item');
    }
    if (!entry) return null;
    return <TimelineItem item={entry} status="current" isLast={true} />;
  }

  return (
    <div>
      {timeline.map((entry, i) => {
        const isLast = i === timeline.length - 1;

        if (entry.type === 'item') {
          const status = i < currentIndex ? 'completed' : i === currentIndex ? 'current' : 'pending';
          return <TimelineItem key={entry.id} item={entry} status={status} isLast={isLast} />;
        }

        if (entry.type === 'milestone') {
          const achieved = i < currentIndex;
          return <TimelineMilestone key={entry.id} milestone={entry} achieved={achieved} isLast={isLast} />;
        }

        return null;
      })}
    </div>
  );
}

// ============================================================================
// TIMELINE TOGGLE (botão expand/collapse bem visível)
// ============================================================================
function TimelineToggle({ expanded, onToggle, totalItems, totalMilestones }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      onClick={onToggle}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        width: '100%',
        background: hover ? `${COLOR.accent}15` : `${COLOR.accent}08`,
        border: `1px solid ${COLOR.accent}${hover ? '70' : '40'}`,
        color: COLOR.accent,
        padding: '16px 20px',
        marginBottom: 24,
        cursor: 'pointer',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: 4,
        transition: 'all 0.2s ease',
        boxShadow: hover ? `0 0 18px ${COLOR.accent}30` : 'none',
        animation: !expanded ? 'toggle-pulse 2.4s ease-in-out infinite' : 'none',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <span style={{
          fontSize: 14,
          transform: expanded ? 'rotate(180deg)' : 'rotate(0)',
          transition: 'transform 0.3s ease',
          display: 'inline-block',
        }}>▼</span>
        <span style={{
          fontFamily: 'Share Tech Mono', fontSize: 12,
          letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 700,
        }}>
          {expanded ? 'Recolher timeline' : 'Ver timeline de andamento'}
        </span>
        <span style={{
          fontSize: 14,
          transform: expanded ? 'rotate(180deg)' : 'rotate(0)',
          transition: 'transform 0.3s ease',
          display: 'inline-block',
        }}>▼</span>
      </div>
      {!expanded && (
        <div style={{
          fontFamily: 'Rajdhani', fontWeight: 400, fontSize: 11,
          color: 'rgba(255,255,255,0.5)', letterSpacing: '0.04em',
        }}>
          {totalItems} itens · {totalMilestones} marco{totalMilestones === 1 ? '' : 's'} no caminho
        </div>
      )}
    </button>
  );
}

// ============================================================================
// FINAL BUILD CARD (configuracao final)
// ============================================================================
function FinalBuildCard({ summary }) {
  return (
    <div style={{
      background: 'rgba(28,28,28,0.85)',
      border: `1px solid ${COLOR.accent}40`,
      borderTop: `3px solid ${COLOR.accent}`,
      padding: '28px 30px',
      marginTop: 32,
      marginBottom: 24,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
        <span style={{ width: 10, height: 10, borderRadius: '50%', background: COLOR.accent, boxShadow: `0 0 10px ${COLOR.accent}` }} />
        <span style={{ fontFamily: 'Share Tech Mono', fontSize: 10, color: COLOR.accent, letterSpacing: '0.18em' }}>
          BUILD FINAL
        </span>
      </div>

      <h3 style={{
        fontFamily: 'Rajdhani', fontWeight: 700, fontSize: 'clamp(22px, 3vw, 30px)',
        color: '#fff', textTransform: 'uppercase',
        marginBottom: 18, letterSpacing: '0.02em',
      }}>
        {summary.headline}
      </h3>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))',
        gap: 12,
      }}>
        {summary.specs.map((s, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '10px 14px',
            background: 'rgba(168,255,0,0.04)',
            border: '1px solid rgba(168,255,0,0.12)',
          }}>
            <span style={{ fontSize: 22 }}>{s.icon}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'Share Tech Mono', fontSize: 9, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.14em' }}>
                {s.label.toUpperCase()}
              </div>
              <div style={{ fontFamily: 'Rajdhani', fontWeight: 600, fontSize: 14, color: '#fff', lineHeight: 1.3 }}>
                {s.value}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================================================
// FUTURE UPGRADES (subseção discreta após o build final)
// ============================================================================
function FutureUpgrades({ data }) {
  return (
    <div style={{
      background: 'rgba(15,15,15,0.5)',
      border: '1px dashed rgba(255,255,255,0.08)',
      padding: '20px 24px',
      marginTop: 24,
      marginBottom: 24,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'rgba(168,255,0,0.5)' }} />
        <span style={{ fontFamily: 'Share Tech Mono', fontSize: 9, color: 'rgba(168,255,0,0.6)', letterSpacing: '0.18em' }}>
          DEPOIS DA META PRINCIPAL
        </span>
      </div>

      <div style={{
        fontFamily: 'Rajdhani', fontWeight: 700, fontSize: 16,
        color: 'rgba(255,255,255,0.85)', textTransform: 'uppercase',
        letterSpacing: '0.04em', marginBottom: 6,
      }}>
        {data.title}
      </div>

      <div style={{
        fontFamily: 'Rajdhani', fontWeight: 400, fontSize: 12,
        color: 'rgba(255,255,255,0.5)', lineHeight: 1.6,
        marginBottom: 14,
      }}>
        {data.intro}
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
        gap: 10,
      }}>
        {data.items.map(it => (
          <div key={it.id} style={{
            display: 'flex',
            gap: 10,
            background: 'rgba(28,28,28,0.4)',
            border: '1px solid rgba(255,255,255,0.04)',
            padding: '10px 12px',
          }}>
            <div style={{
              fontSize: 18, lineHeight: 1, paddingTop: 2,
              opacity: 0.8,
            }}>
              {it.icon}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                display: 'flex', justifyContent: 'space-between',
                alignItems: 'baseline', gap: 6, marginBottom: 2,
              }}>
                <div style={{
                  fontFamily: 'Share Tech Mono', fontSize: 8,
                  color: 'rgba(255,255,255,0.4)', letterSpacing: '0.14em',
                }}>
                  {it.category.toUpperCase()}
                </div>
                <div style={{
                  fontFamily: 'Share Tech Mono', fontSize: 11,
                  color: 'rgba(168,255,0,0.7)', whiteSpace: 'nowrap',
                }}>
                  {fmtBRLRange(it.price_min, it.price_max)}
                </div>
              </div>
              <div style={{
                fontFamily: 'Rajdhani', fontWeight: 600, fontSize: 13,
                color: 'rgba(255,255,255,0.85)', lineHeight: 1.25,
                marginBottom: 4,
              }}>
                {it.name}
              </div>
              <div style={{
                fontFamily: 'Rajdhani', fontWeight: 400, fontSize: 11,
                color: 'rgba(255,255,255,0.5)', lineHeight: 1.5,
              }}>
                {it.rationale}
              </div>
              {it.url && (
                <a href={it.url} target="_blank" rel="noopener noreferrer" style={{
                  display: 'inline-block',
                  marginTop: 6,
                  fontFamily: 'Share Tech Mono', fontSize: 9,
                  color: 'rgba(168,255,0,0.6)', textDecoration: 'none',
                  letterSpacing: '0.12em',
                  borderBottom: '1px dashed rgba(168,255,0,0.3)',
                }}>
                  VER NA LOJA &rarr;
                </a>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================================================
// DISCLAIMERS (3 cards)
// ============================================================================
function Disclaimers({ items }) {
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
      gap: 16,
      marginTop: 24,
      marginBottom: 24,
    }}>
      {items.map(d => (
        <div key={d.id} style={{
          background: 'rgba(20,20,20,0.5)',
          border: '1px solid rgba(255,255,255,0.06)',
          padding: '16px 20px',
        }}>
          <div style={{
            fontFamily: 'Rajdhani', fontWeight: 700, fontSize: 14,
            color: COLOR.accent, textTransform: 'uppercase',
            letterSpacing: '0.04em', marginBottom: 8,
          }}>
            {d.title}
          </div>
          <div style={{
            fontFamily: 'Rajdhani', fontWeight: 400, fontSize: 13,
            color: 'rgba(255,255,255,0.6)', lineHeight: 1.6,
          }}>
            {d.body}
          </div>
        </div>
      ))}
    </div>
  );
}

// ============================================================================
// POST META NOTICE
// ============================================================================
function PostMetaNotice({ notice }) {
  return (
    <div style={{
      background: `linear-gradient(135deg, rgba(168,255,0,0.06) 0%, rgba(28,28,28,0.7) 60%)`,
      border: `1px solid ${COLOR.accent}30`,
      padding: '20px 26px',
      marginTop: 8,
    }}>
      <div style={{
        fontFamily: 'Rajdhani', fontWeight: 700, fontSize: 16,
        color: COLOR.accent, textTransform: 'uppercase',
        letterSpacing: '0.05em', marginBottom: 8,
      }}>
        {notice.title}
      </div>
      <div style={{
        fontFamily: 'Rajdhani', fontWeight: 400, fontSize: 14,
        color: 'rgba(255,255,255,0.7)', lineHeight: 1.65,
      }}>
        {notice.body}
      </div>
    </div>
  );
}

// ============================================================================
// MAIN
// ============================================================================
function MetaCrowdfunding() {
  const [data, setData] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [timelineExpanded, setTimelineExpanded] = React.useState(false);

  React.useEffect(() => {
    const tryPaths = async () => {
      const paths = ['/shared/hardware-goal.json', '../shared/hardware-goal.json', 'shared/hardware-goal.json'];
      for (const p of paths) {
        try {
          const r = await fetch(p);
          if (r.ok) {
            const j = await r.json();
            setData(j);
            return;
          }
        } catch (e) { /* try next */ }
      }
      setError('Falha ao carregar dados da meta. Tente recarregar a página.');
    };
    tryPaths();
  }, []);

  if (error) {
    return (
      <section style={{ padding: '60px 5vw', textAlign: 'center', color: COLOR.danger, fontFamily: 'Rajdhani' }}>
        {error}
      </section>
    );
  }

  if (!data) {
    return (
      <section style={{ padding: '60px 5vw', textAlign: 'center', color: 'rgba(255,255,255,0.4)', fontFamily: 'Share Tech Mono', fontSize: 12, letterSpacing: '0.1em' }}>
        CARREGANDO META
      </section>
    );
  }

  // Calcula totals
  const items = data.timeline.filter(e => e.type === 'item');
  const totalMin = items.reduce((s, i) => s + (i.price_min || 0), 0);
  const totalMax = items.reduce((s, i) => s + (i.price_max || 0), 0);
  const completedItems = items.filter((it, idx) => {
    const arrayIdx = data.timeline.findIndex(e => e.id === it.id);
    return arrayIdx < data.current_step_index;
  }).length;

  return (
    <section style={{
      background: 'rgba(20,20,20,0.85)',
      backdropFilter: 'blur(24px) saturate(1.2)',
      WebkitBackdropFilter: 'blur(24px) saturate(1.2)',
      padding: '80px 5vw',
      borderTop: '1px solid rgba(255,255,255,0.05)',
    }}>
      <style>{`
        @keyframes pulse-step {
          0%, 100% { transform: scale(1); box-shadow: 0 0 16px ${COLOR.current}80; }
          50%      { transform: scale(1.08); box-shadow: 0 0 24px ${COLOR.current}cc; }
        }
        @keyframes toggle-pulse {
          0%, 100% { box-shadow: 0 0 0 0 ${COLOR.accent}40; }
          50%      { box-shadow: 0 0 0 6px ${COLOR.accent}00; }
        }
      `}</style>

      <div style={{ maxWidth: 1100, margin: '0 auto' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <div style={{ width: 24, height: 2, background: COLOR.accent }} />
          <span style={{ fontFamily: 'Share Tech Mono', fontSize: 11, color: COLOR.accent, letterSpacing: '0.18em' }}>
            META DE INFRAESTRUTURA
          </span>
        </div>

        <h2 style={{
          fontFamily: 'Rajdhani', fontWeight: 700,
          fontSize: 'clamp(28px, 4vw, 48px)', lineHeight: 1.1,
          textTransform: 'uppercase', marginBottom: 12,
        }}>
          HARDWARE PRÓPRIO PARA<br />
          <span style={{ color: COLOR.accent }}>50 A 80 JOGADORES</span>
        </h2>

        <p style={{
          color: 'rgba(255,255,255,0.6)', fontSize: 14, lineHeight: 1.7,
          maxWidth: 720, marginBottom: 32,
        }}>
          Migração gradual do host alugado atual para uma máquina dedicada.
          Compra peça por peça, da CPU ao gabinete, até a configuração base estar pronta.
          Investimento estimado entre {fmtBRL(totalMin)} e {fmtBRL(totalMax)}.
        </p>

        {/* Comparativo com host atual */}
        <HostComparison host={data.current_host} totalMin={totalMin} totalMax={totalMax} />

        {/* Barra de progresso superior */}
        <TimelineProgress
          timeline={data.timeline}
          currentIndex={data.current_step_index}
          totalItems={items.length}
          completedItems={completedItems}
        />

        {/* Botão expand/collapse da timeline */}
        <TimelineToggle
          expanded={timelineExpanded}
          onToggle={() => setTimelineExpanded(v => !v)}
          totalItems={items.length}
          totalMilestones={data.timeline.filter(e => e.type === 'milestone').length}
        />

        {/* Timeline vertical (colapsada mostra só o item current) */}
        <Timeline
          timeline={data.timeline}
          currentIndex={data.current_step_index}
          collapsed={!timelineExpanded}
        />

        {/* Build final */}
        {data.final_build_summary && (
          <FinalBuildCard summary={data.final_build_summary} />
        )}

        {/* Sugestões de upgrades futuros (subseção discreta) */}
        {data.future_upgrades && data.future_upgrades.items && data.future_upgrades.items.length > 0 && (
          <FutureUpgrades data={data.future_upgrades} />
        )}

        {/* Disclaimers */}
        {data.disclaimers && data.disclaimers.length > 0 && (
          <Disclaimers items={data.disclaimers} />
        )}

        {/* Aviso pos-meta */}
        {data.post_meta_notice && (
          <PostMetaNotice notice={data.post_meta_notice} />
        )}
      </div>
    </section>
  );
}

Object.assign(window, { MetaCrowdfunding });
