/* global React, ReactDOM, TweaksPanel, TweakSection, TweakRadio, TweakColor, TweakSelect, useTweaks */
const { useState, useEffect } = React;

// ---------- SSO icons (multi-color brand glyphs) ----------
const ProviderIcon = {
  google: (
    <svg viewBox="0 0 48 48" aria-hidden="true">
      <path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3c-1.6 4.7-6 8-11.3 8a12 12 0 1 1 0-24c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7A20 20 0 1 0 24 44c11 0 19.7-9 19.7-20 0-1.3-.1-2.4-.4-3.5z"/>
      <path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7A20 20 0 0 0 6.3 14.7z"/>
      <path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.2L31 33.6c-2 1.4-4.4 2.4-7 2.4-5.3 0-9.7-3.4-11.3-8L6.2 33A20 20 0 0 0 24 44z"/>
      <path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.2 4.1-4.3 5.6l6.4 4.8c-.4.4 6.6-4.9 6.6-14.4 0-1.3-.1-2.4-.4-3.5z"/>
    </svg>
  ),
  microsoft: (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path fill="#F25022" d="M1 1h10v10H1z"/>
      <path fill="#7FBA00" d="M13 1h10v10H13z"/>
      <path fill="#00A4EF" d="M1 13h10v10H1z"/>
      <path fill="#FFB900" d="M13 13h10v10H13z"/>
    </svg>
  ),
  linkedin: (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <rect width="24" height="24" rx="3" fill="#0A66C2"/>
      <path fill="#fff" d="M7.1 9.5h2.7v8.2H7.1zM8.45 5.8a1.55 1.55 0 1 1 0 3.1 1.55 1.55 0 0 1 0-3.1zM11.4 9.5h2.6v1.1c.4-.7 1.4-1.4 2.7-1.4 2.9 0 3.4 1.9 3.4 4.3v4.2h-2.7v-3.7c0-.9 0-2-1.3-2s-1.5 1-1.5 2v3.7h-2.7V9.5z"/>
    </svg>
  ),
  github: (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path fill="#f1efea" d="M12 .5A12 12 0 0 0 0 12.6c0 5.4 3.4 9.9 8.2 11.5.6.1.8-.3.8-.6v-2.1c-3.3.7-4-1.6-4-1.6-.5-1.4-1.3-1.8-1.3-1.8-1.1-.8.1-.7.1-.7 1.2.1 1.8 1.2 1.8 1.2 1.1 1.9 2.9 1.4 3.6 1 .1-.8.4-1.4.8-1.7-2.6-.3-5.4-1.3-5.4-6 0-1.3.5-2.4 1.2-3.2-.1-.3-.5-1.5.1-3.2 0 0 1-.3 3.3 1.2a11.4 11.4 0 0 1 6 0c2.3-1.6 3.3-1.2 3.3-1.2.7 1.7.2 2.9.1 3.2.8.8 1.2 1.9 1.2 3.2 0 4.7-2.8 5.7-5.4 6 .4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6A12.1 12.1 0 0 0 24 12.6 12 12 0 0 0 12 .5z"/>
    </svg>
  ),
  apple: (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path fill="#f1efea" d="M16.4 12.7c0-2.6 2.1-3.9 2.2-3.9-1.2-1.7-3-2-3.7-2-1.6-.2-3 .9-3.8.9-.8 0-2-.9-3.3-.9-1.7 0-3.3 1-4.2 2.5-1.8 3.1-.5 7.7 1.3 10.2.8 1.2 1.8 2.6 3.2 2.6 1.3 0 1.8-.8 3.3-.8 1.5 0 2 .8 3.3.8 1.4 0 2.3-1.2 3.1-2.5.7-1.1 1.3-2.3 1.6-3.6-2-.8-3-3-3-5.3zM14 4.8c.7-.9 1.2-2 1.1-3.2-1 0-2.3.7-3 1.5-.7.8-1.3 2-1.1 3.1 1.2.1 2.3-.6 3-1.4z"/>
    </svg>
  ),
};

const PROVIDERS = [
  { id: 'google', label: 'Continuar com Google' },
  { id: 'microsoft', label: 'Continuar com Microsoft' },
  { id: 'linkedin', label: 'Continuar com LinkedIn' },
  { id: 'github', label: 'Continuar com GitHub' },
  { id: 'apple', label: 'Continuar com Apple' },
];

// ---------- Registration form ----------
function RegisterForm() {
  const [track, setTrack] = useState('pro'); // 'pro' | 'empresa'
  const [submitted, setSubmitted] = useState(false);
  const [form, setForm] = useState({
    name: '', email: '', role: 'senior-eng',
    company: '', teamSize: '6-20', notes: ''
  });

  // listen for track-CTA clicks elsewhere on page
  useEffect(() => {
    const handler = (e) => {
      const a = e.target.closest('[data-track]');
      if (a) setTrack(a.dataset.track);
    };
    document.addEventListener('click', handler);
    return () => document.removeEventListener('click', handler);
  }, []);

  const handleProvider = (id) => {
    setTimeout(() => setSubmitted(true), 400);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!form.email || !form.name) return;
    if (track === 'empresa' && !form.company) return;
    setSubmitted(true);
  };

  if (submitted) {
    return (
      <div className="form-card">
        <div className="form-success">
          <div className="check">
            <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M4 12l5 5L20 6"/></svg>
          </div>
          <h3>{track === 'empresa' ? 'Briefing recebido.' : 'Interesse registrado.'}</h3>
          <p>
            {track === 'empresa'
              ? 'Rafael responde direto em até 2 dias úteis com uma agenda de briefing e os próximos passos.'
              : 'Você recebe a data oficial e o link de inscrição assim que a turma for fechada. Sem newsletter, sem ruído.'}
          </p>
          <div style={{marginTop: 24, paddingTop: 18, borderTop: '1px solid var(--line)', fontFamily: '"Geist Mono", monospace', fontSize: 11, letterSpacing: '.12em', color: 'var(--dim)', textTransform: 'uppercase'}}>
            {track === 'empresa'
              ? <>Protocolo <span style={{color: 'var(--accent)'}}>#EMP-{String(Math.floor(Math.random()*900)+100)}</span></>
              : <>Posição na fila <span style={{color: 'var(--accent)'}}>#0{Math.floor(Math.random()*40)+12}</span></>}
          </div>
        </div>
      </div>
    );
  }

  const isEmpresa = track === 'empresa';

  return (
    <form className="form-card" onSubmit={handleSubmit}>
      <div className="track-toggle" role="tablist" aria-label="Trilha">
        <button type="button" className={track === 'pro' ? 'active' : ''} onClick={() => setTrack('pro')}>Profissional</button>
        <button type="button" className={track === 'empresa' ? 'active' : ''} onClick={() => setTrack('empresa')}>Empresa</button>
      </div>

      <div className="label">{isEmpresa ? 'Entrar com seu login corporativo' : 'Entrar com login profissional'}</div>
      <div className="providers">
        {PROVIDERS.slice(0, 4).map(p => (
          <button type="button" key={p.id} className="prov" onClick={() => handleProvider(p.id)}>
            {ProviderIcon[p.id]}
            <span className="name">{p.label.replace('Continuar com ', '')}</span>
          </button>
        ))}
      </div>
      <button type="button" className="prov" style={{width:'100%'}} onClick={() => handleProvider('apple')}>
        {ProviderIcon.apple}
        <span className="name">Apple</span>
      </button>

      <div className="divider">ou com e-mail</div>

      <div className="field">
        <label htmlFor="name">{isEmpresa ? 'Seu nome' : 'Nome'}</label>
        <input id="name" type="text" placeholder={isEmpresa ? 'Quem está abrindo essa conversa?' : 'Como te chamamos?'} value={form.name} onChange={e => setForm({...form, name: e.target.value})}/>
      </div>
      <div className="field">
        <label htmlFor="email">{isEmpresa ? 'E-mail corporativo' : 'E-mail profissional'}</label>
        <input id="email" type="email" placeholder="voce@empresa.com" value={form.email} onChange={e => setForm({...form, email: e.target.value})}/>
      </div>
      <div className="field">
        <label htmlFor="role">{isEmpresa ? 'Cargo' : 'Função atual'}</label>
        <select id="role" value={form.role} onChange={e => setForm({...form, role: e.target.value})}>
          {isEmpresa ? (
            <>
              <option value="cto">CTO / VP Engineering</option>
              <option value="em">Engineering Manager / Head</option>
              <option value="tech-lead">Tech Lead / Staff</option>
              <option value="founder">Founder</option>
              <option value="ops">L&D · People · Operações</option>
              <option value="other">Outro</option>
            </>
          ) : (
            <>
              <option value="senior-eng">Engenheiro(a) Sênior</option>
              <option value="staff">Staff / Principal</option>
              <option value="tech-lead">Tech Lead</option>
              <option value="em">Engineering Manager</option>
              <option value="fullstack">Fullstack</option>
              <option value="other">Outro</option>
            </>
          )}
        </select>
      </div>

      {isEmpresa && (
        <>
          <div className="field">
            <label htmlFor="company">Empresa</label>
            <input id="company" type="text" placeholder="Nome da empresa" value={form.company} onChange={e => setForm({...form, company: e.target.value})}/>
          </div>
          <div className="field">
            <label htmlFor="teamSize">Tamanho do time de engenharia</label>
            <select id="teamSize" value={form.teamSize} onChange={e => setForm({...form, teamSize: e.target.value})}>
              <option value="1-5">1 – 5 pessoas</option>
              <option value="6-20">6 – 20 pessoas</option>
              <option value="21-50">21 – 50 pessoas</option>
              <option value="51-150">51 – 150 pessoas</option>
              <option value="150+">150 +</option>
            </select>
          </div>
          <div className="field">
            <label htmlFor="notes">Desafio principal (opcional)</label>
            <input id="notes" type="text" placeholder="Onde o time trava hoje?" value={form.notes} onChange={e => setForm({...form, notes: e.target.value})}/>
          </div>
        </>
      )}

      <button type="submit" className="submit">
        {isEmpresa ? 'Enviar briefing' : 'Registrar interesse'}
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M3 8h10M9 4l4 4-4 4"/></svg>
      </button>
      <div className="fineprint">
        {isEmpresa
          ? 'Resposta direta do instrutor em até 2 dias úteis. Sem intermediários.'
          : 'Sem spam. Você recebe a data e um link único de inscrição.'}
      </div>
    </form>
  );
}

ReactDOM.createRoot(document.getElementById('form-mount')).render(<RegisterForm />);

// ---------- Animated terminal ----------
const termMount = document.getElementById('term-mount');
if (termMount) ReactDOM.createRoot(termMount).render(<AnimatedTerminal />);

// ---------- Last updated stamp ----------
const stamp = new Date().toLocaleDateString('pt-BR', { day: '2-digit', month: 'short', year: 'numeric' });
document.getElementById('lastUpd').textContent = stamp.toUpperCase();

// ---------- Tweaks ----------
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "accent": "#D97757",
  "density": "default",
  "headlineStyle": "mixed"
}/*EDITMODE-END*/;

function Tweaks() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', t.theme);
    document.documentElement.setAttribute('data-density', t.density);
    document.documentElement.style.setProperty('--accent', t.accent);
    // headline variations
    const h1 = document.querySelector('.h1');
    if (h1) {
      if (t.headlineStyle === 'plain') {
        h1.innerHTML = 'Não é um curso de prompts.<br/>É sobre rearquitetar<br/>como você entrega.';
      } else if (t.headlineStyle === 'serif') {
        h1.innerHTML = '<em>Não</em> é um curso de <span class="strike">prompts</span>.<br/><em>É sobre rearquitetar</em><br/>como você <em>entrega</em>.';
      } else {
        h1.innerHTML = 'Não é um curso de <span class="strike">prompts</span>.<br/>É sobre <em>rearquitetar</em><br/>como você entrega.';
      }
    }
  }, [t]);

  return (
    <TweaksPanel title="Tweaks" subtitle="Engenharia Composta · variações">
      <TweakSection title="Tema">
        <TweakRadio label="Modo" value={t.theme} options={[
          { value: 'dark', label: 'Dark' },
          { value: 'light', label: 'Light' },
        ]} onChange={v => setTweak('theme', v)} />
      </TweakSection>

      <TweakSection title="Acento">
        <TweakColor label="Cor" value={t.accent} options={['#D97757','#FF6B35','#E8B931','#5EB4A4','#7C9CFF']} onChange={v => setTweak('accent', v)} />
      </TweakSection>

      <TweakSection title="Densidade">
        <TweakRadio label="Respiro" value={t.density} options={[
          { value: 'compact', label: 'Compacto' },
          { value: 'default', label: 'Padrão' },
          { value: 'spacious', label: 'Amplo' },
        ]} onChange={v => setTweak('density', v)} />
      </TweakSection>

      <TweakSection title="Tipografia do título">
        <TweakSelect label="Estilo" value={t.headlineStyle} options={[
          { value: 'mixed', label: 'Misto (sans + itálico)' },
          { value: 'serif', label: 'Editorial (mais itálico)' },
          { value: 'plain', label: 'Sans puro' },
        ]} onChange={v => setTweak('headlineStyle', v)} />
      </TweakSection>
    </TweaksPanel>
  );
}

const tweaksMount = document.createElement('div');
document.body.appendChild(tweaksMount);
ReactDOM.createRoot(tweaksMount).render(<Tweaks />);
