Files
Lucas Rayan GuerraandClaude Sonnet 5.5 bc9ae5c036 Redesign das páginas internas no novo design system (AAA) (#2)
* feat(design): redesign das páginas internas no novo design system

Padroniza todas as páginas e componentes internos nos tokens e primitivos
de app/globals.css, com contraste AAA (7:1) nos dois temas e alvos de toque
de 44px.

- Páginas reescritas: glossário, séries, série, seletor, comparador,
  diagnóstico, catálogo, component registry, frameworks, framework, sobre
  e a nova 404.
- Componentes: PageHero e SectionHead novos; BoardCard, CodeExample,
  PinRestrictions, SeriesTabMenu e ConnectionsDiagram refeitos, com abas
  e diálogo acessíveis.
- Remove emojis, cores avulsas por série, caixa alta com tracking, texto
  menor que 12px e os pares slate-*/dark:*.
- Comparador: "mostrar só as diferenças" e leitura de ?chips=.
- Corrige overflow em 320/390px e ajusta accent/copper do tema claro
  para fechar 7:1.
- scripts/auditar-temas.mjs passa a travar paleta crua, dark:, texto
  pequeno, emoji e contraste dos tokens.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016W1xmizFcmXLrmabSvfSuc

* ci: roda lint, auditorias de design e build em cada PR

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016W1xmizFcmXLrmabSvfSuc

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 16:10:15 -03:00

1333 lines
56 KiB
React

"use client";
import { useState, useMemo } from "react";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import Link from "next/link";
import seriesData from "@/public/series.json";
import PageHero from "@/components/PageHero";
import {
Activity,
AlertTriangle,
ArrowRight,
ArrowUpRight,
Award,
Ban,
Battery,
BookOpen,
Bot,
Cable,
Check,
CheckCircle,
ChevronLeft,
ChevronRight,
Cpu,
Edit2,
Filter,
HardDrive,
HelpCircle,
Home as HomeIcon,
KeyRound,
Layers,
Lock,
Monitor,
Network,
Radio,
RotateCcw,
ShieldCheck,
ShoppingBag,
Sliders,
SlidersHorizontal,
Sparkles,
Volume2,
Wifi,
Zap,
} from "lucide-react";
// Dynamic icon mapper for options and presets
const iconMap = {
// Categorias
"category_smarthome": <HomeIcon className="h-5 w-5" aria-hidden="true" />,
"category_multimedia": <Monitor className="h-5 w-5" aria-hidden="true" />,
"category_ai_edge": <Bot className="h-5 w-5" aria-hidden="true" />,
"category_wearable": <Battery className="h-5 w-5" aria-hidden="true" />,
"category_industrial": <Cpu className="h-5 w-5" aria-hidden="true" />,
"category_basic_iot": <Sparkles className="h-5 w-5" aria-hidden="true" />,
// Conectividade
"connectivity_wifi6_dualband": <Wifi className="h-5 w-5" aria-hidden="true" />,
"connectivity_wifi6_mesh": <Network className="h-5 w-5" aria-hidden="true" />,
"connectivity_mesh_only": <Radio className="h-5 w-5" aria-hidden="true" />,
"connectivity_wifi_ble": <Wifi className="h-5 w-5" aria-hidden="true" />,
"connectivity_bt_classic_audio": <Volume2 className="h-5 w-5" aria-hidden="true" />,
"connectivity_ethernet": <Cable className="h-5 w-5" aria-hidden="true" />,
"connectivity_none_local": <Ban className="h-5 w-5" aria-hidden="true" />,
// Alimentação
"power_battery_critical": <Battery className="h-5 w-5" aria-hidden="true" />,
"power_ulp_coprocessor": <Activity className="h-5 w-5" aria-hidden="true" />,
"power_always_on": <Zap className="h-5 w-5" aria-hidden="true" />,
// Periféricos / Hardware
"hardware_mipi_multimedia": <Monitor className="h-5 w-5" aria-hidden="true" />,
"hardware_usb_otg": <Cable className="h-5 w-5" aria-hidden="true" />,
"hardware_can_twai": <Sliders className="h-5 w-5" aria-hidden="true" />,
"hardware_dac_audio": <Volume2 className="h-5 w-5" aria-hidden="true" />,
"hardware_many_gpios": <SlidersHorizontal className="h-5 w-5" aria-hidden="true" />,
"hardware_standard_sensors": <Cpu className="h-5 w-5" aria-hidden="true" />,
// Memória
"memory_heavy_psram": <HardDrive className="h-5 w-5" aria-hidden="true" />,
"memory_moderate_sram": <Layers className="h-5 w-5" aria-hidden="true" />,
"memory_minimal_cost": <Sparkles className="h-5 w-5" aria-hidden="true" />,
// IA
"ai_ai_vector": <Bot className="h-5 w-5" aria-hidden="true" />,
"ai_standard": <Ban className="h-5 w-5" aria-hidden="true" />,
// Segurança
"security_key_manager_dpa": <KeyRound className="h-5 w-5" aria-hidden="true" />,
"security_hardware_ecc_ecdsa": <ShieldCheck className="h-5 w-5" aria-hidden="true" />,
"security_matter_ecdsa": <ShieldCheck className="h-5 w-5" aria-hidden="true" />,
"security_secure_boot": <Lock className="h-5 w-5" aria-hidden="true" />,
"security_standard_tls": <HelpCircle className="h-5 w-5" aria-hidden="true" />,
// Ecossistema
"ecosystem_arduino_ready": <CheckCircle className="h-5 w-5" aria-hidden="true" />,
"ecosystem_advanced_idf": <Cpu className="h-5 w-5" aria-hidden="true" />,
};
const getOptionIcon = (questionId, value) => {
const key = `${questionId}_${value}`;
return iconMap[key] || <HelpCircle className="h-5 w-5" aria-hidden="true" />;
};
// 7 Preset Configurations for 1-click recommendations
const PRESETS = [
{
id: "preset_smarthome",
title: "Smart Home & Matter",
badge: "Automação 802.15.4",
description: "Wi-Fi 6, Thread/Zigbee e baixo consumo",
answers: {
category: "smarthome",
connectivity: "wifi6_mesh",
power: "ulp_coprocessor",
hardware: "standard_sensors",
memory: "moderate_sram",
ai: "standard",
security: "hardware_ecc_ecdsa",
ecosystem: "arduino_ready",
}
},
{
id: "preset_hmi",
title: "Painel Touch & Telas",
badge: "Display / Câmera",
description: "Display LCD/MIPI, PSRAM e alta taxa de quadros",
answers: {
category: "multimedia",
connectivity: "wifi_ble",
power: "always_on",
hardware: "mipi_multimedia",
memory: "heavy_psram",
ai: "standard",
security: "secure_boot",
ecosystem: "arduino_ready",
}
},
{
id: "preset_ai",
title: "Edge AI & Visão",
badge: "Aceleração Vetorial",
description: "Acelerador neural, câmera e alta memória",
answers: {
category: "ai_edge",
connectivity: "wifi_ble",
power: "always_on",
hardware: "mipi_multimedia",
memory: "heavy_psram",
ai: "ai_vector",
security: "secure_boot",
ecosystem: "arduino_ready",
}
},
{
id: "preset_wearable",
title: "Wearable a Bateria",
badge: "Deep Sleep <10µA",
description: "Eficiência extrema e rádio Bluetooth LE",
answers: {
category: "wearable",
connectivity: "wifi_ble",
power: "battery_critical",
hardware: "standard_sensors",
memory: "minimal_cost",
ai: "standard",
security: "standard_tls",
ecosystem: "arduino_ready",
}
},
{
id: "preset_wifi6_5ghz",
title: "Wi-Fi 6 Dual-Band (5GHz)",
badge: "2.4 & 5 GHz",
description: "Banda de 5 GHz com menor interferência de RF",
answers: {
category: "smarthome",
connectivity: "wifi6_dualband",
power: "always_on",
hardware: "standard_sensors",
memory: "moderate_sram",
ai: "standard",
security: "key_manager_dpa",
ecosystem: "arduino_ready",
}
},
{
id: "preset_industrial",
title: "Industrial / CAN & Rede",
badge: "Ethernet & TWAI",
description: "Barramento CAN/TWAI, Ethernet e alta robustez",
answers: {
category: "industrial",
connectivity: "ethernet",
power: "always_on",
hardware: "can_twai",
memory: "moderate_sram",
ai: "standard",
security: "secure_boot",
ecosystem: "arduino_ready",
}
},
{
id: "preset_budget",
title: "IoT Básico de Baixo Custo",
badge: "Ultra-Econômico",
description: "Menor custo por unidade para sensores simples",
answers: {
category: "basic_iot",
connectivity: "wifi_ble",
power: "battery_critical",
hardware: "standard_sensors",
memory: "minimal_cost",
ai: "standard",
security: "standard_tls",
ecosystem: "arduino_ready",
}
}
];
export default function Seletor() {
const [mode, setMode] = useState("wizard"); // "wizard" | "filter"
const [currentStep, setCurrentStep] = useState(0);
const [currentAnswer, setCurrentAnswer] = useState(null);
const [activePreset, setActivePreset] = useState(null);
const [answers, setAnswers] = useState({
category: null,
connectivity: null,
power: null,
hardware: null,
memory: null,
ai: null,
security: null,
ecosystem: null,
});
const [showResults, setShowResults] = useState(false);
const [showSummary, setShowSummary] = useState(false);
// Direct Parametric Filter State (for "filter" mode)
const [filters, setFilters] = useState({
wifi6: false,
wifi5ghz: false,
bluetoothClassic: false,
leAudio: false,
matter: false,
ethernet: false,
aiAccel: false,
psram: false,
mipiDisplayCamera: false,
usbOTG: false,
canBus: false,
dac: false,
touch: false,
arduinoReady: false,
keyManager: false,
eccHardware: false,
ecdsaHardware: false,
secureBootV2: false,
});
const questions = [
{
id: "category",
question: "1. Qual é o foco principal ou aplicação do seu projeto?",
description: "Categorizar sua aplicação ajuda a equilibrar formato físico, custo por unidade, barramentos de mídia e poder computacional.",
options: [
{ value: "smarthome", label: "Automação / Smart Home / Dispositivos Conectados", icon: "category_smarthome" },
{ value: "multimedia", label: "Interfaces Gráficas (Telas LCD/MIPI / Câmeras / IHM)", icon: "category_multimedia" },
{ value: "ai_edge", label: "Inteligência Artificial na Borda (Visão / Áudio / TinyML)", icon: "category_ai_edge" },
{ value: "wearable", label: "Dispositivo Portátil / Vestível (Alimentado a Bateria)", icon: "category_wearable" },
{ value: "industrial", label: "Industrial / Robótica / Redes de Campo e Automação", icon: "category_industrial" },
{ value: "basic_iot", label: "IoT Básico / Sensor Conectado de Ultra-Baixo Custo", icon: "category_basic_iot" },
]
},
{
id: "connectivity",
question: "2. Qual tecnologia de rede sem fio ou cabeada você precisa?",
description: "O ecossistema ESP32 oferece desde rádios Wi-Fi 6 Dual-Band (2.4/5GHz), Bluetooth 6 e Mesh 802.15.4 até Ethernet cabeada e Bluetooth Clássico.",
options: [
{ value: "wifi6_dualband", label: "Wi-Fi 6 Dual-Band (2.4 GHz e 5 GHz) + Bluetooth 6.0", icon: "connectivity_wifi6_dualband" },
{ value: "wifi6_mesh", label: "Wi-Fi 6 (2.4 GHz) + Matter / Zigbee 3.0 / Thread (802.15.4)", icon: "connectivity_wifi6_mesh" },
{ value: "mesh_only", label: "Apenas Rádio Mesh (Zigbee / Thread / Matter) + BLE (Sem Wi-Fi)", icon: "connectivity_mesh_only" },
{ value: "wifi_ble", label: "Wi-Fi 4 Tradicional (2.4 GHz) + Bluetooth LE", icon: "connectivity_wifi_ble" },
{ value: "bt_classic_audio", label: "Bluetooth Clássico BR/EDR (Áudio A2DP / SPP Serial)", icon: "connectivity_bt_classic_audio" },
{ value: "ethernet", label: "Rede Cabeada Industrial (Ethernet MAC integrado)", icon: "connectivity_ethernet" },
{ value: "none_local", label: "Apenas Processamento Local / Sem Conexão Sem Fio", icon: "connectivity_none_local" },
]
},
{
id: "power",
question: "3. Como o dispositivo será alimentado eletricamente?",
description: "A escolha da fonte define a importância de modos de Deep Sleep ultra-baixos (<10µA) e coprocessadores ULP para monitoramento contínuo.",
options: [
{ value: "battery_critical", label: "Bateria / Solar (Consumo Ultra-Baixo em Deep Sleep <10µA)", icon: "power_battery_critical" },
{ value: "ulp_coprocessor", label: "Misto / Monitorar sensores em background via Coprocessador ULP", icon: "power_ulp_coprocessor" },
{ value: "always_on", label: "Tomada, Fonte Externa ou USB (Sempre Ativo / Alto Desempenho)", icon: "power_always_on" },
]
},
{
id: "hardware",
question: "4. Quais periféricos ou barramentos físicos especiais você vai usar?",
description: "Algumas funcionalidades exigem blocos de silício dedicados, como interfaces de vídeo MIPI/RGB, barramento CAN industrial ou USB nativo.",
options: [
{ value: "mipi_multimedia", label: "Display Gráfico LCD (RGB/MIPI DSI) ou Câmeras (DVP/MIPI CSI)", icon: "hardware_mipi_multimedia" },
{ value: "usb_otg", label: "USB Nativo OTG / Host (Emular teclado/mouse HID, CDC ou modo Host)", icon: "hardware_usb_otg" },
{ value: "can_twai", label: "Barramento Automotivo / Industrial CAN (TWAI ou CAN-FD)", icon: "hardware_can_twai" },
{ value: "dac_audio", label: "Áudio Analógico com DAC integrado (saída direta de som)", icon: "hardware_dac_audio" },
{ value: "many_gpios", label: "Muitos pinos livres de expansão (Mais de 35 GPIOs físicos)", icon: "hardware_many_gpios" },
{ value: "standard_sensors", label: "Sensores comuns com barramentos tradicionais (I2C, SPI, UART, PWM)", icon: "hardware_standard_sensors" },
]
},
{
id: "memory",
question: "5. Qual o volume de memória RAM / PSRAM necessário?",
description: "Projetos gráficos (LVGL), visão computacional, áudio ou pilhas pesadas exigem suporte a PSRAM externa ou integrada de alta densidade.",
options: [
{ value: "heavy_psram", label: "Alta Densidade de PSRAM (>4 MB a 64 MB para buffers de vídeo, IA ou LVGL)", icon: "memory_heavy_psram" },
{ value: "moderate_sram", label: "SRAM interna equilibrada (320 KB a 512 KB) com ou sem PSRAM leve", icon: "memory_moderate_sram" },
{ value: "minimal_cost", label: "Memória compacta e econômica (firmware enxuto de baixo custo)", icon: "memory_minimal_cost" },
]
},
{
id: "ai",
question: "6. Seu projeto usará Inteligência Artificial local (Edge AI / TinyML)?",
description: "Instruções vetoriais e aceleradores neurais dedicados em hardware reduzem o tempo de inferência de redes neurais de segundos para milissegundos.",
options: [
{ value: "ai_vector", label: "Sim, preciso de acelerador vetorial de IA em hardware (TinyML / Visão)", icon: "ai_ai_vector" },
{ value: "standard", label: "Não, processamento lógico e matemático comum é suficiente", icon: "ai_standard" },
]
},
{
id: "security",
question: "7. Qual nível de segurança e criptografia por hardware o produto exige?",
description: "As séries diferem em suporte a Key Manager, proteção contra ataques de canal lateral (DPA), curvas elípticas (ECC/ECDSA) e aceleradores AES.",
options: [
{ value: "key_manager_dpa", label: "Proteção Máxima: Key Manager em hardware (chave isolada da CPU) e Proteção DPA", icon: "security_key_manager_dpa" },
{ value: "hardware_ecc_ecdsa", label: "Acelerador de Curvas Elípticas (ECC) e Assinatura Digital ECDSA por hardware", icon: "security_hardware_ecc_ecdsa" },
{ value: "secure_boot", label: "Boot Seguro V2 e Criptografia de Flash (XTS-AES) contra cópia do firmware", icon: "security_secure_boot" },
{ value: "standard_tls", label: "Comunicação TLS/HTTPS comum (Aceleradores AES e SHA por hardware)", icon: "security_standard_tls" },
]
},
{
id: "ecosystem",
question: "8. Qual é a sua preferência de ambiente de desenvolvimento?",
description: "Chips mais maduros têm amplo suporte oficial no Arduino Core com centenas de bibliotecas prontas, enquanto chips preliminares utilizam ESP-IDF.",
options: [
{ value: "arduino_ready", label: "Pronto para Arduino IDE (suporte maduro com vasta coleção de bibliotecas)", icon: "ecosystem_arduino_ready" },
{ value: "advanced_idf", label: "ESP-IDF profissional ou aberto a silícios de última geração (S31, H4, etc.)", icon: "ecosystem_advanced_idf" },
]
}
];
const handleAnswer = (questionId, value) => {
setCurrentAnswer(value);
setAnswers(prev => ({ ...prev, [questionId]: value }));
setActivePreset(null);
};
const handleNext = () => {
if (currentAnswer !== null) {
if (currentStep < questions.length - 1) {
const nextStep = currentStep + 1;
setCurrentStep(nextStep);
setCurrentAnswer(answers[questions[nextStep].id] || null);
} else {
setShowSummary(true);
}
}
};
const goBack = () => {
if (currentStep > 0) {
const prevStep = currentStep - 1;
setCurrentStep(prevStep);
setCurrentAnswer(answers[questions[prevStep].id] || null);
}
};
const resetQuiz = () => {
setCurrentStep(0);
setCurrentAnswer(null);
setShowResults(false);
setShowSummary(false);
setActivePreset(null);
setAnswers({
category: null,
connectivity: null,
power: null,
hardware: null,
memory: null,
ai: null,
security: null,
ecosystem: null,
});
};
const applyPreset = (preset) => {
setAnswers(preset.answers);
setActivePreset(preset.id);
setCurrentStep(questions.length - 1);
setCurrentAnswer(preset.answers.ecosystem);
setShowSummary(false);
setShowResults(true);
};
// Comprehensive Multi-Criteria Scoring Engine based on series.json
const calculateRecommendations = () => {
const scores = {};
const reasons = {};
const alerts = {};
Object.keys(seriesData).forEach(key => {
scores[key] = 0;
reasons[key] = [];
alerts[key] = [];
const serie = seriesData[key];
const seg = serie.seguranca || {};
// 1. CATEGORIA (category)
if (answers.category === "smarthome") {
if (serie.matter === "Sim") {
scores[key] += 25;
reasons[key].push("Suporte nativo a Matter para interoperabilidade residencial inteligente");
}
if (serie.zigbee_thread && serie.zigbee_thread !== "Não") {
scores[key] += 20;
reasons[key].push("Rádio 802.15.4 integrado compatível com Zigbee 3.0 e Thread");
}
if (serie.wifi && !String(serie.wifi).includes("Não")) {
scores[key] += 10;
reasons[key].push("Rádio Wi-Fi integrado para conexão direta ao roteador");
}
} else if (answers.category === "multimedia") {
if (serie.mipi_dsi || serie.mipi_csi) {
scores[key] += 35;
reasons[key].push("Barramentos avançados de alta velocidade MIPI DSI (telas) e MIPI CSI (câmeras)");
} else if (serie.lcd || serie.camera) {
scores[key] += 25;
reasons[key].push("Interfaces dedicadas em hardware para telas LCD RGB e câmeras DVP");
} else {
scores[key] -= 40;
alerts[key].push("Sem barramentos dedicados para telas coloridas ou câmeras (apenas SPI/I2C simples)");
}
if (serie.psram_externa && serie.psram_externa !== "Não") {
scores[key] += 20;
reasons[key].push("Suporte a PSRAM de alta capacidade para framebuffers gráficos e processamento de imagem");
}
} else if (answers.category === "ai_edge") {
if (serie.aceleradores_ia) {
scores[key] += 40;
reasons[key].push(`Aceleração neural e instruções vetoriais dedicadas (${serie.aceleradores_ia})`);
} else {
scores[key] -= 50;
alerts[key].push("Sem aceleradores neurais dedicados em hardware");
}
if (serie.nucleos && serie.nucleos.includes("2")) {
scores[key] += 10;
reasons[key].push("Processador Dual-Core para pipeline paralelo de captura e inferência");
}
} else if (answers.category === "wearable") {
const sleep = serie.consumo_energia?.deep_sleep;
if (sleep) {
const uaMatch = sleep.match(/(\d+)\s*µA/);
if (uaMatch && parseInt(uaMatch[1]) <= 10) {
scores[key] += 25;
reasons[key].push(`Consumo em Deep Sleep ultrabaixo de apenas ${sleep} preserva baterias compactas`);
}
}
if (serie.bluetooth && serie.bluetooth !== "Não") {
scores[key] += 15;
reasons[key].push("Rádio Bluetooth de alta eficiência energética para pareamento contínuo");
}
if (key === "ESP32-C2" || key === "ESP32-C3" || key === "ESP32-H2") {
scores[key] += 10;
reasons[key].push("Encapsulamento compacto QFN reduz o footprint na placa");
}
} else if (answers.category === "industrial") {
if (serie.ethernet || serie.ethernet_mac) {
scores[key] += 30;
reasons[key].push("Controlador MAC Ethernet integrado para conexões cabeadas industriais imunes a ruídos de RF");
}
if (serie.can) {
scores[key] += 25;
reasons[key].push(`Interface de barramento industrial ${serie.can}`);
}
if (parseInt(serie.gpio) >= 30) {
scores[key] += 10;
reasons[key].push(`Ampla contagem de portas digitais (${serie.gpio} GPIOs) para relés e atuadores`);
}
} else if (answers.category === "basic_iot") {
if (key === "ESP32-C2" || key === "ESP32-C3" || key === "ESP32-C61") {
scores[key] += 30;
reasons[key].push("Excelente relação custo-benefício para sensores e atuadores conectados em escala");
}
if (serie.wifi && !String(serie.wifi).includes("Não") && serie.bluetooth !== "Não") {
scores[key] += 15;
reasons[key].push("Wi-Fi + BLE integrados em módulo econômico");
}
}
// 2. CONECTIVIDADE (connectivity)
if (answers.connectivity === "wifi6_dualband") {
if (String(serie.wifi).includes("5 GHz") || String(serie.wifi).includes("dual-band")) {
scores[key] += 50;
reasons[key].push("Exclusivo Wi-Fi 6 Dual-Band (2.4 GHz e 5 GHz) para ambientes com alto ruído de RF");
} else {
scores[key] -= 250;
alerts[key].push("Incompatível: Não possui rádio Wi-Fi na faixa de 5 GHz");
}
} else if (answers.connectivity === "wifi6_mesh") {
if (String(serie.wifi).includes("Wi-Fi 6") && serie.matter === "Sim") {
scores[key] += 40;
reasons[key].push("Wi-Fi 6 (802.11ax) somado a rádio 802.15.4 para Thread/Zigbee/Matter");
} else if (serie.matter === "Sim") {
scores[key] += 15;
reasons[key].push("Suporte a Matter/Thread, porém sem Wi-Fi 6");
} else {
scores[key] -= 150;
alerts[key].push("Incompatível: Sem rádio 802.15.4 integrado para Thread/Zigbee");
}
} else if (answers.connectivity === "mesh_only") {
if ((serie.wifi === "Não" || !serie.wifi) && serie.matter === "Sim") {
scores[key] += 45;
reasons[key].push("Foco 100% em 802.15.4 (Zigbee/Thread/Matter) com baixo consumo e sem rádio Wi-Fi");
} else if (serie.matter === "Sim") {
scores[key] += 20;
reasons[key].push("Suporta redes Mesh (Zigbee/Thread), mas inclui rádio Wi-Fi adicional");
} else {
scores[key] -= 180;
alerts[key].push("Incompatível: Sem rádio 802.15.4 para protocolo Thread ou Zigbee");
}
} else if (answers.connectivity === "wifi_ble") {
if (serie.wifi && !String(serie.wifi).includes("Não") && serie.bluetooth && serie.bluetooth !== "Não") {
scores[key] += 30;
reasons[key].push(`Pilha completa com Wi-Fi (${serie.wifi}) e Bluetooth (${serie.bluetooth})`);
} else if (serie.wifi && !String(serie.wifi).includes("Não")) {
scores[key] += 10;
alerts[key].push("Possui Wi-Fi, mas não possui rádio Bluetooth integrado");
} else {
scores[key] -= 200;
alerts[key].push("Incompatível: Não possui rádio Wi-Fi integrado");
}
} else if (answers.connectivity === "bt_classic_audio") {
if (String(serie.bluetooth).includes("Classic") || String(serie.bluetooth).includes("Clássico")) {
scores[key] += 50;
reasons[key].push("Suporte a Bluetooth Clássico (BR/EDR) com perfis A2DP de áudio e SPP serial");
} else {
scores[key] -= 250;
alerts[key].push("Incompatível: Não possui Bluetooth Clássico (apenas BLE, incompatível com áudio A2DP legado)");
}
} else if (answers.connectivity === "ethernet") {
if (serie.ethernet || serie.ethernet_mac) {
scores[key] += 45;
reasons[key].push("Controlador MAC Ethernet nativo integrado (requer apenas transceiver PHY)");
} else {
scores[key] -= 180;
alerts[key].push("Sem MAC Ethernet interno (necessita de módulo SPI Ethernet externo como W5500)");
}
} else if (answers.connectivity === "none_local") {
if (serie.wifi === "Não" || serie.bluetooth === "Não" || key === "ESP32-P4") {
scores[key] += 35;
reasons[key].push("Arquitetura orientada a processamento local dedicado sem custo de transceivers de rádio");
} else {
scores[key] += 10;
}
}
// 3. ALIMENTAÇÃO (power)
if (answers.power === "battery_critical") {
const sleep = serie.consumo_energia?.deep_sleep;
if (sleep) {
const uaMatch = sleep.match(/(\d+)\s*µA/);
if (uaMatch && parseInt(uaMatch[1]) <= 10) {
scores[key] += 25;
reasons[key].push(`Consumo de suspensão de ${sleep} permite operação prolongada por bateria`);
} else {
scores[key] += 10;
reasons[key].push(`Modo de baixo consumo de ${sleep}`);
}
}
if (serie.coprocessador_ulp && serie.coprocessador_ulp !== "Não") {
scores[key] += 10;
reasons[key].push("Coprocessador ULP permite checar pinos sem despertar a CPU principal");
}
} else if (answers.power === "ulp_coprocessor") {
if (serie.coprocessador_ulp && serie.coprocessador_ulp !== "Não") {
scores[key] += 35;
reasons[key].push(`Coprocessador ULP / CPU de Baixo Consumo (${serie.coprocessador_ulp})`);
} else {
scores[key] -= 30;
alerts[key].push("Sem coprocessador ULP dedicado");
}
} else if (answers.power === "always_on") {
if (serie.nucleos && serie.nucleos.includes("2")) {
scores[key] += 15;
reasons[key].push("Processador Dual-Core para multitarefa paralela contínua");
}
const freqMatch = serie.frequencia?.match(/(\d+)\s*MHz/);
if (freqMatch && parseInt(freqMatch[1]) >= 240) {
scores[key] += 15;
reasons[key].push(`Frequência de clock de alto desempenho (${serie.frequencia})`);
}
}
// 4. HARDWARE & PERIFÉRICOS (hardware)
if (answers.hardware === "mipi_multimedia") {
if (serie.mipi_dsi || serie.mipi_csi) {
scores[key] += 40;
reasons[key].push("Interface MIPI DSI (telas) e MIPI CSI (câmeras) de altíssima taxa de transferência");
} else if (serie.lcd || serie.camera) {
scores[key] += 25;
reasons[key].push("Interfaces paralelas para LCD RGB e câmeras DVP de 8/16 bits");
} else {
scores[key] -= 180;
alerts[key].push("Incompatível: Sem interfaces dedicadas de tela/câmera (limitado a barramento SPI/I2C)");
}
} else if (answers.hardware === "usb_otg") {
if (serie.usb && String(serie.usb).includes("OTG 2.0")) {
scores[key] += 40;
reasons[key].push(`Porta USB 2.0 High-Speed OTG (${serie.usb}) para emulação HID, CDC e modo Host`);
} else if (serie.usb && String(serie.usb).includes("OTG")) {
scores[key] += 30;
reasons[key].push(`Interface USB OTG 1.1 integrada (${serie.usb}) para emulação HID e Host`);
} else {
scores[key] -= 160;
alerts[key].push("Incompatível: Sem USB OTG nativo (USB Serial/JTAG não suporta modo Host ou HID customizado)");
}
} else if (answers.hardware === "can_twai") {
if (serie.can && String(serie.can).includes("CAN FD")) {
scores[key] += 40;
reasons[key].push("Controlador avançado CAN-FD (Flexible Data-Rate) para alta largura de banda automotiva");
} else if (serie.can) {
scores[key] += 30;
reasons[key].push(`Controlador de barramento industrial ${serie.can}`);
} else {
scores[key] -= 150;
alerts[key].push("Incompatível: Sem controlador de barramento CAN / TWAI nativo");
}
} else if (answers.hardware === "dac_audio") {
if (serie.dac && serie.dac !== "Não") {
scores[key] += 45;
reasons[key].push(`Conversores Digital-Analógico embutidos (${serie.dac}) para saída de áudio direta sem DAC externo`);
} else {
scores[key] -= 150;
alerts[key].push("Incompatível: Não possui conversor DAC interno de áudio (requer codec I2S externo)");
}
} else if (answers.hardware === "many_gpios") {
const gpios = parseInt(serie.gpio) || 0;
if (gpios >= 40) {
scores[key] += 35;
reasons[key].push(`Excepcional número de pinos disponíveis (${gpios} GPIOs)`);
} else if (gpios >= 28) {
scores[key] += 15;
reasons[key].push(`Quantidade moderada de portas (${gpios} GPIOs)`);
} else {
scores[key] -= 60;
alerts[key].push(`Contagem restrita de pinos (${gpios} GPIOs)`);
}
} else if (answers.hardware === "standard_sensors") {
scores[key] += 10;
}
// 5. MEMÓRIA & PSRAM (memory)
if (answers.memory === "heavy_psram") {
if (serie.psram_externa && (String(serie.psram_externa).includes("64 MB") || String(serie.psram_externa).includes("1 GB"))) {
scores[key] += 40;
reasons[key].push(`Expansão massiva de memória PSRAM (${serie.psram_externa})`);
} else if (serie.psram_externa && serie.psram_externa !== "Não") {
scores[key] += 25;
reasons[key].push(`Suporte a memória PSRAM externa (${serie.psram_externa})`);
} else {
scores[key] -= 180;
alerts[key].push("Incompatível: Sem suporte a memória PSRAM externa ou integrada");
}
} else if (answers.memory === "moderate_sram") {
const sramMatch = serie.memoria_sram?.match(/(\d+)\s*KB/);
if (sramMatch && parseInt(sramMatch[1]) >= 380) {
scores[key] += 15;
reasons[key].push(`SRAM interna confortável (${serie.memoria_sram})`);
} else {
scores[key] += 8;
}
} else if (answers.memory === "minimal_cost") {
if (key === "ESP32-C2" || key === "ESP32-C3" || key === "ESP32-H2") {
scores[key] += 25;
reasons[key].push("Memória enxuta e silício compacto para menor custo unitário");
} else {
scores[key] += 5;
}
}
// 6. INTELIGÊNCIA ARTIFICIAL (ai)
if (answers.ai === "ai_vector") {
if (serie.aceleradores_ia) {
scores[key] += 45;
reasons[key].push("Acelerador neural de silício e instruções vetoriais para inferência veloz");
} else {
scores[key] -= 180;
alerts[key].push("Incompatível: Sem aceleração vetorial por hardware para IA na borda");
}
} else if (answers.ai === "standard") {
scores[key] += 5;
}
// 7. SEGURANÇA (security)
const temECDSA = String(seg.ecdsa).startsWith("Sim");
const temECC = String(seg.ecc).startsWith("Sim");
const temAES = String(seg.aes).startsWith("AES");
const temKeyManager = seg.key_manager === "Sim";
const temDPA = seg.protecao_dpa === "Sim";
if (answers.security === "key_manager_dpa") {
if (temKeyManager && temDPA) {
scores[key] += 45;
reasons[key].push("Key Manager em silício (chaves isoladas da CPU) e proteção contra análise de consumo DPA");
} else if (temKeyManager) {
scores[key] += 35;
reasons[key].push("Periférico Key Manager integrado para isolamento total de chaves privadas");
} else if (temDPA) {
scores[key] += 20;
reasons[key].push("Proteção física DPA em hardware contra ataques de canal lateral");
} else {
scores[key] -= 160;
alerts[key].push("Incompatível: Sem Key Manager nem proteção física contra DPA");
}
} else if (answers.security === "hardware_ecc_ecdsa") {
if (temECDSA) {
scores[key] += 40;
reasons[key].push(`Acelerador de assinatura digital ECDSA determinístico em hardware (${seg.ecc})`);
} else if (temECC) {
scores[key] += 30;
reasons[key].push(`Coprocessador de curvas elípticas ECC em hardware (${seg.ecc})`);
} else {
scores[key] -= 220;
alerts[key].push("Incompatível: Não possui acelerador de hardware para curvas elípticas (ECC/ECDSA)");
}
} else if (answers.security === "secure_boot") {
if (String(seg.secure_boot).includes("V2")) {
scores[key] += 25;
reasons[key].push(`Secure Boot ${seg.secure_boot} com criptografia de flash ${seg.criptografia_flash}`);
} else if (String(seg.secure_boot).includes("V1")) {
scores[key] += 5;
alerts[key].push("Secure Boot em esquema V1 (legado com limitações de segurança)");
} else {
scores[key] -= 80;
alerts[key].push("Sem Secure Boot V2 estável");
}
} else if (answers.security === "standard_tls") {
if (temAES) {
scores[key] += 15;
reasons[key].push(`Criptografia de tráfego TLS acelerada por hardware (${seg.aes})`);
} else {
scores[key] += 5;
}
}
// 8. ECOSSISTEMA (ecosystem)
if (answers.ecosystem === "arduino_ready") {
if (String(serie.arduino_core).startsWith("Sim")) {
const countMatch = serie.arduino_core.match(/(\d+)\s*definições/);
const count = countMatch ? parseInt(countMatch[1]) : 1;
if (count >= 20) {
scores[key] += 25;
reasons[key].push(`Excelente maturidade no core oficial Arduino (${count} variantes de placas)`);
} else {
scores[key] += 15;
reasons[key].push(`Suporte no core oficial Arduino (${count} placa registrada)`);
}
} else {
scores[key] -= 200;
alerts[key].push("Incompatível: Ainda não suportado no core oficial do Arduino (desenvolvimento restrito ao ESP-IDF)");
}
} else if (answers.ecosystem === "advanced_idf") {
scores[key] += 15;
}
});
return { scores, reasons, alerts };
};
// Parametric Direct Filter Matcher
const filteredChips = useMemo(() => {
if (mode !== "filter") return [];
return Object.entries(seriesData).filter(([key, serie]) => {
const seg = serie.seguranca || {};
if (filters.wifi6 && !String(serie.wifi).includes("Wi-Fi 6") && !String(serie.wifi).includes("802.11ax")) return false;
if (filters.wifi5ghz && (!serie.wifi || !String(serie.wifi).includes("5 GHz"))) return false;
if (filters.bluetoothClassic && (!serie.bluetooth || (!String(serie.bluetooth).includes("Classic") && !String(serie.bluetooth).includes("Clássico")))) return false;
if (filters.leAudio && (!serie.bluetooth || !String(serie.bluetooth).includes("LE Audio"))) return false;
if (filters.matter && serie.matter !== "Sim") return false;
if (filters.ethernet && !serie.ethernet && !serie.ethernet_mac) return false;
if (filters.aiAccel && !serie.aceleradores_ia) return false;
if (filters.psram && (!serie.psram_externa || serie.psram_externa === "Não")) return false;
if (filters.mipiDisplayCamera && !serie.mipi_dsi && !serie.mipi_csi && !serie.lcd && !serie.camera) return false;
if (filters.usbOTG && (!serie.usb || !String(serie.usb).includes("OTG"))) return false;
if (filters.canBus && !serie.can) return false;
if (filters.dac && (!serie.dac || serie.dac === "Não")) return false;
if (filters.touch && (!serie.touch || serie.touch === "Não")) return false;
if (filters.arduinoReady && (!serie.arduino_core || !String(serie.arduino_core).startsWith("Sim"))) return false;
if (filters.keyManager && seg.key_manager !== "Sim") return false;
if (filters.eccHardware && (!seg.ecc || seg.ecc === "Não")) return false;
if (filters.ecdsaHardware && (!seg.ecdsa || !String(seg.ecdsa).startsWith("Sim"))) return false;
if (filters.secureBootV2 && (!seg.secure_boot || !String(seg.secure_boot).includes("V2"))) return false;
return true;
});
}, [mode, filters]);
const { scores: allScores, reasons: allReasons, alerts: allAlerts } = useMemo(() => {
if (showResults && Object.values(answers).every(a => a !== null)) {
return calculateRecommendations();
}
return { scores: {}, reasons: {}, alerts: {} };
}, [showResults, answers]);
const recommendations = useMemo(() => {
const entries = Object.entries(allScores)
.filter(([_, score]) => score > 0)
.sort(([, a], [, b]) => b - a);
const maxScore = entries.length > 0 ? entries[0][1] : 1;
return entries.map(([key, score]) => ({
key,
score,
percentage: Math.min(100, Math.round((score / maxScore) * 100)),
}));
}, [allScores]);
const topThree = recommendations.slice(0, 3);
const otherRecommendations = recommendations.slice(3);
const progress = ((currentStep + 1) / questions.length) * 100;
const FILTROS = [
{ key: "wifi6", label: "Wi-Fi 6 (802.11ax)" },
{ key: "wifi5ghz", label: "Wi-Fi dual-band (5 GHz)" },
{ key: "bluetoothClassic", label: "Bluetooth Clássico (A2DP)" },
{ key: "leAudio", label: "Bluetooth LE Audio" },
{ key: "matter", label: "Matter / 802.15.4" },
{ key: "ethernet", label: "Ethernet MAC" },
{ key: "aiAccel", label: "Aceleração vetorial de IA" },
{ key: "psram", label: "Suporte a PSRAM" },
{ key: "mipiDisplayCamera", label: "Telas e câmeras (MIPI/RGB)" },
{ key: "usbOTG", label: "USB nativo OTG" },
{ key: "canBus", label: "Barramento CAN / TWAI" },
{ key: "dac", label: "Conversor DAC" },
{ key: "touch", label: "Touch capacitivo" },
{ key: "arduinoReady", label: "Suporte ao Arduino Core" },
{ key: "eccHardware", label: "Curvas elípticas (ECC)" },
{ key: "ecdsaHardware", label: "Assinatura ECDSA em hardware" },
{ key: "keyManager", label: "Key Manager em hardware" },
{ key: "secureBootV2", label: "Secure Boot V2" },
];
const filtrosAtivos = FILTROS.filter(({ key }) => filters[key]).length;
const limparFiltros = () => setFilters(Object.fromEntries(FILTROS.map(({ key }) => [key, false])));
const ROTULOS_ETAPA = {
category: "Aplicação",
connectivity: "Conectividade",
power: "Alimentação",
hardware: "Periféricos",
memory: "Memória",
ai: "Inteligência artificial",
security: "Segurança",
ecosystem: "Ambiente de desenvolvimento",
};
// O texto das perguntas vem numerado ("1. Qual é..."); a interface já mostra a etapa.
const semNumero = (texto) => texto.replace(/^\d+\.\s*/, "");
const pergunta = questions[currentStep];
return (
<div className="site-canvas min-h-screen">
<Header />
<main id="conteudo">
<PageHero
trail={[{ label: "Seletor de chip" }]}
icon={Sparkles}
label="Seletor inteligente"
title="Qual ESP32 escolher?"
lede="Responda a oito perguntas sobre o projeto, ou marque os recursos obrigatórios, e veja os modelos mais compatíveis com a justificativa técnica."
>
<div role="group" aria-label="Modo de seleção" className="flex flex-wrap gap-2">
<button type="button" onClick={() => setMode("wizard")} aria-pressed={mode === "wizard"} className="chip-btn">
<Sparkles className="h-4 w-4" aria-hidden="true" />
Assistente guiado
</button>
<button type="button" onClick={() => setMode("filter")} aria-pressed={mode === "filter"} className="chip-btn">
<Filter className="h-4 w-4" aria-hidden="true" />
Filtro por recursos
</button>
</div>
</PageHero>
{/* Assistente: pergunta */}
{mode === "wizard" && !showResults && !showSummary && (
<section className="shell pb-6 pt-10" aria-labelledby="pergunta-titulo">
<div className="panel mx-auto max-w-3xl p-5 sm:p-9">
<div className="flex items-center justify-between gap-4 text-sm">
<p className="font-medium text-ink">
Etapa {currentStep + 1} de {questions.length}
<span className="text-muted"> · {ROTULOS_ETAPA[pergunta.id]}</span>
</p>
<span className="tabular-nums text-muted">{Math.round(progress)}%</span>
</div>
<div
role="progressbar"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={Math.round(progress)}
aria-label="Progresso do questionário"
className="mt-3 h-1.5 overflow-hidden rounded-full bg-line"
>
<div className="h-full rounded-full bg-accent transition-[width] duration-500 ease-out" style={{ width: `${progress}%` }} />
</div>
<h2 id="pergunta-titulo" className="section-title mt-8">{semNumero(pergunta.question)}</h2>
<p className="mt-3 text-sm leading-relaxed text-muted sm:text-base">{pergunta.description}</p>
<div role="radiogroup" aria-labelledby="pergunta-titulo" className="mt-7 grid gap-2.5">
{pergunta.options.map((option) => {
const isSelected = currentAnswer === option.value;
return (
<button
key={option.value}
type="button"
role="radio"
aria-checked={isSelected}
onClick={() => handleAnswer(pergunta.id, option.value)}
className={`flex min-h-14 items-center gap-4 rounded-xl border p-3.5 text-left transition-colors sm:p-4 ${
isSelected ? "border-accent bg-accent-soft" : "border-line-strong bg-surface hover:bg-surface-2"
}`}
>
<span className={`grid h-10 w-10 shrink-0 place-items-center rounded-full ${isSelected ? "bg-accent text-accent-contrast" : "bg-surface-2 text-accent"}`}>
{getOptionIcon(pergunta.id, option.value)}
</span>
<span className="grow text-sm font-medium leading-snug text-ink sm:text-base">{option.label}</span>
{isSelected && <Check className="h-5 w-5 shrink-0 text-accent" aria-hidden="true" />}
</button>
);
})}
</div>
<div className="mt-8 flex flex-col-reverse items-stretch gap-3 border-t border-line pt-6 sm:flex-row sm:items-center sm:justify-between">
<button type="button" onClick={goBack} disabled={currentStep === 0} className="btn btn-ghost disabled:cursor-not-allowed disabled:opacity-40">
<ChevronLeft className="h-4 w-4" aria-hidden="true" />
Voltar
</button>
<button type="button" onClick={resetQuiz} className="inline-flex min-h-11 items-center justify-center gap-1.5 text-sm font-medium text-muted hover:text-ink">
<RotateCcw className="h-4 w-4" aria-hidden="true" />
Recomeçar
</button>
<button type="button" onClick={handleNext} disabled={currentAnswer === null} className="btn btn-primary disabled:cursor-not-allowed disabled:opacity-40">
{currentStep === questions.length - 1 ? "Revisar respostas" : "Avançar"}
<ChevronRight className="h-4 w-4" aria-hidden="true" />
</button>
</div>
</div>
</section>
)}
{/* Atalhos por aplicação */}
{mode === "wizard" && !showResults && !showSummary && currentStep === 0 && (
<section className="shell pb-6 pt-10" aria-labelledby="atalhos-titulo">
<h2 id="atalhos-titulo" className="text-base font-semibold text-ink">Ou comece por um perfil pronto</h2>
<p className="mt-1 text-sm text-muted">Aplica as oito respostas de uma vez e mostra o resultado. Você pode ajustar depois.</p>
<div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{PRESETS.map((preset) => (
<button
key={preset.id}
type="button"
onClick={() => applyPreset(preset)}
className="card card-interactive group flex items-start gap-4 p-4 text-left sm:p-5"
>
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-accent-soft text-accent">
{iconMap[`category_${preset.answers.category}`] || <Sparkles className="h-5 w-5" aria-hidden="true" />}
</span>
<span className="min-w-0">
<span className="block font-semibold text-ink">{preset.title}</span>
<span className="mt-0.5 block text-sm text-muted">{preset.description}</span>
<span className="mt-2 inline-flex items-center gap-1 text-sm font-medium text-accent">
Ver recomendação
<ArrowRight className="h-3.5 w-3.5 transition-transform group-hover:translate-x-0.5" aria-hidden="true" />
</span>
</span>
</button>
))}
</div>
</section>
)}
{/* Assistente: revisão */}
{mode === "wizard" && showSummary && !showResults && (
<section className="shell pb-6 pt-10" aria-labelledby="resumo-titulo">
<div className="panel mx-auto max-w-4xl p-5 sm:p-9">
<h2 id="resumo-titulo" className="section-title">Revise suas respostas</h2>
<p className="mt-3 text-sm text-muted sm:text-base">Confira as escolhas antes de calcular a compatibilidade com cada série.</p>
<ul className="mt-7 grid gap-3 md:grid-cols-2">
{questions.map((question) => {
const answer = answers[question.id];
const selectedOption = question.options.find((opt) => opt.value === answer);
return (
<li key={question.id} className="tile flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="text-xs font-medium text-muted">{ROTULOS_ETAPA[question.id]}</p>
{selectedOption && <p className="mt-1 text-sm font-medium leading-snug text-ink">{selectedOption.label}</p>}
</div>
<button
type="button"
onClick={() => {
setCurrentStep(questions.findIndex((q) => q.id === question.id));
setCurrentAnswer(answers[question.id]);
setShowSummary(false);
}}
className="grid h-11 w-11 shrink-0 place-items-center rounded-full text-muted transition-colors hover:bg-surface hover:text-accent"
aria-label={`Editar resposta: ${ROTULOS_ETAPA[question.id]}`}
>
<Edit2 className="h-4 w-4" aria-hidden="true" />
</button>
</li>
);
})}
</ul>
<div className="mt-8 flex flex-col-reverse gap-3 border-t border-line pt-6 sm:flex-row sm:justify-between">
<button
type="button"
onClick={() => {
setCurrentStep(questions.length - 1);
setCurrentAnswer(answers[questions[questions.length - 1].id]);
setShowSummary(false);
}}
className="btn btn-ghost"
>
<ChevronLeft className="h-4 w-4" aria-hidden="true" />
Voltar
</button>
<button type="button" onClick={() => setShowResults(true)} className="btn btn-primary">
<Sparkles className="h-4 w-4" aria-hidden="true" />
Ver recomendações
</button>
</div>
</div>
</section>
)}
{/* Assistente: resultado */}
{mode === "wizard" && showResults && recommendations.length > 0 && (
<section className="shell pb-6 pt-10" aria-labelledby="resultado-titulo">
<div className="flex flex-col justify-between gap-4 sm:flex-row sm:items-end">
<div>
<h2 id="resultado-titulo" className="section-title">Suas recomendações</h2>
<p role="status" className="mt-2 text-sm text-muted">{recommendations.length} modelos compatíveis, do mais ao menos indicado.</p>
</div>
<div className="flex flex-wrap gap-2">
<button type="button" onClick={() => { setShowResults(false); setShowSummary(true); }} className="btn btn-ghost btn-sm">
<Edit2 className="h-4 w-4" aria-hidden="true" />
Ajustar respostas
</button>
<button type="button" onClick={resetQuiz} className="btn btn-ghost btn-sm">
<RotateCcw className="h-4 w-4" aria-hidden="true" />
Recomeçar
</button>
</div>
</div>
<ol className="mt-8 grid gap-4 lg:grid-cols-3">
{topThree.map((rec, index) => {
const seriesKey = rec.key;
const serie = seriesData[seriesKey];
const matchReasons = allReasons[seriesKey] || [];
const chipAlerts = allAlerts[seriesKey] || [];
const primeiro = index === 0;
return (
<li key={seriesKey} className={`card flex flex-col p-5 sm:p-6 ${primeiro ? "border-accent ring-2 ring-accent/20" : ""}`}>
<div className="flex items-center justify-between gap-3">
<span className={`chip ${primeiro ? "chip-accent" : ""}`}>
{primeiro && <Award className="h-3.5 w-3.5" aria-hidden="true" />}
{index + 1}ª recomendação
</span>
<span className="text-sm text-muted">
Afinidade <strong className="font-semibold text-ink">{rec.percentage}%</strong>
</span>
</div>
<h3 className="mt-4 font-display text-2xl font-semibold tracking-[-0.035em] text-ink">{seriesKey}</h3>
<p className="mt-1 line-clamp-2 text-sm text-muted">{serie.descricao}</p>
<div className="mt-5 h-1.5 overflow-hidden rounded-full bg-line" aria-hidden="true">
<div className="h-full rounded-full bg-accent" style={{ width: `${rec.percentage}%` }} />
</div>
<h4 className="mt-6 text-sm font-semibold text-ink">Por que combina</h4>
<ul className="mt-2 space-y-2">
{matchReasons.slice(0, 3).map((reason) => (
<li key={reason} className="flex items-start gap-2 text-sm leading-relaxed text-ink-soft">
<Check className="mt-1 h-3.5 w-3.5 shrink-0 text-ok" aria-hidden="true" />
{reason}
</li>
))}
</ul>
{chipAlerts.length > 0 && (
<div className="callout callout-warn mt-5">
<p className="flex items-center gap-1.5 font-semibold text-ink">
<AlertTriangle className="h-4 w-4 text-gold" aria-hidden="true" />
Pontos de atenção
</p>
<ul className="mt-1.5 list-disc space-y-1 pl-5">
{chipAlerts.slice(0, 2).map((alert) => (
<li key={alert}>{alert}</li>
))}
</ul>
</div>
)}
<dl className="mt-5 grid grid-cols-2 gap-2">
{[
["Arquitetura", serie.arquitetura.split(" ")[0]],
["Clock", serie.frequencia],
["GPIO", `${serie.gpio} pinos`],
["SRAM", serie.memoria_sram],
].map(([rotulo, valor]) => (
<div key={rotulo} className="tile !p-3">
<dt className="text-xs text-muted">{rotulo}</dt>
<dd className="mt-0.5 truncate text-sm font-medium text-ink">{valor}</dd>
</div>
))}
</dl>
<Link href={`/series/${seriesKey}`} className={`btn mt-6 w-full ${primeiro ? "btn-primary" : "btn-ghost"}`}>
Abrir a ficha do {seriesKey}
<ArrowUpRight className="h-4 w-4" aria-hidden="true" />
</Link>
</li>
);
})}
</ol>
<div className="panel mt-10 p-5 sm:p-8">
<div className="flex flex-col justify-between gap-3 sm:flex-row sm:items-center">
<div>
<h3 className="font-display text-xl font-semibold tracking-[-0.03em] text-ink">Os finalistas lado a lado</h3>
<p className="mt-1 text-sm text-muted">As principais especificações das três primeiras recomendações.</p>
</div>
<Link href={`/comparacao?chips=${topThree.map((t) => t.key).join(",")}`} className="inline-flex min-h-11 items-center gap-1.5 text-sm font-medium text-accent hover:text-accent-strong">
Abrir no comparador completo
<ArrowRight className="h-4 w-4" aria-hidden="true" />
</Link>
</div>
<div className="mt-6 overflow-x-auto">
<table className="w-full min-w-[32rem] border-collapse text-left text-sm">
<caption className="sr-only">Comparação das três séries recomendadas</caption>
<thead>
<tr className="border-b border-line">
<th scope="col" className="px-3 py-3 font-medium text-muted">Parâmetro</th>
{topThree.map((rec) => (
<th key={rec.key} scope="col" className="px-3 py-3 font-display text-base font-semibold text-ink">{rec.key}</th>
))}
</tr>
</thead>
<tbody className="divide-y divide-line text-ink-soft">
{[
["Arquitetura", (c) => c.arquitetura],
["Clock", (c) => c.frequencia],
["Wi-Fi", (c) => c.wifi],
["Bluetooth", (c) => c.bluetooth],
["Matter / 802.15.4", (c) => (c.matter === "Sim" ? "Sim" : "Não")],
["Aceleração de IA", (c) => (c.aceleradores_ia ? "Vetorial" : "Não")],
["PSRAM externa", (c) => c.psram_externa || "Não"],
["Arduino Core", (c) => (String(c.arduino_core).startsWith("Sim") ? "Suportado" : "Só ESP-IDF")],
].map(([rotulo, obter]) => (
<tr key={rotulo}>
<th scope="row" className="px-3 py-3 align-top font-medium text-muted">{rotulo}</th>
{topThree.map((rec) => (
<td key={rec.key} className="px-3 py-3 align-top">{obter(seriesData[rec.key])}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</div>
{otherRecommendations.length > 0 && (
<div className="mt-10">
<h3 className="font-display text-xl font-semibold tracking-[-0.03em] text-ink">Outras alternativas avaliadas</h3>
<ul className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{otherRecommendations.map((rec) => (
<li key={rec.key}>
<Link href={`/series/${rec.key}`} className="card card-interactive flex items-center justify-between gap-3 px-4 py-3.5">
<span className="font-display text-lg font-semibold tracking-[-0.03em] text-ink">{rec.key}</span>
<span className="text-sm text-muted">{rec.percentage}%</span>
</Link>
</li>
))}
</ul>
</div>
)}
</section>
)}
{mode === "wizard" && showResults && recommendations.length === 0 && (
<section className="shell pb-6 pt-10">
<div className="card mx-auto max-w-2xl px-6 py-14 text-center">
<HelpCircle className="mx-auto h-10 w-10 text-gold" aria-hidden="true" />
<h2 className="mt-4 font-display text-2xl font-semibold text-ink">Nenhum chip atende a todos os requisitos</h2>
<p className="mx-auto mt-2 max-w-md text-sm text-muted">
Esta combinação tem critérios que nenhuma série cumpre ao mesmo tempo. Flexibilize uma das respostas e tente de novo.
</p>
<div className="mt-6 flex flex-col justify-center gap-3 sm:flex-row">
<button type="button" onClick={() => { setShowResults(false); setShowSummary(true); }} className="btn btn-primary">
<Edit2 className="h-4 w-4" aria-hidden="true" />
Ajustar respostas
</button>
<button type="button" onClick={resetQuiz} className="btn btn-ghost">
<RotateCcw className="h-4 w-4" aria-hidden="true" />
Recomeçar
</button>
</div>
</div>
</section>
)}
{/* Filtro por recursos */}
{mode === "filter" && (
<section className="shell pb-6 pt-10" aria-labelledby="filtro-titulo">
<div className="panel p-5 sm:p-8">
<div className="flex flex-col justify-between gap-3 sm:flex-row sm:items-end">
<div className="max-w-xl">
<h2 id="filtro-titulo" className="section-title">Marque o que é obrigatório</h2>
<p className="mt-2 text-sm text-muted">Só ficam as séries que têm todos os recursos marcados.</p>
</div>
{filtrosAtivos > 0 && (
<button type="button" onClick={limparFiltros} className="inline-flex min-h-11 items-center gap-1.5 text-sm font-medium text-accent hover:text-accent-strong">
<RotateCcw className="h-4 w-4" aria-hidden="true" />
Limpar {filtrosAtivos} {filtrosAtivos === 1 ? "filtro" : "filtros"}
</button>
)}
</div>
<div className="mt-6 flex flex-wrap gap-2" role="group" aria-label="Recursos">
{FILTROS.map(({ key, label }) => (
<button key={key} type="button" onClick={() => setFilters((prev) => ({ ...prev, [key]: !prev[key] }))} aria-pressed={filters[key]} className="chip-btn">
{filters[key] && <Check className="h-4 w-4" aria-hidden="true" />}
{label}
</button>
))}
</div>
</div>
<h3 role="status" aria-live="polite" className="mt-8 text-base font-semibold text-ink">
{filteredChips.length} de {Object.keys(seriesData).length} séries compatíveis
</h3>
{filteredChips.length > 0 ? (
<div className="mt-4 grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{filteredChips.map(([seriesKey, serie]) => (
<Link key={seriesKey} href={`/series/${seriesKey}`} className="card card-interactive group flex flex-col p-5 sm:p-6">
<h4 className="font-display text-2xl font-semibold tracking-[-0.035em] text-ink">{seriesKey}</h4>
<p className="mt-1 line-clamp-2 min-h-[2.9rem] text-sm text-muted">{serie.descricao}</p>
<dl className="mt-4 divide-y divide-line border-y border-line text-sm">
{[
["Wi-Fi", serie.wifi],
["Matter / Thread", serie.matter === "Sim" ? "Sim" : "Não"],
["Clock", serie.frequencia],
["GPIO", `${serie.gpio} pinos`],
["PSRAM", serie.psram_externa || "Não"],
].map(([rotulo, valor]) => (
<div key={rotulo} className="flex items-baseline justify-between gap-4 py-2">
<dt className="text-muted">{rotulo}</dt>
<dd className="truncate text-right font-medium text-ink">{valor}</dd>
</div>
))}
</dl>
<span className="mt-4 inline-flex items-center gap-1 text-sm font-medium text-accent">
Abrir ficha
<ArrowUpRight className="h-4 w-4 transition-transform group-hover:-translate-y-0.5 group-hover:translate-x-0.5" aria-hidden="true" />
</span>
</Link>
))}
</div>
) : (
<div className="card mt-4 px-6 py-14 text-center">
<HelpCircle className="mx-auto h-10 w-10 text-gold" aria-hidden="true" />
<h4 className="mt-4 font-display text-xl font-semibold text-ink">Nenhuma série atende a todos os filtros</h4>
<p className="mx-auto mt-2 max-w-md text-sm text-muted">Desmarque os recursos mais restritivos, como Wi-Fi 5 GHz junto com Ethernet MAC.</p>
<button type="button" onClick={limparFiltros} className="btn btn-primary mt-6">Limpar filtros</button>
</div>
)}
</section>
)}
<section className="shell section" aria-labelledby="proximos-titulo">
<h2 id="proximos-titulo" className="section-title">Próximos passos</h2>
<div className="mt-8 grid gap-4 md:grid-cols-3">
{[
{ href: "/catalogo", icon: ShoppingBag, titulo: "Catálogo de placas", texto: "DevKits e módulos reais, com pinagem e link para a loja." },
{ href: "/comparacao", icon: SlidersHorizontal, titulo: "Comparador lado a lado", texto: "Frequência, GPIOs, ADC/DAC, consumo e segurança em uma tabela." },
{ href: "/glossario", icon: BookOpen, titulo: "Glossário técnico", texto: "Dúvida sobre ULP, SRAM RTC, JTAG ou Matter? Veja as definições." },
].map(({ href, icon: Icon, titulo, texto }) => (
<Link key={href} href={href} className="card card-interactive group flex flex-col p-5 sm:p-6">
<span className="grid h-10 w-10 place-items-center rounded-full bg-accent-soft text-accent">
<Icon className="h-5 w-5" aria-hidden="true" />
</span>
<h3 className="mt-4 font-display text-xl font-semibold tracking-[-0.03em] text-ink">{titulo}</h3>
<p className="mt-2 flex-1 text-sm leading-relaxed text-muted">{texto}</p>
<span className="mt-4 inline-flex items-center gap-1 text-sm font-medium text-accent">
Abrir
<ArrowRight className="h-4 w-4 transition-transform group-hover:translate-x-0.5" aria-hidden="true" />
</span>
</Link>
))}
</div>
</section>
</main>
<Footer />
</div>
);
}