// site-jogador/js/roadmap-horizontal.jsx
//
// Roadmap visual horizontal estilo PoE 2 / No Man's Sky.
// 5 fases macro do projeto, scrollável horizontal, estações conectadas.
// Identidade visual herdada de landing.jsx (Rajdhani + Share Tech Mono +
// accent #a8ff00 + dark glass).
//
// Fonte de marcos: hardcoded aqui por enquanto. Depois pode ser alimentada
// pelo painel-admin via fetch ou build-time script (vide /roadmap/index.html).

const PHASES = [
  {
    id: 'fundacao',
    label: 'FUNDAÇÃO',
    statusLabel: 'CONCLUÍDA',
    dateLabel: 'Q1–Q2 2026',
    state: 'concluido',
    color: '#22c55e',
    icon: '⬢',
    description: 'Equipamento custom e mecânicas únicas que diferenciam o servidor.',
    milestones: [
      { done: true, label: 'Equipamento A.U.R.A. — 3 tiers de armadura customizada' },
      { done: true, label: 'Balanceamento próprio (sem kit invencível, todo equipamento tem trade-off)' },
      { done: true, label: 'Defesa vanilla recalibrada pra dar peso real à escolha de armadura' },
      { done: true, label: 'Pipeline interno pra produzir conteúdo customizado' },
    ],
  },
  {
    id: 'construcao',
    label: 'CONSTRUÇÃO',
    statusLabel: 'EM ANDAMENTO',
    dateLabel: 'Q2 2026',
    state: 'em-desenvolvimento',
    color: '#f59e0b',
    icon: '◈',
    description: 'Sistema de progressão e ferramentas internas de gestão.',
    milestones: [
      { done: false, label: 'Sistema de crafting com receitas progressivas (T1 acessível, T3 endgame)' },
      { done: false, label: 'Banca de trabalho com tiers (improvisada, oficina, militar)' },
      { done: false, label: 'Ferramentas pra manter o servidor estável e responder rápido a problemas' },
    ],
  },
  {
    id: 'pre-abertura',
    label: 'PRÉ-ABERTURA',
    statusLabel: 'PLANEJADO',
    dateLabel: 'Q3 2026',
    state: 'planejamento',
    color: '#3b82f6',
    icon: '◇',
    description: 'Última camada antes do servidor abrir pra comunidade.',
    milestones: [
      { done: false, label: 'Loot raro distribuído com cuidado (sem bombar inventário no início)' },
      { done: false, label: 'Site oficial com sistema de apoio (donate)' },
      { done: false, label: 'Onboarding via Discord com verificação anti-cheat' },
      { done: false, label: 'Discord vinculado à conta in-game pra entregas automáticas' },
    ],
  },
  {
    id: 'abertura-beta',
    label: 'ABERTURA BETA',
    statusLabel: 'PRÓXIMA META',
    dateLabel: 'Q4 2026',
    state: 'planejamento',
    color: '#a855f7',
    icon: '◆',
    description: 'Servidor aberto pra primeiros sobreviventes.',
    milestones: [
      { done: false, label: 'Acesso liberado pros primeiros jogadores' },
      { done: false, label: 'Eventos administrados ao vivo nas primeiras semanas' },
      { done: false, label: 'Coleta intensa de feedback' },
      { done: false, label: 'Ajustes de balance baseados em jogo real, não em teoria' },
    ],
  },
  {
    id: 'visao-futura',
    label: 'VISÃO FUTURA',
    statusLabel: 'EXPANSÃO',
    dateLabel: '2027+',
    state: 'ideia',
    color: '#737373',
    icon: '✧',
    description: 'O que vem depois do beta estabilizar.',
    milestones: [
      { done: false, label: 'Lobby único com tutorial in-game pros novos' },
      { done: false, label: 'Quests narrativas com lore exclusivo do servidor' },
      { done: false, label: 'NPCs traders movendo a economia player-driven' },
      { done: false, label: 'Eventos automáticos timed (airdrops PvP, hordas especiais, lua cheia)' },
    ],
  },
];

// ============================================================================
// JOURNEY BAR — trilha de waypoints conectados, mostra "voce esta aqui" e a rota
// ============================================================================
function JourneyBar({ phases, currentIdx }) {
  const total = phases.length;
  const progressPct = total > 1 ? (currentIdx / (total - 1)) * 100 : 0;

  return (
    <div
      style={{
        position: 'relative',
        display: 'grid',
        gridTemplateColumns: `repeat(${total}, minmax(0, 1fr))`,
        gap: 14,
        marginBottom: 28,
        paddingTop: 4,
      }}
    >
      {/* Linha base ligando todos os waypoints */}
      <div
        style={{
          position: 'absolute',
          top: 17, left: `${100 / total / 2}%`, right: `${100 / total / 2}%`,
          height: 2,
          background: 'rgba(255,255,255,0.1)',
          zIndex: 0,
        }}
      />
      {/* Linha de progresso ate o waypoint atual (verde solido) */}
      <div
        style={{
          position: 'absolute',
          top: 17,
          left: `${100 / total / 2}%`,
          width: `calc(${progressPct}% * ${(total - 1) / total})`,
          height: 2,
          background: 'linear-gradient(90deg, #22c55e 0%, #f59e0b 100%)',
          boxShadow: '0 0 10px rgba(34,197,94,0.5)',
          zIndex: 1,
          transition: 'width 0.6s ease',
        }}
      />

      {phases.map((p, i) => {
        const status = i < currentIdx ? 'done' : i === currentIdx ? 'current' : 'future';
        const color =
          status === 'done' ? '#22c55e' :
          status === 'current' ? p.color :
          'rgba(255,255,255,0.3)';
        const filled = status !== 'future';

        return (
          <div
            key={p.id}
            style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              position: 'relative',
              zIndex: 2,
            }}
          >
            <div
              style={{
                width: 34, height: 34, borderRadius: '50%',
                background: filled ? color : 'rgba(20,20,20,0.95)',
                border: `2px solid ${color}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'Share Tech Mono', fontSize: 12, fontWeight: 700,
                color: filled && status !== 'current' ? '#000' : status === 'current' ? '#000' : color,
                boxShadow: status === 'current' ? `0 0 18px ${color}cc` : status === 'done' ? `0 0 8px ${color}60` : 'none',
                animation: status === 'current' ? 'pulse-waypoint 1.8s ease-in-out infinite' : 'none',
              }}
            >
              {status === 'done' ? '✓' : String(i + 1).padStart(2, '0')}
            </div>

            {status === 'current' && (
              <div
                style={{
                  marginTop: 6,
                  display: 'flex', flexDirection: 'column', alignItems: 'center',
                  pointerEvents: 'none',
                }}
              >
                <div
                  style={{
                    width: 0, height: 0,
                    borderLeft: '5px solid transparent',
                    borderRight: '5px solid transparent',
                    borderBottom: `5px solid ${color}`,
                    marginBottom: 2,
                  }}
                />
                <div
                  style={{
                    fontFamily: 'Share Tech Mono', fontSize: 9, fontWeight: 700,
                    color, letterSpacing: '0.18em', whiteSpace: 'nowrap',
                    background: 'rgba(0,0,0,0.7)', padding: '3px 8px',
                    border: `1px solid ${color}80`,
                  }}
                >
                  FASE ATUAL
                </div>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

function PhaseCard({ phase, isCurrent }) {
  const [hovered, setHovered] = React.useState(false);

  // Defensive: se phase ou color não vier por qualquer motivo, não quebra a página
  if (!phase || !phase.color) {
    if (typeof console !== 'undefined') console.warn('[PhaseCard] phase inválida:', phase);
    return null;
  }

  const tintBg = `linear-gradient(180deg, ${phase.color}18 0%, ${phase.color}06 60%, transparent 100%)`;

  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        width: '100%',
        minWidth: 0,
        minHeight: 460,
        background: 'rgba(28,28,28,0.85)',
        backdropFilter: 'blur(20px) saturate(1.2)',
        WebkitBackdropFilter: 'blur(20px) saturate(1.2)',
        border: `1px solid ${isCurrent ? phase.color : 'rgba(255,255,255,0.08)'}`,
        borderTop: `3px solid ${phase.color}`,
        transition: 'transform 0.25s ease, box-shadow 0.25s ease, border-color 0.25s',
        transform: hovered ? 'translateY(-6px)' : 'translateY(0)',
        boxShadow: hovered
          ? `0 12px 32px rgba(0,0,0,0.4), 0 0 24px ${phase.color}40`
          : isCurrent
            ? `0 0 24px ${phase.color}30`
            : 'none',
        position: 'relative',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {/* Imagem placeholder (gradient) — será substituída por arte futuramente */}
      <div
        style={{
          height: 130,
          background: tintBg,
          borderBottom: `1px solid ${phase.color}30`,
          position: 'relative',
          overflow: 'hidden',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        {/* Linhas técnicas decorativas */}
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: `repeating-linear-gradient(0deg, transparent 0, transparent 11px, ${phase.color}08 11px, ${phase.color}08 12px)`,
          pointerEvents: 'none',
        }} />
        <div
          style={{
            fontFamily: 'Share Tech Mono',
            fontSize: 96,
            color: phase.color,
            opacity: 0.85,
            lineHeight: 1,
            filter: `drop-shadow(0 0 18px ${phase.color}80)`,
            animation: isCurrent ? 'pulse-icon 2.4s ease-in-out infinite' : 'none',
          }}
        >
          {phase.icon}
        </div>
        {/* Status badge */}
        <div style={{
          position: 'absolute', top: 10, right: 10,
          fontFamily: 'Share Tech Mono', fontSize: 9,
          color: phase.color, letterSpacing: '0.18em',
          background: 'rgba(0,0,0,0.6)', padding: '4px 8px',
          border: `1px solid ${phase.color}50`,
        }}>
          {phase.statusLabel}
        </div>
        {/* Date badge */}
        <div style={{
          position: 'absolute', bottom: 10, left: 10,
          fontFamily: 'Share Tech Mono', fontSize: 10,
          color: 'rgba(255,255,255,0.6)', letterSpacing: '0.1em',
          background: 'rgba(0,0,0,0.6)', padding: '3px 8px',
          border: '1px solid rgba(255,255,255,0.15)',
        }}>
          {phase.dateLabel}
        </div>
      </div>

      {/* Body */}
      <div style={{ padding: '18px 20px', display: 'flex', flexDirection: 'column', flex: 1 }}>
        <h3 style={{
          fontFamily: 'Rajdhani', fontWeight: 700,
          fontSize: 22, letterSpacing: '0.06em',
          color: '#fff', textTransform: 'uppercase',
          marginBottom: 8,
        }}>
          {phase.label}
        </h3>

        <p style={{
          fontSize: 12, color: 'rgba(255,255,255,0.55)',
          lineHeight: 1.6, marginBottom: 16,
          fontFamily: 'Rajdhani',
        }}>
          {phase.description}
        </p>

        <div style={{ flex: 1 }}>
          {phase.milestones.map((m, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'flex-start', gap: 10,
              marginBottom: 8,
              fontSize: 12, lineHeight: 1.5,
              fontFamily: 'Rajdhani',
              color: m.done ? 'rgba(255,255,255,0.85)' : 'rgba(255,255,255,0.5)',
            }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                width: 14, height: 14, flexShrink: 0, marginTop: 2,
                fontSize: 10, fontFamily: 'Share Tech Mono',
                color: m.done ? phase.color : 'rgba(255,255,255,0.3)',
                border: `1px solid ${m.done ? phase.color : 'rgba(255,255,255,0.2)'}`,
              }}>
                {m.done ? '✓' : '·'}
              </span>
              <span style={m.done ? {} : { textDecoration: 'none' }}>
                {m.label}
              </span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function RoadmapHorizontal() {
  const scrollRef = React.useRef(null);
  const currentIdx = PHASES.findIndex(p => p.state === 'em-desenvolvimento');

  const [isWide, setIsWide] = React.useState(
    typeof window !== 'undefined' && window.innerWidth >= 1100
  );
  React.useEffect(() => {
    const onResize = () => setIsWide(window.innerWidth >= 1100);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  const scroll = (dir) => {
    if (!scrollRef.current) return;
    scrollRef.current.scrollBy({ left: dir * 320, behavior: 'smooth' });
  };

  return (
    <section style={{ padding: '80px 5vw', position: 'relative' }}>
      {/* Animação local */}
      <style>{`
        @keyframes pulse-icon {
          0%,100% { opacity: 0.85; transform: scale(1); }
          50%      { opacity: 1; transform: scale(1.05); }
        }
        @keyframes pulse-waypoint {
          0%,100% { transform: scale(1);    box-shadow: 0 0 18px #f59e0bcc; }
          50%      { transform: scale(1.12); box-shadow: 0 0 28px #f59e0bff; }
        }
        .roadmap-scroll::-webkit-scrollbar { height: 6px; }
        .roadmap-scroll::-webkit-scrollbar-track { background: rgba(0,0,0,0.3); }
        .roadmap-scroll::-webkit-scrollbar-thumb { background: rgba(168,255,0,0.3); }
      `}</style>

      <div style={{ maxWidth: 1400, margin: '0 auto' }}>
        {/* Section header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <div style={{ width: 24, height: 2, background: '#a8ff00' }} />
          <span style={{ fontFamily: 'Share Tech Mono', fontSize: 11, color: '#a8ff00', letterSpacing: '0.18em' }}>
            ROADMAP DO PROJETO
          </span>
        </div>

        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16, marginBottom: 32 }}>
          <div>
            <h2 style={{
              fontFamily: 'Rajdhani', fontWeight: 700,
              fontSize: 'clamp(28px, 4vw, 48px)', lineHeight: 1.1,
              textTransform: 'uppercase',
            }}>
              ESTAMOS AQUI<br />
              <span style={{ color: '#a8ff00' }}>NA CONSTRUÇÃO</span>
            </h2>
            <p style={{
              color: 'rgba(255,255,255,0.55)', fontSize: 14,
              maxWidth: 540, marginTop: 12, lineHeight: 1.7,
            }}>
              5 fases macro do projeto, do alicerce ao endgame. Atualizado em tempo real conforme o trabalho avança.
            </p>
            {currentIdx >= 0 && (
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 10,
                marginTop: 14, padding: '6px 12px',
                background: `${PHASES[currentIdx].color}15`,
                border: `1px solid ${PHASES[currentIdx].color}50`,
                fontFamily: 'Share Tech Mono', fontSize: 11,
                color: PHASES[currentIdx].color, letterSpacing: '0.14em',
              }}>
                <span style={{ opacity: 0.7 }}>FASE {String(currentIdx + 1).padStart(2, '0')} DE {String(PHASES.length).padStart(2, '0')}</span>
                <span style={{ opacity: 0.4 }}>·</span>
                <span style={{ fontWeight: 700 }}>{PHASES[currentIdx].label}</span>
              </div>
            )}
          </div>

          {/* Scroll controls (somente em narrow) */}
          {!isWide && (
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => scroll(-1)} style={navButtonStyle()}>‹</button>
              <button onClick={() => scroll(1)} style={navButtonStyle()}>›</button>
            </div>
          )}
        </div>

        {/* Trilha de waypoints (jornada) */}
        <JourneyBar phases={PHASES} currentIdx={currentIdx} />

        {/* Cards: grid em desktop (todos visíveis), scroll horizontal em mobile */}
        {isWide ? (
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(5, minmax(0, 1fr))',
              gap: 14,
              paddingTop: 12,
              paddingBottom: 20,
            }}
          >
            {PHASES.map((phase, i) => (
              <PhaseCard key={phase.id} phase={phase} isCurrent={i === currentIdx} />
            ))}
          </div>
        ) : (
          <div
            ref={scrollRef}
            className="roadmap-scroll"
            style={{
              display: 'flex',
              gap: 16,
              overflowX: 'auto',
              paddingTop: 12,
              paddingBottom: 20,
              scrollSnapType: 'x mandatory',
            }}
          >
            {PHASES.map((phase, i) => (
              <div key={phase.id} style={{ scrollSnapAlign: 'start', display: 'flex', flex: '0 0 280px' }}>
                <PhaseCard phase={phase} isCurrent={i === currentIdx} />
                {i < PHASES.length - 1 && <PhaseConnector nextColor={PHASES[i + 1].color} fromColor={phase.color} />}
              </div>
            ))}
          </div>
        )}

        {/* Legenda */}
        <div style={{
          display: 'flex', gap: 20, flexWrap: 'wrap', marginTop: 24,
          fontFamily: 'Share Tech Mono', fontSize: 10, color: 'rgba(255,255,255,0.4)',
          letterSpacing: '0.12em',
        }}>
          {[
            { color: '#22c55e', label: 'CONCLUÍDA' },
            { color: '#f59e0b', label: 'EM ANDAMENTO' },
            { color: '#3b82f6', label: 'PLANEJADA' },
            { color: '#a855f7', label: 'PRÓXIMA META' },
            { color: '#737373', label: 'EXPANSÃO' },
          ].map(l => (
            <span key={l.label} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 10, height: 10, background: l.color, display: 'inline-block' }} />
              {l.label}
            </span>
          ))}
        </div>
      </div>
    </section>
  );
}

function PhaseConnector({ fromColor, nextColor }) {
  return (
    <div style={{
      width: 16, alignSelf: 'center',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flex: '0 0 16px',
    }}>
      <svg width="16" height="20" viewBox="0 0 16 20" style={{ overflow: 'visible' }}>
        <defs>
          <linearGradient id={`grad-${fromColor.slice(1)}-${nextColor.slice(1)}`} x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor={fromColor} stopOpacity="0.6" />
            <stop offset="100%" stopColor={nextColor} stopOpacity="0.6" />
          </linearGradient>
        </defs>
        <line
          x1="0" y1="10" x2="16" y2="10"
          stroke={`url(#grad-${fromColor.slice(1)}-${nextColor.slice(1)})`}
          strokeWidth="1.5"
          strokeDasharray="2 3"
        />
      </svg>
    </div>
  );
}

function navButtonStyle() {
  return {
    width: 36, height: 36,
    background: 'rgba(168,255,0,0.05)',
    border: '1px solid rgba(168,255,0,0.3)',
    color: '#a8ff00',
    fontFamily: 'Share Tech Mono', fontSize: 18,
    cursor: 'pointer', transition: 'all 0.2s',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  };
}

Object.assign(window, { RoadmapHorizontal });
