/* global React */

// ===== Configurator — gamified project builder =====
const CONFIG_TYPES = [
  { id: 'app',     label: 'App mobile',  desc: 'iOS + Android com publicação inclusa',  price: 18000, weeks: 6, icon: '📱' },
  { id: 'site',    label: 'Site / Landing', desc: 'Institucional, landing ou e-commerce', price: 6000,  weeks: 2, icon: '🌐' },
  { id: 'sistema', label: 'Sistema web',  desc: 'SaaS, painel admin, plataforma sob medida', price: 24000, weeks: 8, icon: '⚙️' },
];

const CONFIG_FEATURES = [
  { id: 'login',    label: 'Login & cadastro',      desc: 'Email, Google, Apple, biometria',   price: 1500, weeks: 0.5, icon: '🔐' },
  { id: 'pay',      label: 'Pagamentos',            desc: 'PIX, cartão, assinatura',           price: 3500, weeks: 1.0, icon: '💳' },
  { id: 'push',     label: 'Push & notificações',   desc: 'Engajamento e re-engajamento',      price: 1200, weeks: 0.5, icon: '🔔' },
  { id: 'chat',     label: 'Chat em tempo real',    desc: 'Conversas entre usuários',          price: 4000, weeks: 1.5, icon: '💬' },
  { id: 'maps',     label: 'Mapas & GPS',           desc: 'Geolocalização, rotas, busca',      price: 2500, weeks: 1.0, icon: '📍' },
  { id: 'ai',       label: 'IA & assistente',       desc: 'Chatbot, recomendação, automação',  price: 5000, weeks: 1.5, icon: '🤖' },
  { id: 'admin',    label: 'Painel admin',          desc: 'Gestão, métricas, controle total',  price: 4500, weeks: 2.0, icon: '📊' },
  { id: 'integ',    label: 'Integrações',           desc: 'CRM, ERP, planilhas, APIs',         price: 3000, weeks: 1.0, icon: '🔌' },
  { id: 'market',   label: 'Marketplace',           desc: 'Vendedores, comissão, repasse',     price: 8000, weeks: 2.0, icon: '🛒' },
  { id: 'sched',    label: 'Agendamento',           desc: 'Calendário, reservas, confirmação', price: 2500, weeks: 1.0, icon: '📅' },
];

const CONFIG_STYLES = [
  { id: 'minimal', label: 'Minimalista', desc: 'Limpo, espaçoso, foco no conteúdo',   sample: ['#fafafa','#0a0a0a','#0066ff'] },
  { id: 'modern',  label: 'Moderno',     desc: 'Cards arredondados, animações suaves', sample: ['#1a1a2e','#e94560','#f5f5f5'] },
  { id: 'bold',    label: 'Ousado',      desc: 'Tipografia gigante, cores fortes',     sample: ['#ff3d00','#ffeb3b','#0a0a0a'] },
  { id: 'premium', label: 'Premium',     desc: 'Preto, dourado, tipografia elegante',  sample: ['#0a0a0a','#c9a961','#ffffff'] },
];

const PHONE = '11 96710-6583';
const PHONE_DIGITS = '5511967106583';

function Configurator() {
  const [step, setStep] = React.useState(0); // 0..3 = pick steps, 4 = success
  const [type, setType] = React.useState(null);
  const [features, setFeatures] = React.useState(new Set());
  const [style, setStyle] = React.useState(null);
  const [nome, setNome] = React.useState('');
  const [contato, setContato] = React.useState('');
  const [obs, setObs] = React.useState('');

  // Derived estimate
  const basePrice = type ? CONFIG_TYPES.find(t => t.id === type).price : 0;
  const baseWeeks = type ? CONFIG_TYPES.find(t => t.id === type).weeks : 0;
  const featPrice = [...features].reduce((s, id) => s + CONFIG_FEATURES.find(f => f.id === id).price, 0);
  const featWeeks = [...features].reduce((s, id) => s + CONFIG_FEATURES.find(f => f.id === id).weeks, 0);
  const totalPrice = basePrice + featPrice;
  const totalWeeks = baseWeeks + featWeeks;
  const score = (type ? 25 : 0) + features.size * 5 + (style ? 15 : 0) + (nome && contato ? 10 : 0);

  const toggleFeature = (id) => {
    setFeatures((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  const next = () => setStep((s) => Math.min(4, s + 1));
  const back = () => setStep((s) => Math.max(0, s - 1));

  const canAdvance =
    (step === 0 && !!type) ||
    (step === 1) || // features optional
    (step === 2 && !!style) ||
    (step === 3 && !!nome && !!contato);

  const submit = (e) => {
    e?.preventDefault();
    setStep(4);
    fireConfetti();
  };

  const reset = () => {
    setStep(0); setType(null); setFeatures(new Set()); setStyle(null);
    setNome(''); setContato(''); setObs('');
  };

  const progress = step === 4 ? 100 : (step / 4) * 100;

  return (
    <div className="config-card">
      {/* Header */}
      <div className="config-head">
        <div className="config-title">
          <span className="config-badge mono">// PROJETO.SETUP</span>
          <h3>Monte seu projeto em 60s</h3>
        </div>
        <div className="config-score">
          <span className="mono lab">SCORE</span>
          <span className="num"><AnimatedCount value={score} /></span>
        </div>
      </div>

      <div className="config-progress">
        <div className="config-progress-bar" style={{ width: `${progress}%` }}></div>
        <div className="config-steps">
          {['Tipo','Recursos','Estilo','Contato'].map((lab, i) => (
            <span key={i} className={`config-step ${step >= i ? 'done' : ''} ${step === i ? 'active' : ''}`}>
              <span className="dot"></span>
              <span className="lab">{i + 1}. {lab}</span>
            </span>
          ))}
        </div>
      </div>

      {/* Estimate row */}
      <div className="config-estimate">
        <div className="estimate-item">
          <span className="mono lab">// investimento</span>
          <span className="val">
            R$ <AnimatedCount value={totalPrice} format="price" />
          </span>
        </div>
        <div className="estimate-item">
          <span className="mono lab">// prazo</span>
          <span className="val">
            <AnimatedCount value={totalWeeks} format="weeks" /> sem
          </span>
        </div>
        <div className="estimate-item">
          <span className="mono lab">// features</span>
          <span className="val">{features.size}/10</span>
        </div>
      </div>

      {/* Step body */}
      <div className="config-body">
        {step === 0 && <StepType selected={type} onPick={(id) => { setType(id); setTimeout(next, 200); }} />}
        {step === 1 && <StepFeatures selected={features} onToggle={toggleFeature} />}
        {step === 2 && <StepStyle selected={style} onPick={(id) => { setStyle(id); setTimeout(next, 200); }} />}
        {step === 3 && (
          <StepContact
            nome={nome} setNome={setNome}
            contato={contato} setContato={setContato}
            obs={obs} setObs={setObs}
            onSubmit={submit}
          />
        )}
        {step === 4 && (
          <StepSuccess
            type={type} features={features} style={style}
            nome={nome} contato={contato}
            totalPrice={totalPrice} totalWeeks={totalWeeks}
            onReset={reset}
          />
        )}
      </div>

      {/* Nav */}
      {step < 4 && (
        <div className="config-nav">
          {step > 0 ? (
            <button className="config-nav-btn ghost" onClick={back}>
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M11 19l-7-7 7-7" /></svg>
              Voltar
            </button>
          ) : <span></span>}
          {step < 3 ? (
            <button className="config-nav-btn primary" onClick={next} disabled={!canAdvance}>
              {step === 1 ? `Avançar com ${features.size}` : 'Próximo'}
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
            </button>
          ) : null}
        </div>
      )}
    </div>
  );
}

// ===== Step components =====
function StepType({ selected, onPick }) {
  return (
    <div className="step-pane">
      <div className="step-q">// Qual o tipo do projeto?</div>
      <div className="opt-stack">
        {CONFIG_TYPES.map((t) => (
          <button
            key={t.id}
            className={`opt-card type ${selected === t.id ? 'on' : ''}`}
            onClick={() => onPick(t.id)}
          >
            <span className="opt-icon">{t.icon}</span>
            <div className="opt-meta">
              <span className="opt-label">{t.label}</span>
              <span className="opt-desc">{t.desc}</span>
            </div>
            <span className="opt-price mono">
              a partir de R$ {t.price.toLocaleString('pt-BR')}
            </span>
          </button>
        ))}
      </div>
    </div>
  );
}

function StepFeatures({ selected, onToggle }) {
  return (
    <div className="step-pane">
      <div className="step-q">// Que funcionalidades você precisa? <span style={{ color: 'var(--accent-2)' }}>multi-select</span></div>
      <div className="opt-grid">
        {CONFIG_FEATURES.map((f) => (
          <button
            key={f.id}
            className={`opt-card feat ${selected.has(f.id) ? 'on' : ''}`}
            onClick={() => onToggle(f.id)}
          >
            <span className="opt-icon">{f.icon}</span>
            <span className="opt-label">{f.label}</span>
            <span className="opt-desc">{f.desc}</span>
            <span className="opt-check" aria-hidden="true">
              {selected.has(f.id) ? '✓' : '+'}
            </span>
            <span className="opt-price mono">
              +R$ {f.price.toLocaleString('pt-BR')} · +{f.weeks}sem
            </span>
          </button>
        ))}
      </div>
      <div className="step-hint mono">// pule essa etapa se ainda não decidiu — pode ajustar depois</div>
    </div>
  );
}

function StepStyle({ selected, onPick }) {
  return (
    <div className="step-pane">
      <div className="step-q">// Que estilo visual faz mais sentido?</div>
      <div className="opt-grid two">
        {CONFIG_STYLES.map((s) => (
          <button
            key={s.id}
            className={`opt-card style ${selected === s.id ? 'on' : ''}`}
            onClick={() => onPick(s.id)}
          >
            <span className="style-swatches">
              {s.sample.map((c, i) => (
                <span key={i} style={{ background: c }}></span>
              ))}
            </span>
            <span className="opt-label">{s.label}</span>
            <span className="opt-desc">{s.desc}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

function StepContact({ nome, setNome, contato, setContato, obs, setObs, onSubmit }) {
  return (
    <form className="step-pane step-contact" onSubmit={onSubmit}>
      <div className="step-q">// Tá quase. Como a gente fala com você?</div>
      <div className="config-form-row">
        <label className="mono">nome</label>
        <input value={nome} onChange={(e) => setNome(e.target.value)} required placeholder="Como podemos te chamar?" />
      </div>
      <div className="config-form-row">
        <label className="mono">e-mail ou whatsapp</label>
        <input value={contato} onChange={(e) => setContato(e.target.value)} required placeholder="você@empresa.com ou (11) 9..." />
      </div>
      <div className="config-form-row">
        <label className="mono">algo a acrescentar? <span style={{ opacity: 0.5 }}>(opcional)</span></label>
        <textarea value={obs} onChange={(e) => setObs(e.target.value)} placeholder="referências, prazo apertado, dúvidas..." />
      </div>
      <button type="submit" className="config-submit" disabled={!nome || !contato}>
        <span>Enviar projeto configurado</span>
        <span className="config-submit-arrow">
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M5 12h14M13 5l7 7-7 7" />
          </svg>
        </span>
      </button>
    </form>
  );
}

function StepSuccess({ type, features, style, nome, totalPrice, totalWeeks, onReset }) {
  const typeLabel = type ? CONFIG_TYPES.find(t => t.id === type).label : '—';
  const styleLabel = style ? CONFIG_STYLES.find(s => s.id === style).label : '—';
  const featList = [...features].map(id => CONFIG_FEATURES.find(f => f.id === id)?.label).filter(Boolean);

  return (
    <div className="step-pane step-success">
      <div className="success-emoji">🚀</div>
      <h3>Projeto recebido{nome ? `, ${nome.split(' ')[0]}` : ''}!</h3>
      <p className="success-lede">
        A gente analisa sua configuração e volta em <strong>até 48 horas</strong> no
        contato que você passou, com uma proposta detalhada.
      </p>
      <div className="success-summary">
        <div className="summary-row"><span className="mono">// tipo</span><span>{typeLabel}</span></div>
        <div className="summary-row">
          <span className="mono">// recursos</span>
          <span>{featList.length > 0 ? featList.join(', ') : 'a definir'}</span>
        </div>
        <div className="summary-row"><span className="mono">// estilo</span><span>{styleLabel}</span></div>
        <div className="summary-row big"><span className="mono">// investimento estimado</span><span>R$ {totalPrice.toLocaleString('pt-BR')}</span></div>
        <div className="summary-row big"><span className="mono">// prazo estimado</span><span>{totalWeeks.toFixed(1).replace('.0','').replace('.',',')} semanas</span></div>
      </div>
      <div className="success-actions">
        <a
          className="config-nav-btn primary"
          target="_blank" rel="noreferrer"
          href={`https://wa.me/${PHONE_DIGITS}?text=${encodeURIComponent(`Olá! Acabei de configurar um projeto no site: ${typeLabel}, ${featList.length} recursos, estilo ${styleLabel}. Investimento estimado: R$ ${totalPrice.toLocaleString('pt-BR')}, prazo: ~${totalWeeks} semanas.`)}`}
        >
          Continuar no WhatsApp
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
        </a>
        <button className="config-nav-btn ghost" onClick={onReset}>
          Configurar outro
        </button>
      </div>
    </div>
  );
}

// ===== Animated counter (inline, no observer needed — driven by prop) =====
function AnimatedCount({ value, format }) {
  const [v, setV] = React.useState(value);
  const fromRef = React.useRef(value);
  React.useEffect(() => {
    const from = fromRef.current;
    const to = value;
    const dur = 450;
    const start = performance.now();
    let raf;
    const tick = (t) => {
      const p = Math.min(1, (t - start) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      setV(from + (to - from) * eased);
      if (p < 1) raf = requestAnimationFrame(tick);
      else { setV(to); fromRef.current = to; }
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [value]);
  if (format === 'price') {
    return <>{Math.round(v).toLocaleString('pt-BR')}</>;
  }
  if (format === 'weeks') {
    return <>{v.toFixed(1).replace('.0','').replace('.',',')}</>;
  }
  return <>{Math.round(v)}</>;
}

// ===== Confetti =====
function fireConfetti() {
  const colors = ['#0066ff', '#ffd60a', '#06d6a0', '#ef476f', '#ffffff'];
  for (let i = 0; i < 80; i++) {
    const p = document.createElement('div');
    p.className = 'confetti-piece';
    const c = colors[i % colors.length];
    const sz = 6 + Math.random() * 8;
    p.style.cssText = `
      position: fixed;
      left: ${50 + (Math.random() - 0.5) * 30}vw;
      top: 40vh;
      width: ${sz}px;
      height: ${sz * 0.4}px;
      background: ${c};
      z-index: 999;
      pointer-events: none;
      transform: rotate(${Math.random() * 360}deg);
      opacity: 1;
    `;
    document.body.appendChild(p);
    const tx = (Math.random() - 0.5) * 800;
    const ty = 400 + Math.random() * 400;
    const rot = Math.random() * 720;
    p.animate(
      [
        { transform: `translate(0, 0) rotate(0deg)`, opacity: 1 },
        { transform: `translate(${tx}px, ${ty}px) rotate(${rot}deg)`, opacity: 0 },
      ],
      { duration: 1400 + Math.random() * 800, easing: 'cubic-bezier(.2,.7,.2,1)', fill: 'forwards' }
    );
    setTimeout(() => p.remove(), 2400);
  }
}

Object.assign(window, { Configurator });
