/* AORYN — Calculator, Contact, Footer */

const { useState: uS3, useEffect: uE3, useMemo: uM3, useRef: uR3 } = React;

// ============================================================================
// CALCULATOR
// ============================================================================
const CALC_STEPS = [
  {
    key: 'businessType',
    title: '¿Qué tipo de proyecto tienes?',
    options: ['Negocio local (taller, tienda, oficio...)', 'Marca personal / profesional', 'Artista / proyecto creativo', 'Empresa mediana']
  },
  {
    key: 'needs',
    title: '¿Qué necesitas primero?',
    helper: 'Selecciona máximo 2 opciones principales.',
    multi: true,
    options: ['Web clara y funcional', 'Contenido audiovisual (vídeo / fotos)', 'Orden y estrategia', 'Automatización / IA aplicada']
  },
  {
    key: 'startingPoint',
    title: '¿Qué tienes ahora mismo?',
    options: ['Tengo web/redes pero está desordenado', 'Tengo algo, pero está obsoleto', 'Empiezo desde una base mínima', 'No lo sé / necesito revisión']
  },
  {
    key: 'pace',
    title: '¿Cómo quieres trabajar?',
    options: ['Paso a paso, con calma', 'Tengo fecha pero puedo adaptarme', 'Necesito algo rápido / urgente']
  },
  {
    key: 'monthly',
    title: '¿Quieres acompañamiento mensual?',
    options: ['Sí, mantenimiento básico', 'Sí, acompañamiento y mejoras', 'No, solo proyecto puntual']
  }
];

function Calculator() {
  const [open, setOpen] = uS3(false);
  const [step, setStep] = uS3(0);
  const [done, setDone] = uS3(false);
  const [data, setData] = uS3({ businessType: '', needs: [], startingPoint: '', pace: '', monthly: '' });

  uE3(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const reset = () => {
    setStep(0); setDone(false);
    setData({ businessType: '', needs: [], startingPoint: '', pace: '', monthly: '' });
  };
  const close = () => { setOpen(false); setTimeout(reset, 300); };

  const current = CALC_STEPS[step];
  const value = data[current?.key];
  const canNext = current?.multi ? value.length > 0 : !!value;

  const select = (opt) => {
    if (current.multi) {
      const arr = data[current.key];
      if (arr.includes(opt)) {
        setData({ ...data, [current.key]: arr.filter(x => x !== opt) });
      } else if (arr.length < 2) {
        setData({ ...data, [current.key]: [...arr, opt] });
      }
    } else {
      setData({ ...data, [current.key]: opt });
    }
  };

  const next = () => {
    if (step < CALC_STEPS.length - 1) setStep(step + 1);
    else setDone(true);
  };

  const estimate = uM3(() => {
    let minB = 700, maxB = 1200, minM = 0, maxM = 0;
    if (data.businessType === 'Empresa mediana') { minB += 1000; maxB += 2000; }
    if (data.businessType === 'Artista / proyecto creativo') { minB -= 100; maxB -= 200; }
    if (data.needs.includes('Web clara y funcional')) { minB += 500; maxB += 800; }
    if (data.needs.includes('Contenido audiovisual (vídeo / fotos)')) { minB += 600; maxB += 1000; }
    if (data.needs.includes('Automatización / IA aplicada')) { minB += 400; maxB += 800; }
    if (data.monthly.includes('mantenimiento básico')) { minM = 79; maxM = 120; }
    if (data.monthly.includes('acompañamiento')) { minM = 190; maxM = 350; }
    return {
      project: `${minB}€ – ${maxB}€`,
      monthly: minM > 0 ? `${minM}€ – ${maxM}€` : 'No contemplado',
      urgent: data.pace.includes('rápido')
    };
  }, [data]);

  const isSelected = (opt) => current?.multi ? data[current.key].includes(opt) : data[current?.key] === opt;

  return (
    <>
      <section id="calculator" className="calc-section">
        <div className="calc-card">
          <div className="calc-bg"></div>
          <div className="calc-content reveal">
            <div className="calc-eyebrow">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="4" y="2" width="16" height="20" rx="2"/><path d="M8 6h8M8 10h8M8 14h4"/></svg>
              Estimación inmediata
            </div>
            <h2>¿Cuánto cuesta trabajar con AORYN?</h2>
            <p className="calc-sub">
              Calculadora rápida para obtener una horquilla de precios realista en menos
              de 2 minutos. Sin compromiso, sin formularios infinitos.
            </p>
            <button className="btn-primary" onClick={() => setOpen(true)}>
              Calcular presupuesto
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
            </button>
          </div>
        </div>
      </section>

      <div className={`calc-modal ${open ? 'open' : ''}`}>
        <div className="calc-modal-inner">
          <div className="calc-card-form">
            <button className="calc-close" onClick={close}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
            </button>

            {!done ? (
              <>
                <div className="calc-progress">
                  <div className="bar" style={{ width: `${((step + 1) / CALC_STEPS.length) * 100}%` }}></div>
                </div>
                <div className="calc-step">
                  <h3>{current.title}</h3>
                  {current.helper && <p className="helper">{current.helper}</p>}
                  <div className="calc-options">
                    {current.options.map((opt) => (
                      <button key={opt} onClick={() => select(opt)} className={`calc-opt ${isSelected(opt) ? 'selected' : ''}`}>
                        <span>{opt}</span>
                        <span className="check">
                          {isSelected(opt) && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M5 13l4 4L19 7"/></svg>}
                        </span>
                      </button>
                    ))}
                  </div>
                </div>
                <div className="calc-actions">
                  <button className={`calc-back ${step === 0 ? 'hidden' : ''}`} onClick={() => setStep(Math.max(0, step - 1))}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
                    Atrás
                  </button>
                  <button className="calc-next" disabled={!canNext} onClick={next}>
                    {step === CALC_STEPS.length - 1 ? 'Ver resultado' : 'Siguiente'}
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
                  </button>
                </div>
              </>
            ) : (
              <div>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '999px', background: '#dcfce7', color: '#166534', fontSize: '11px', fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase', marginBottom: '20px' }}>
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M5 13l4 4L19 7"/></svg>
                  Cálculo completado
                </div>
                <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '-0.025em', fontSize: '28px', marginBottom: '24px' }}>
                  Tu estimación personalizada
                </h3>
                {estimate.urgent && (
                  <div className="calc-urgent-warn">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ flexShrink: 0 }}><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
                    <div>
                      <strong>Nota sobre urgencia: </strong>
                      AORYN no encaja con urgencias de "para ayer". Nuestros procesos requieren un mínimo de calma.
                    </div>
                  </div>
                )}
                <div className="calc-result-card">
                  <div className="box">
                    <div className="lbl">Proyecto base</div>
                    <div className="val">{estimate.project}</div>
                  </div>
                  <div className="box">
                    <div className="lbl">Cuota mensual</div>
                    <div className="val">{estimate.monthly}</div>
                  </div>
                </div>
                <button className="calc-next" style={{ width: '100%', justifyContent: 'center', padding: '16px' }} onClick={() => { close(); setTimeout(() => document.getElementById('contact')?.scrollIntoView({ behavior: 'smooth' }), 350); }}>
                  Continuar a contacto
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

// ============================================================================
// CONTACT
// ============================================================================
function Contact() {
  const [form, setForm] = uS3({ name: '', email: '', message: '' });
  const [sending, setSending] = uS3(false);
  const [ok, setOk] = uS3(false);

  const submit = async (e) => {
    e.preventDefault();
    setSending(true);
    await new Promise(r => setTimeout(r, 1200));
    setSending(false);
    setOk(true);
    setForm({ name: '', email: '', message: '' });
    setTimeout(() => setOk(false), 6000);
  };

  return (
    <section id="contact" className="contact-section">
      <div className="contact-glow"></div>
      <div className="contact-grid">
        <div className="contact-text reveal">
          <div className="section-eyebrow"><span className="num">04 —</span><span>Contacto</span></div>
          <h2>¿Hablamos de tu proyecto?</h2>
          <p>
            Si buscas trabajar con calma, coherencia y visión de largo plazo,
            estamos aquí. Respondemos en 24-48 horas.
          </p>
          <div className="direct">
            <div className="lbl">O escríbenos directamente</div>
            <a href="mailto:hola@aoryn.studio">hola@aoryn.studio</a>
          </div>
        </div>

        <form className="contact-form reveal" style={{ '--reveal-delay': '150ms' }} onSubmit={submit}>
          {ok ? (
            <div className="contact-success">
              <div className="check-circle">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 13l4 4L19 7"/></svg>
              </div>
              <h4 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: '22px' }}>Mensaje recibido</h4>
              <p style={{ color: 'var(--muted-fg)', fontSize: '15px' }}>Te responderemos en 24-48 horas.</p>
            </div>
          ) : (
            <>
              <div className="field">
                <label>Nombre</label>
                <input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Tu nombre"/>
              </div>
              <div className="field">
                <label>Email</label>
                <input required type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="tu@email.com"/>
              </div>
              <div className="field">
                <label>Mensaje</label>
                <textarea required value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })} placeholder="Cuéntanos brevemente qué necesitas..."/>
              </div>
              <button type="submit" disabled={sending} className="submit">
                {sending ? 'Enviando...' : 'Enviar mensaje'}
                {!sending && <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>}
              </button>
            </>
          )}
        </form>
      </div>

      <div className="contact-bottom">
        Sin promesas rápidas. Sin humo. Con proceso y propósito.
      </div>
    </section>
  );
}

// ============================================================================
// FOOTER
// ============================================================================
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-mega">AORYN</div>
      <div className="footer-grid">
        <div className="brand-block">
          <div className="wordmark"><span className="mark"></span> AORYN</div>
          <p>Estrategia, creación audiovisual y sistemas digitales para negocios que quieren comunicar con claridad.</p>
        </div>
        <div>
          <h4>Servicios</h4>
          <ul>
            <li><a href="#services">Estrategia & Consultoría</a></li>
            <li><a href="#services">Diseño & Audiovisual</a></li>
            <li><a href="#services">Web & Aplicaciones</a></li>
            <li><a href="#services">Automatización & IA</a></li>
          </ul>
        </div>
        <div>
          <h4>Contacto</h4>
          <ul>
            <li><a href="mailto:hola@aoryn.studio">hola@aoryn.studio</a></li>
            <li>Respondemos en 24-48h</li>
            <li>Sin automatizaciones</li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 AORYN Studio</span>
        <span className="text-gradient">Sin promesas rápidas · Con proceso</span>
      </div>
    </footer>
  );
}

Object.assign(window, { Calculator, Contact, Footer });
