// Diagnóstico gratis · Preguntas frecuentes · Footer
const DiagField = ({ label, error, children }) => (
  <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
    <span className="eyebrow" style={{ color: 'var(--ink-soft)' }}>{label}</span>
    {children}
    {error && <span className="hand" style={{ fontSize: 18, color: 'var(--bad)' }}>{error}</span>}
  </label>
);

const WA_NUMERO = '5491160473922';

const mensajeDiagnostico = d => [
  `Hola, quiero el diagnóstico gratis de ${BRAND.name}.`,
  `Nombre: ${d.nombre.trim()}`,
  `Restaurante: ${d.restaurante.trim()}`,
  `WhatsApp: ${d.whatsapp.trim()}`,
  d.email.trim() && `Mail: ${d.email.trim()}`,
  `Locales: ${d.locales}`,
].filter(Boolean).join('\n');

const DiagnosticoV2 = () => {
  const [data, setData] = React.useState({ nombre: '', restaurante: '', whatsapp: '', email: '', locales: '1' });
  const [touched, setTouched] = React.useState({});
  const [sent, setSent] = React.useState(false);

  const errors = {};
  if (!data.nombre.trim()) errors.nombre = 'Ponele tu nombre';
  if (!data.restaurante.trim()) errors.restaurante = '¿Cómo se llama tu restaurante?';
  if (!data.whatsapp.trim()) errors.whatsapp = 'Necesitamos un WhatsApp para pedirte las facturas';
  else if (!/^[\d\s+\-()]{8,}$/.test(data.whatsapp)) errors.whatsapp = 'Revisá el número';
  if (data.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) errors.email = 'Mail inválido';
  const ok = Object.keys(errors).length === 0;
  const up = (k, v) => setData(d => ({ ...d, [k]: v }));
  const blur = k => setTouched(t => ({ ...t, [k]: true }));
  const submit = e => {
    e.preventDefault();
    setTouched({ nombre: true, restaurante: true, whatsapp: true, email: true });
    if (!ok) return;
    window.open(waLink, '_blank', 'noopener');
    setSent(true);
  };
  const waLink = `https://wa.me/${WA_NUMERO}?text=` + encodeURIComponent(mensajeDiagnostico(data));

  return (
    <section id="diagnostico" style={{ background: 'var(--kraft)', borderTop: '1.5px solid var(--ink)', borderBottom: '1.5px solid var(--ink)' }}>
      <div className="container">
        <div className="diag-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(0,6fr) minmax(0,5fr)', gap: 80, alignItems: 'start' }}>
          <div>
            <div className="kicker" style={{ color: 'var(--primary)' }}><span>Diagnóstico gratuito</span></div>
            <h2 className="display" style={{ fontSize: 'clamp(42px, 5.4vw, 80px)', margin: '20px 0 26px' }}>
              ¿Cuánto te cobraron <HandUnderline color="var(--accent)"><em>de más</em></HandUnderline> este mes?
            </h2>
            <p className="body-lg" style={{ color: 'var(--ink)', margin: '0 0 36px', maxWidth: 600 }}>
              Mandanos tus últimas 10 facturas de proveedores y lo que habías acordado pagar (la orden, el WhatsApp o la lista de precios).
              En 48 hs te devolvemos un informe con lo que encontramos.
            </p>
            <div className="eyebrow" style={{ color: 'var(--ink)', paddingBottom: 12, borderBottom: '1.5px solid var(--ink)' }}>Qué recibís</div>
            <ol style={{ listStyle: 'none', padding: 0, margin: '0 0 30px' }}>
              {[
                'Diferencias entre lo facturado y lo acordado, por proveedor',
                'Insumos que subieron más de 7% y cuánto pesan en tu carta',
                'Cambios de envase o presentación que esconden aumentos',
                'Un plato tuyo costeado con los precios de hoy',
              ].map((t, i) => (
                <li key={t} style={{ display: 'grid', gridTemplateColumns: '40px minmax(0,1fr)', gap: 8, padding: '15px 0', borderBottom: '1px solid rgba(28,25,23,.18)', fontSize: 17, color: 'var(--ink)' }}>
                  <span className="display" style={{ fontSize: 24, color: 'var(--accent)', lineHeight: 1.1 }}>{i + 1}</span>{t}
                </li>
              ))}
            </ol>
            <p style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 22, color: 'var(--primary)', margin: 0, maxWidth: 520, lineHeight: 1.3 }}>
              Si no encontramos nada, te lo decimos igual. Eso también es información.
            </p>
          </div>

          <div style={{ position: 'relative', filter: 'drop-shadow(6px 12px 20px rgba(60,40,20,.2))', transform: 'rotate(.8deg)' }}>
            <span className="tape" style={{ left: 40, transform: 'rotate(-4deg)' }}/>
            <span className="tape" style={{ right: 40, transform: 'rotate(5deg)' }}/>
            <div style={{ position: 'absolute', right: 22, top: 26, zIndex: 3 }}>
              <Stamp color="var(--accent)" rotate={9} size={1}>Gratis</Stamp>
            </div>
            <Receipt pad="40px 34px 50px" teeth={30}>
              {sent ? (
                <div style={{ padding: '30px 0', textAlign: 'center' }}>
                  <Stamp color="var(--olive)" rotate={-6} size={1.3} style={{ marginBottom: 28 }}>Casi listo</Stamp>
                  <h3 className="display" style={{ fontSize: 38, margin: '0 0 12px' }}>Gracias, {data.nombre.trim().split(' ')[0]}.</h3>
                  <p className="body" style={{ margin: '0 0 18px' }}>
                    Se abrió WhatsApp con tus datos: tocá <strong style={{ color: 'var(--ink)' }}>Enviar</strong> para que nos llegue el pedido.
                    Después te pedimos las facturas por ahí y el informe te llega en 48 hs desde que las recibimos.
                  </p>
                  <a href={waLink} target="_blank" rel="noopener" style={{ color: 'var(--accent)', fontWeight: 600 }}>¿No se abrió? Abrir WhatsApp →</a>
                </div>
              ) : (
                <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
                  <div>
                    <div className="eyebrow">Solicitud de diagnóstico</div>
                    <div className="display" style={{ fontSize: 30, marginTop: 4 }}>Tus datos</div>
                  </div>
                  <DiagField label="Tu nombre *" error={touched.nombre && errors.nombre}>
                    <input className="line-input" value={data.nombre} onChange={e => up('nombre', e.target.value)} onBlur={() => blur('nombre')}/>
                  </DiagField>
                  <DiagField label="Restaurante *" error={touched.restaurante && errors.restaurante}>
                    <input className="line-input" value={data.restaurante} onChange={e => up('restaurante', e.target.value)} onBlur={() => blur('restaurante')}/>
                  </DiagField>
                  <div className="diag-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 22 }}>
                    <DiagField label="WhatsApp *" error={touched.whatsapp && errors.whatsapp}>
                      <input className="line-input" type="tel" placeholder="+54 9 11…" value={data.whatsapp} onChange={e => up('whatsapp', e.target.value)} onBlur={() => blur('whatsapp')}/>
                    </DiagField>
                    <DiagField label="Mail" error={touched.email && errors.email}>
                      <input className="line-input" type="email" value={data.email} onChange={e => up('email', e.target.value)} onBlur={() => blur('email')}/>
                    </DiagField>
                  </div>
                  <div>
                    <div className="eyebrow" style={{ color: 'var(--ink-soft)', marginBottom: 10 }}>¿Cuántos locales?</div>
                    <div style={{ display: 'flex', gap: 22, flexWrap: 'wrap' }}>
                      {['1', '2-3', '4+'].map(o => {
                        const on = data.locales === o;
                        return (
                          <button type="button" key={o} onClick={() => up('locales', o)} aria-pressed={on} style={{
                            display: 'inline-flex', alignItems: 'center', gap: 9, background: 'none', border: 'none', padding: '6px 0',
                            cursor: 'pointer', fontFamily: 'var(--sans)', fontSize: 16, color: 'var(--ink)', minHeight: 44,
                          }}>
                            <span style={{ width: 20, height: 20, border: '1.5px solid var(--ink)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--accent)' }}>
                              {on && <Icon.Check size={15}/>}
                            </span>{o}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                  <div>
                    <div className="eyebrow" style={{ color: 'var(--ink-soft)', marginBottom: 6 }}>Facturas</div>
                    <div className="hand" style={{ fontSize: 22, color: 'var(--ink-soft)', borderBottom: '1.5px dashed var(--line-strong)', paddingBottom: 8 }}>Te las pedimos por WhatsApp.</div>
                  </div>
                  <button type="submit" className="btn btn-primary btn-lg" style={{ justifyContent: 'center', marginTop: 6 }}>
                    Quiero mi diagnóstico gratis<Icon.Arrow size={16}/>
                  </button>
                  <p className="small" style={{ margin: 0, textAlign: 'center', fontSize: 12.5 }}>
                    Se abre WhatsApp con tus datos para que nos los mandes. Tus facturas no se comparten ni se usan como ejemplo. Tomamos 10 diagnósticos por mes.
                  </p>
                </form>
              )}
            </Receipt>
          </div>
        </div>

        <div style={{ marginTop: 64, paddingTop: 26, borderTop: '1.5px solid var(--ink)', fontSize: 16, color: 'var(--ink)', display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'baseline' }}>
          ¿Preferís ver el sistema primero?
          <a href={`https://wa.me/${WA_NUMERO}?text=` + encodeURIComponent('Hola, quiero agendar una demo de ' + BRAND.name)} target="_blank" rel="noopener" style={{ color: 'var(--accent)', fontWeight: 600 }}>Agendá una demo de 30 minutos →</a>
        </div>
      </div>
      <style>{`@media (max-width:960px){.diag-grid{grid-template-columns:1fr!important;gap:56px!important}}@media (max-width:540px){.diag-2{grid-template-columns:1fr!important}}`}</style>
    </section>
  );
};

const FAQS_V2 = [
  ['¿Tengo que cambiar de proveedores?', <>No. Trabajás con los mismos; el sistema te muestra cuál te conviene en cada insumo.</>],
  ['¿Necesito una computadora en la cocina?', <>No. Se usa desde el celular o desde la PC de la oficina.</>],
  ['¿Quién carga los datos al principio?', <>Nosotros, desde tus facturas, recetas y carta, como las tengas (Excel, cuaderno o foto).</>],
  ['¿Cuánto tiempo por día me lleva?', <>Cargar las órdenes, las facturas y la venta del día. <Confirmar>minutos por servicio</Confirmar></>],
  ['¿Sirve si tengo varios locales?', <>Sí, con el plan Grupo.</>],
  ['¿Qué pasa si me doy de baja?', <>Te llevás todos tus datos en Excel. Avisás con 30 días y listo.</>],
  ['¿Mis recetas quedan seguras?', <>Sí. Cada restaurante ve solo sus datos y nunca los usamos como ejemplo sin tu autorización.</>],
];

const FaqV2 = () => {
  const [open, setOpen] = React.useState(0);
  return (
    <section id="preguntas">
      <div className="container">
        <div className="faq-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(0,4fr) minmax(0,7fr)', gap: 80, alignItems: 'start' }}>
          <div className="faq-side" style={{ position: 'sticky', top: 110 }}>
            <div className="kicker"><span>Preguntas frecuentes</span></div>
            <h2 className="display" style={{ fontSize: 'clamp(40px, 4.6vw, 66px)', margin: '20px 0 0' }}>Lo que nos <em>preguntan siempre.</em></h2>
          </div>
          <div style={{ borderTop: '1.5px solid var(--ink)' }}>
            {FAQS_V2.map(([q, a], i) => {
              const on = open === i;
              return (
                <div key={q} style={{ borderBottom: '1px solid var(--line-strong)' }}>
                  <button onClick={() => setOpen(on ? -1 : i)} aria-expanded={on} style={{
                    width: '100%', display: 'grid', gridTemplateColumns: '44px minmax(0,1fr) 28px', alignItems: 'baseline', gap: 8,
                    padding: '24px 0', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', color: 'var(--ink)',
                  }}>
                    <span style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--accent)' }}>{String(i + 1).padStart(2, '0')}</span>
                    <span className="display" style={{ fontSize: 'clamp(22px, 2.2vw, 28px)', lineHeight: 1.2 }}>{q}</span>
                    <span style={{ fontFamily: 'var(--serif)', fontSize: 30, lineHeight: .6, color: 'var(--accent)', transform: on ? 'rotate(45deg)' : 'none', transition: 'transform 220ms ease', textAlign: 'center' }}>+</span>
                  </button>
                  {on && <p className="body" style={{ margin: '-6px 0 26px', padding: '0 36px 0 52px', fontSize: 17, animation: 'fadeInUp 260ms ease both' }}>{a}</p>}
                </div>
              );
            })}
          </div>
        </div>
      </div>
      <style>{`@media (max-width:920px){.faq-grid{grid-template-columns:1fr!important;gap:40px!important}.faq-side{position:static!important}}`}</style>
    </section>
  );
};

const FooterV2 = () => {
  const cols = [
    ['Módulos', [['Compras', '#producto'], ['Cocina', '#producto'], ['Barra', '#producto'], ['Operación', '#producto'], ['Análisis', '#producto'], ['Informes', '#producto']]],
    ['La empresa', [['Por qué existe', '#por-que-existe'], ['Caso Tero Restó', '#resultados'], ['Diagnóstico gratis', '#diagnostico'], ['Preguntas frecuentes', '#preguntas']]],
  ];
  return (
    <footer style={{ background: 'var(--ink)', color: 'rgba(246,241,231,.82)', padding: '88px 0 32px', overflow: 'hidden' }}>
      <div className="container">
        <div className="ft-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.4fr) repeat(2, minmax(0,1fr))', gap: 48, marginBottom: 64 }}>
          <div>
            <p className="display" style={{ fontSize: 30, color: '#F6F1E7', margin: '0 0 18px', maxWidth: 420, lineHeight: 1.15 }}>
              Software de gestión gastronómica y control de costos. <em style={{ color: 'var(--accent-soft)' }}>Hecho en una cocina.</em>
            </p>
            <div style={{ fontSize: 14, lineHeight: 1.7 }}>
              Benavidez, zona norte · Buenos Aires<br/>
              <a href={'mailto:' + BRAND.email} style={{ color: 'var(--accent-soft)' }}>{BRAND.email}</a> <Confirmar>mail</Confirmar>
            </div>
          </div>
          {cols.map(([t, links]) => (
            <div key={t}>
              <div className="eyebrow" style={{ color: 'rgba(246,241,231,.5)', marginBottom: 16 }}>{t}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
                {links.map(([l, h]) => <li key={l}><a href={h} style={{ color: 'rgba(246,241,231,.85)', textDecoration: 'none', fontSize: 15 }}>{l}</a></li>)}
              </ul>
            </div>
          ))}
        </div>
        <div aria-hidden="true" className="display" style={{ fontSize: 'clamp(84px, 19vw, 270px)', lineHeight: .8, color: '#F6F1E7', letterSpacing: '-.04em', margin: '0 0 30px', whiteSpace: 'nowrap' }}>
          {BRAND.name}<span style={{ color: 'var(--accent)' }}>.</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', paddingTop: 22, borderTop: '1px solid rgba(246,241,231,.18)', fontSize: 13, color: 'rgba(246,241,231,.55)' }}>
          <span>© 2026 {BRAND.name} · Buenos Aires, Argentina</span>
          <span style={{ display: 'flex', gap: 20 }}><a href="#" style={{ color: 'inherit' }}>Términos</a><a href="#" style={{ color: 'inherit' }}>Privacidad</a></span>
        </div>
      </div>
      <style>{`@media (max-width:760px){.ft-grid{grid-template-columns:1fr 1fr!important}.ft-grid>div:first-child{grid-column:1/-1}}`}</style>
    </footer>
  );
};

Object.assign(window, { DiagnosticoV2, FaqV2, FooterV2 });
