// LinkPass — Central de Ajuda

const FAQS = [
  {
    category: 'Acesso à Plataforma',
    icon: '🔐',
    color: '#06B6D4',
    questions: [
      { q: 'Como faço para acessar minha conta?', a: 'Acesse o site e clique em "Entrar". Utilize seu e-mail corporativo e senha cadastrados pelo administrador da sua instituição.' },
      { q: 'Esqueci minha senha. O que fazer?', a: 'Na tela de login, clique em "Esqueci a senha". Você receberá um link de redefinição no e-mail cadastrado em até 5 minutos.' },
      { q: 'Posso acessar a plataforma pelo celular?', a: 'Sim! A LinkPass possui aplicativo mobile disponível para iOS e Android, além de acesso completo pelo navegador mobile.' },
    ],
  },
  {
    category: 'Controle de Acesso',
    icon: '🚪',
    color: '#818CF8',
    questions: [
      { q: 'Como cadastrar um novo usuário?', a: 'No painel administrativo, acesse "Usuários" > "Novo Cadastro". Preencha os dados, defina o perfil de acesso e salve. O usuário receberá um convite por e-mail.' },
      { q: 'Como funciona o reconhecimento facial?', a: 'O sistema captura e analisa pontos biométricos do rosto em tempo real. O cadastro é feito uma única vez e o acesso é liberado automaticamente nas próximas visitas.' },
      { q: 'Posso definir horários para cada perfil?', a: 'Sim. Você pode configurar janelas de acesso por horário, dia da semana e por local específico para cada usuário ou grupo de usuários.' },
    ],
  },
  {
    category: 'Visitantes e Convites',
    icon: '👥',
    color: '#10B981',
    questions: [
      { q: 'Como autorizar um visitante temporário?', a: 'No aplicativo ou painel, acesse "Visitantes" > "Novo convite". Defina a data, horário e envie o QR Code por WhatsApp ou e-mail.' },
      { q: 'O visitante precisa de aplicativo instalado?', a: 'Não. O visitante recebe um QR Code por link ou imagem, que é lido na catraca ou totem na entrada, sem precisar baixar nada.' },
      { q: 'Posso cadastrar visitantes recorrentes?', a: 'Sim. Para prestadores e visitantes frequentes, você pode criar um cadastro permanente com acesso em dias e horários pré-determinados.' },
    ],
  },
  {
    category: 'Planos e Faturamento',
    icon: '💳',
    color: '#F59E0B',
    questions: [
      { q: 'Como faço upgrade do meu plano?', a: 'Entre em contato com nosso time comercial pelo formulário abaixo ou pelo WhatsApp. Nossos consultores farão a migração sem interrupção do serviço.' },
      { q: 'A LinkPass tem contrato de fidelidade?', a: 'Não. Trabalhamos com contrato mensal sem multa por cancelamento. Para planos anuais, oferecemos desconto especial.' },
      { q: 'Como recebo minha fatura?', a: 'As faturas são enviadas mensalmente por e-mail para o responsável financeiro cadastrado na conta da instituição.' },
    ],
  },
];

function AjudaPage({ onNavigate }) {
  const isMobile = useMobile();
  const [openFaq, setOpenFaq] = React.useState(null);
  const [form, setForm] = React.useState({ nome: '', email: '', assunto: '', mensagem: '' });
  const [sent, setSent] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [erro, setErro] = React.useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setErro('');
    try {
      const res = await fetch('https://formspree.io/f/mvzyalyg', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify(form),
      });
      if (res.ok) setSent(true);
      else setErro('Erro ao enviar. Tente novamente em instantes.');
    } catch {
      setErro('Erro de conexão. Verifique sua internet e tente novamente.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {/* Hero */}
      <section style={{ padding: isMobile ? '110px 20px 60px' : '140px 40px 80px', background: T.bgDeep, position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: 700, height: 400, background: 'radial-gradient(ellipse, rgba(6,182,212,0.1) 0%, transparent 70%)', pointerEvents: 'none' }} />
        <div style={{ maxWidth: 680, margin: '0 auto', textAlign: 'center', position: 'relative' }}>
          <SPBadge color="cyan">❓ Suporte</SPBadge>
          <h1 style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", fontWeight: 800, fontSize: isMobile ? 34 : 52, letterSpacing: '-0.03em', color: T.white, margin: '20px 0 16px', lineHeight: 1.1 }}>
            Central de Ajuda
          </h1>
          <p style={{ fontSize: isMobile ? 15 : 17, color: T.muted, lineHeight: 1.7, maxWidth: 500, margin: '0 auto' }}>
            Encontre respostas para as dúvidas mais comuns ou entre em contato com nossa equipe de suporte.
          </p>
        </div>
      </section>

      {/* Quick access cards */}
      <section style={{ padding: isMobile ? '0 20px 40px' : '0 40px 60px', background: T.bgDeep }}>
        <div style={{ maxWidth: 900, margin: '0 auto', display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4, 1fr)', gap: 16 }}>
          {[
            { icon: '📖', title: 'Primeiros passos', desc: 'Configure sua conta' },
            { icon: '🔑', title: 'Acesso e senha', desc: 'Gerencie credenciais' },
            { icon: '📱', title: 'App mobile', desc: 'iOS e Android' },
            { icon: '💬', title: 'Fale conosco', desc: 'Formulário abaixo' },
          ].map(c => (
            <div key={c.title} style={{ background: T.bgCard, border: `1px solid ${T.border}`, borderRadius: 14, padding: isMobile ? 16 : 22, textAlign: 'center' }}>
              <div style={{ fontSize: isMobile ? 26 : 32, marginBottom: 10 }}>{c.icon}</div>
              <div style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", fontWeight: 700, fontSize: isMobile ? 13 : 14, color: T.white, marginBottom: 4 }}>{c.title}</div>
              <div style={{ fontSize: 12, color: T.muted }}>{c.desc}</div>
            </div>
          ))}
        </div>
      </section>

      {/* FAQs */}
      <section style={{ padding: isMobile ? '24px 20px 60px' : '32px 40px 80px', background: T.bgSurface }}>
        <div style={{ maxWidth: 900, margin: '0 auto' }}>
          <div style={{ textAlign: 'center', marginBottom: isMobile ? 32 : 48 }}>
            <h2 style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", fontWeight: 800, fontSize: isMobile ? 26 : 38, color: T.white, letterSpacing: '-0.02em' }}>
              Perguntas Frequentes
            </h2>
          </div>
          {FAQS.map(cat => (
            <div key={cat.category} style={{ marginBottom: 32 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
                <div style={{ width: 34, height: 34, background: `${cat.color}18`, border: `1px solid ${cat.color}33`, borderRadius: 9, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, flexShrink: 0 }}>{cat.icon}</div>
                <h3 style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", fontWeight: 700, fontSize: isMobile ? 15 : 17, color: T.white }}>{cat.category}</h3>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {cat.questions.map((faq, i) => {
                  const key = `${cat.category}-${i}`;
                  const isOpen = openFaq === key;
                  return (
                    <div key={key} style={{ background: T.bgCard, border: `1px solid ${isOpen ? cat.color + '55' : T.border}`, borderRadius: 12, overflow: 'hidden', transition: 'border 0.2s' }}>
                      <button onClick={() => setOpenFaq(isOpen ? null : key)} style={{ width: '100%', textAlign: 'left', background: 'transparent', border: 'none', cursor: 'pointer', padding: isMobile ? '14px 16px' : '16px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
                        <span style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", fontWeight: 600, fontSize: isMobile ? 14 : 15, color: isOpen ? cat.color : T.white }}>{faq.q}</span>
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ flexShrink: 0, transform: isOpen ? 'rotate(180deg)' : 'none', transition: 'transform 0.2s' }}>
                          <path d="M4 6l4 4 4-4" stroke={isOpen ? cat.color : T.muted} strokeWidth="1.5" strokeLinecap="round" fill="none"/>
                        </svg>
                      </button>
                      {isOpen && (
                        <div style={{ padding: isMobile ? '0 16px 16px' : '0 20px 18px', fontSize: isMobile ? 13 : 14, color: T.mutedLt, lineHeight: 1.75 }}>{faq.a}</div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Contact Form */}
      <section style={{ padding: isMobile ? '60px 20px 80px' : '80px 40px 100px', background: T.bgDeep, position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', bottom: '20%', right: '10%', width: 500, height: 400, background: 'radial-gradient(ellipse, rgba(129,140,248,0.1) 0%, transparent 70%)', pointerEvents: 'none' }} />
        <div style={{ maxWidth: 680, margin: '0 auto', position: 'relative' }}>
          <div style={{ textAlign: 'center', marginBottom: isMobile ? 32 : 40 }}>
            <SPBadge color="indigo">💬 Suporte direto</SPBadge>
            <h2 style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", fontWeight: 800, fontSize: isMobile ? 26 : 36, color: T.white, margin: '16px 0 8px', letterSpacing: '-0.02em' }}>
              Não encontrou o que procura?
            </h2>
            <p style={{ fontSize: isMobile ? 14 : 16, color: T.muted }}>Nossa equipe responde em até 24 horas úteis.</p>
          </div>

          <div style={{ background: T.bgCard, border: `1px solid ${T.border}`, borderRadius: 20, padding: isMobile ? 24 : 40, boxShadow: '0 24px 60px rgba(0,0,0,0.4)' }}>
            {sent ? (
              <div style={{ textAlign: 'center', padding: '40px 0' }}>
                <div style={{ fontSize: 52, marginBottom: 16 }}>✅</div>
                <div style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", fontWeight: 800, fontSize: 22, color: T.white, marginBottom: 10 }}>Mensagem enviada!</div>
                <p style={{ color: T.muted, fontSize: 15, lineHeight: 1.65 }}>Nossa equipe de suporte entrará em contato em até 24 horas úteis.</p>
              </div>
            ) : (
              <form onSubmit={handleSubmit}>
                <div style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", fontWeight: 800, fontSize: isMobile ? 18 : 20, color: T.white, marginBottom: 22 }}>Abrir chamado de suporte</div>
                <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14, marginBottom: 14 }}>
                  {[
                    { id: 'nome', label: 'Seu nome', placeholder: 'Nome completo', type: 'text' },
                    { id: 'email', label: 'E-mail', placeholder: 'voce@empresa.com.br', type: 'email' },
                  ].map(field => (
                    <div key={field.id}>
                      <label style={{ fontSize: 12, fontWeight: 600, color: T.muted, textTransform: 'uppercase', letterSpacing: '0.07em', display: 'block', marginBottom: 6 }}>{field.label}</label>
                      <input type={field.type} placeholder={field.placeholder} required value={form[field.id]} onChange={e => setForm(f => ({ ...f, [field.id]: e.target.value }))}
                        style={{ width: '100%', background: T.bgSurface, border: `1px solid ${T.border}`, borderRadius: 9, padding: '11px 14px', fontSize: 14, color: T.white, fontFamily: 'Inter, sans-serif', outline: 'none', boxSizing: 'border-box', transition: 'border 0.15s' }}
                        onFocus={e => e.target.style.borderColor = T.cyan} onBlur={e => e.target.style.borderColor = T.border} />
                    </div>
                  ))}
                </div>
                <div style={{ marginBottom: 14 }}>
                  <label style={{ fontSize: 12, fontWeight: 600, color: T.muted, textTransform: 'uppercase', letterSpacing: '0.07em', display: 'block', marginBottom: 6 }}>Assunto</label>
                  <select value={form.assunto} onChange={e => setForm(f => ({ ...f, assunto: e.target.value }))}
                    style={{ width: '100%', background: T.bgSurface, border: `1px solid ${T.border}`, borderRadius: 9, padding: '11px 14px', fontSize: 14, color: form.assunto ? T.white : T.muted, fontFamily: 'Inter, sans-serif', outline: 'none', boxSizing: 'border-box' }}>
                    <option value="">Selecione o assunto...</option>
                    {['Problema técnico', 'Dúvida sobre funcionalidade', 'Acesso e credenciais', 'Faturamento e planos', 'Outro'].map(o => <option key={o} value={o}>{o}</option>)}
                  </select>
                </div>
                <div style={{ marginBottom: 22 }}>
                  <label style={{ fontSize: 12, fontWeight: 600, color: T.muted, textTransform: 'uppercase', letterSpacing: '0.07em', display: 'block', marginBottom: 6 }}>Descreva sua dúvida</label>
                  <textarea placeholder="Explique com detalhes o que está acontecendo..." value={form.mensagem} onChange={e => setForm(f => ({ ...f, mensagem: e.target.value }))} rows={4} required
                    style={{ width: '100%', background: T.bgSurface, border: `1px solid ${T.border}`, borderRadius: 9, padding: '11px 14px', fontSize: 14, color: T.white, fontFamily: 'Inter, sans-serif', outline: 'none', resize: 'vertical', boxSizing: 'border-box', transition: 'border 0.15s' }}
                    onFocus={e => e.target.style.borderColor = T.cyan} onBlur={e => e.target.style.borderColor = T.border} />
                </div>
                {erro && (
                  <div style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.3)', borderRadius: 9, padding: '10px 14px', fontSize: 13, color: '#FCA5A5', marginBottom: 14 }}>{erro}</div>
                )}
                <button type="submit" disabled={loading} style={{
                  width: '100%', background: loading ? '#0891B2' : T.cyan,
                  color: '#07091A', fontWeight: 700, fontSize: 15,
                  border: 'none', borderRadius: 10, padding: '14px 18px',
                  cursor: loading ? 'wait' : 'pointer',
                  fontFamily: 'Inter, sans-serif',
                  boxShadow: '0 0 20px rgba(6,182,212,0.3)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                  transition: 'all 0.15s',
                }}>
                  {loading ? (
                    <>
                      <div style={{ width: 14, height: 14, border: '2px solid rgba(7,9,26,0.3)', borderTopColor: '#07091A', borderRadius: '50%', animation: 'lp-spin 0.7s linear infinite' }} />
                      Enviando...
                    </>
                  ) : 'Enviar mensagem →'}
                </button>
                <style>{`@keyframes lp-spin { to { transform: rotate(360deg) } }`}</style>
              </form>
            )}
          </div>

          {/* Contact info */}
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(3, 1fr)', gap: 16, marginTop: 24 }}>
            {[
              { icon: '✉️', label: 'E-mail', value: 'suporte@linkpasstech.com.br' },
              { icon: '📞', label: 'Telefone', value: '(91) 98942-8497' },
              { icon: '🕐', label: 'Atendimento', value: 'Seg–Sex, 8h às 18h' },
            ].map(item => (
              <div key={item.label} style={{ background: T.bgCard, border: `1px solid ${T.border}`, borderRadius: 12, padding: 16, display: 'flex', alignItems: 'center', gap: 12 }}>
                <span style={{ fontSize: 20 }}>{item.icon}</span>
                <div>
                  <div style={{ fontSize: 11, color: T.muted, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.07em' }}>{item.label}</div>
                  <div style={{ fontSize: isMobile ? 12 : 13, color: T.white, marginTop: 2 }}>{item.value}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </>
  );
}

Object.assign(window, { AjudaPage });
