// calendar.jsx — Booking section (B2B clean style)

function Booking() {
  const [step, setStep] = React.useState('pick');
  const [weekOffset, setWeekOffset] = React.useState(0);
  const [selected, setSelected] = React.useState(null);
  const [form, setForm] = React.useState({
    name: '', business: '', email: '', phone: '', context: '',
  });
  const [errors, setErrors] = React.useState({});

  const today = React.useMemo(() => {
    const d = new Date();
    d.setHours(0, 0, 0, 0);
    return d;
  }, []);

  const week = React.useMemo(() => {
    const days = [];
    for (let i = 0; i < 5; i++) {
      const d = new Date(today);
      d.setDate(today.getDate() + 1 + weekOffset * 7 + i);
      days.push(d);
    }
    return days;
  }, [today, weekOffset]);

  const dayNames = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'];
  const monthNames = ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'];

  const slotsFor = (date) => {
    const all = ['09:30', '11:00', '14:30', '16:00', '17:30'];
    const seed = date.getDate() % 5;
    return all.map((t, i) => ({ time: t, busy: (i + seed) % 4 === 0 }));
  };

  const labelFor = (d) =>
    `${dayNames[d.getDay()]} ${d.getDate()} ${monthNames[d.getMonth()]}`;

  const onPick = (d, slot) => {
    if (slot.busy) return;
    setSelected({
      dayName: dayNames[d.getDay()],
      dateLabel: `${d.getDate()} ${monthNames[d.getMonth()]}`,
      time: slot.time,
      fullDate: d,
    });
    setStep('form');
  };

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Manca il tuo nome.';
    if (!form.business.trim()) e.business = "Manca il nome dell'attività.";
    if (!form.email.trim()) e.email = "Manca l'email.";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "Email non valida.";
    if (!form.context.trim() || form.context.trim().length < 10) {
      e.context = 'Anche due righe vanno bene. Minimo 10 caratteri.';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const onSubmit = (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setStep('done');
  };

  const resetAll = () => {
    setStep('pick');
    setSelected(null);
    setForm({ name: '', business: '', email: '', phone: '', context: '' });
    setErrors({});
  };

  return (
    <section id="prenota" style={{
      padding: '110px 0 100px',
      background: 'linear-gradient(180deg, var(--bg) 0%, var(--bg-3) 100%)',
      position: 'relative',
    }}>
      <div className="container">
        <div style={{ textAlign: 'center', marginBottom: 56, maxWidth: 720, margin: '0 auto 56px' }}>
          <Eyebrow style={{ marginBottom: 16 }}>Reserva la llamada</Eyebrow>
          <h2 style={{
            fontFamily: 'var(--sans)',
            fontSize: 'clamp(38px, 5vw, 60px)',
            fontWeight: 700, lineHeight: 1.05,
            letterSpacing: '-0.03em', margin: '0 0 18px',
          }}>
            30 minutos gratis.{' '}<br />
            <span style={{
              background: 'linear-gradient(120deg, var(--accent) 0%, var(--accent-deep) 100%)',
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent',
              backgroundClip: 'text',
            }}>Sin compromiso.</span>
          </h2>
          <p style={{
            fontSize: 18, color: 'var(--fg-soft)',
            margin: 0, lineHeight: 1.55,
          }}>
            Nos cuentas cómo trabajas hoy, te decimos honestamente qué
            vale la pena automatizar. Si no hay encaje, lo decimos de inmediato.
          </p>
        </div>

        <div style={{
          background: 'var(--bg-2)',
          borderRadius: 'var(--radius-lg)',
          border: '1px solid var(--rule)',
          boxShadow: 'var(--shadow-lg)',
          overflow: 'hidden',
          maxWidth: 1100, margin: '0 auto',
        }}>
          {step === 'pick' && (
            <PickStep
              week={week} weekOffset={weekOffset} setWeekOffset={setWeekOffset}
              slotsFor={slotsFor} labelFor={labelFor} onPick={onPick}
            />
          )}
          {step === 'form' && (
            <FormStep
              selected={selected}
              form={form} setForm={setForm}
              errors={errors}
              onBack={() => setStep('pick')}
              onSubmit={onSubmit}
            />
          )}
          {step === 'done' && (
            <DoneStep selected={selected} form={form} onReset={resetAll} />
          )}
        </div>
      </div>
    </section>
  );
}

function PickStep({ week, weekOffset, setWeekOffset, slotsFor, labelFor, onPick }) {
  return (
    <div style={{ padding: 'clamp(24px, 3vw, 36px)' }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 28, flexWrap: 'wrap', gap: 16,
      }}>
        <div>
          <Eyebrow style={{ marginBottom: 6 }}>Paso 1 de 2</Eyebrow>
          <h3 style={{
            margin: 0, fontSize: 22, fontWeight: 700,
            letterSpacing: '-0.015em',
          }}>Elige cuándo nos hablamos</h3>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button
            disabled={weekOffset === 0}
            onClick={() => setWeekOffset(weekOffset - 1)}
            style={{
              appearance: 'none',
              background: weekOffset === 0 ? 'var(--bg-3)' : 'var(--bg-2)',
              border: '1px solid var(--rule)',
              color: weekOffset === 0 ? 'var(--fg-mute)' : 'var(--fg)',
              fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 600,
              padding: '10px 14px', borderRadius: 8,
              cursor: weekOffset === 0 ? 'not-allowed' : 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
            ← Semana anterior
          </button>
          <button
            onClick={() => setWeekOffset(weekOffset + 1)}
            style={{
              appearance: 'none',
              background: 'var(--bg-2)',
              border: '1px solid var(--rule)',
              color: 'var(--fg)',
              fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 600,
              padding: '10px 14px', borderRadius: 8,
              cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
            Semana siguiente →
          </button>
        </div>
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(5, 1fr)',
        gap: 12,
      }} className="week-grid">
        {week.map((d, i) => {
          const slots = slotsFor(d);
          return (
            <div key={i} style={{
              background: 'var(--bg)',
              border: '1px solid var(--rule)',
              borderRadius: 'var(--radius)',
              padding: 14,
              display: 'flex', flexDirection: 'column', gap: 8,
            }}>
              <div style={{
                paddingBottom: 12,
                borderBottom: '1px solid var(--rule)',
                marginBottom: 4,
              }}>
                <div style={{
                  fontFamily: 'var(--mono)', fontSize: 11,
                  color: 'var(--fg-mute)', fontWeight: 600,
                  letterSpacing: '0.04em', textTransform: 'uppercase',
                }}>{labelFor(d).split(' ')[0]}</div>
                <div style={{ marginTop: 4 }}>
                  <span style={{
                    fontSize: 22, fontWeight: 700, letterSpacing: '-0.015em',
                  }}>{d.getDate()}</span>
                  <span style={{
                    fontSize: 13, color: 'var(--fg-mute)', marginLeft: 4,
                  }}>{labelFor(d).split(' ')[2]}</span>
                </div>
              </div>
              {slots.map((s, k) => (
                <button
                  key={k}
                  disabled={s.busy}
                  onClick={() => onPick(d, s)}
                  style={{
                    appearance: 'none',
                    border: '1px solid ' + (s.busy ? 'var(--rule)' : 'var(--rule)'),
                    background: s.busy ? 'transparent' : 'var(--bg-2)',
                    color: s.busy ? 'var(--fg-mute)' : 'var(--fg)',
                    padding: '8px 10px',
                    fontFamily: 'var(--mono)', fontSize: 13, fontWeight: 600,
                    borderRadius: 8,
                    cursor: s.busy ? 'not-allowed' : 'pointer',
                    textDecoration: s.busy ? 'line-through' : 'none',
                    opacity: s.busy ? 0.45 : 1,
                    transition: 'all .15s ease',
                  }}
                  onMouseEnter={(e) => {
                    if (s.busy) return;
                    e.currentTarget.style.background = 'var(--accent)';
                    e.currentTarget.style.color = '#fff';
                    e.currentTarget.style.borderColor = 'var(--accent)';
                  }}
                  onMouseLeave={(e) => {
                    if (s.busy) return;
                    e.currentTarget.style.background = 'var(--bg-2)';
                    e.currentTarget.style.color = 'var(--fg)';
                    e.currentTarget.style.borderColor = 'var(--rule)';
                  }}
                >
                  {s.time}
                </button>
              ))}
            </div>
          );
        })}
      </div>

      <p style={{
        marginTop: 20, fontSize: 12, color: 'var(--fg-mute)',
        display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8,
        fontFamily: 'var(--mono)',
      }}>
        <span>Huso CET (España) · 30 minutos · Google Meet</span>
        <span>Confirmas en el siguiente paso</span>
      </p>

      <style>{`
        @media (max-width: 860px) {
          .week-grid { grid-template-columns: repeat(2, 1fr) !important; }
        }
        @media (max-width: 520px) {
          .week-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

function FormStep({ selected, form, setForm, errors, onBack, onSubmit }) {
  const update = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'minmax(0, 0.8fr) minmax(0, 1.3fr)',
    }} className="form-grid">
      <aside style={{
        background: 'var(--bg)',
        padding: 'clamp(24px, 3vw, 32px)',
        borderRight: '1px solid var(--rule)',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        gap: 24,
      }}>
        <div>
          <Eyebrow style={{ marginBottom: 16 }}>Paso 2 de 2 · Resumen</Eyebrow>
          <h3 style={{
            margin: '0 0 24px', fontSize: 24, fontWeight: 700,
            letterSpacing: '-0.02em',
          }}>Casi listo.</h3>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <SummaryRow label="Cuándo" value={`${selected.dayName} ${selected.dateLabel}`} />
            <SummaryRow label="Hora" value={`${selected.time} → ${addThirty(selected.time)}`} />
            <SummaryRow label="Duración" value="30 minutos" />
            <SummaryRow label="Dónde" value="Google Meet" />
            <SummaryRow label="Coste" value="Gratis" tone="positive" />
          </div>
        </div>

        <button onClick={onBack} style={{
          appearance: 'none', border: 'none', background: 'transparent',
          color: 'var(--fg-soft)', cursor: 'pointer',
          fontSize: 13, fontWeight: 600, textAlign: 'left',
          padding: 0, display: 'inline-flex', alignItems: 'center', gap: 6,
          fontFamily: 'var(--sans)',
        }}>← Cambiar horario</button>
      </aside>

      <form onSubmit={onSubmit} style={{
        padding: 'clamp(24px, 3vw, 32px)',
        display: 'flex', flexDirection: 'column', gap: 18,
      }}>
        <h3 style={{
          margin: 0, fontSize: 20, fontWeight: 700,
          letterSpacing: '-0.015em',
        }}>Cuéntanos dos cosas</h3>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }} className="form-row">
          <Field label="Nombre" value={form.name} onChange={update('name')} error={errors.name} required />
          <Field label="Empresa / actividad" value={form.business} onChange={update('business')} error={errors.business} required />
          <Field label="Email" type="email" value={form.email} onChange={update('email')} error={errors.email} required />
          <Field label="Teléfono" type="tel" value={form.phone} onChange={update('phone')} placeholder="opcional" />
        </div>

        <Field
          label="¿Qué te hace perder más tiempo hoy?"
          value={form.context}
          onChange={update('context')}
          error={errors.context}
          required
          textarea
          placeholder="Dos líneas están bien — un ejemplo concreto nos basta."
        />

        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          flexWrap: 'wrap', gap: 14, marginTop: 4,
          paddingTop: 16, borderTop: '1px solid var(--rule)',
        }}>
          <p style={{
            margin: 0, fontSize: 12,
            color: 'var(--fg-mute)', maxWidth: 360,
          }}>
            🔒 Al confirmar recibirás un email con el enlace de Meet y un breve formulario de preparación (1 min).
          </p>
          <button type="submit" style={{
            appearance: 'none', border: 'none',
            background: 'var(--accent)', color: '#fff',
            padding: '13px 22px', borderRadius: 999,
            fontSize: 15, fontWeight: 600,
            cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 8,
            boxShadow: 'var(--shadow-md)',
            fontFamily: 'var(--sans)',
            transition: 'transform .15s ease',
          }}
            onMouseEnter={(e) => e.currentTarget.style.transform = 'translateY(-1px)'}
            onMouseLeave={(e) => e.currentTarget.style.transform = 'translateY(0)'}
          >
            Confirmar reserva <ArrowRight />
          </button>
        </div>
      </form>

      <style>{`
        @media (max-width: 860px) {
          .form-grid { grid-template-columns: 1fr !important; }
          .form-row { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

function SummaryRow({ label, value, tone }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between',
      gap: 12, padding: '12px 0',
      borderBottom: '1px solid var(--rule)',
      alignItems: 'center',
    }}>
      <span style={{
        fontSize: 12, color: 'var(--fg-mute)',
        fontFamily: 'var(--mono)', fontWeight: 600,
        letterSpacing: '0.04em', textTransform: 'uppercase',
      }}>{label}</span>
      <span style={{
        fontSize: 14, fontWeight: 600, textAlign: 'right',
        color: tone === 'positive' ? 'var(--positive)' : 'var(--fg)',
      }}>{value}</span>
    </div>
  );
}

function Field({ label, error, required, textarea, ...props }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{
        fontSize: 12, fontWeight: 600,
        color: error ? '#c83535' : 'var(--fg-soft)',
        display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap',
      }}>
        {label} {required && <span style={{ color: 'var(--accent)' }}>*</span>}
        {error && <span style={{
          fontStyle: 'italic', fontWeight: 500, color: '#c83535',
        }}>— {error}</span>}
      </span>
      {textarea ? (
        <textarea {...props} rows={3} style={{
          fontFamily: 'var(--sans)', fontSize: 15,
          padding: '12px 14px',
          resize: 'vertical',
          background: 'var(--bg)',
          border: `1px solid ${error ? '#c83535' : 'var(--rule)'}`,
          borderRadius: 10,
          color: 'var(--fg)',
          outline: 'none',
          transition: 'border-color .15s ease, box-shadow .15s ease',
        }} onFocus={(e) => { e.target.style.borderColor = 'var(--accent)'; e.target.style.boxShadow = '0 0 0 3px var(--accent-soft)'; }}
           onBlur={(e) => { e.target.style.borderColor = error ? '#c83535' : 'var(--rule)'; e.target.style.boxShadow = 'none'; }} />
      ) : (
        <input {...props} style={{
          fontFamily: 'var(--sans)', fontSize: 15,
          padding: '11px 14px',
          background: 'var(--bg)',
          border: `1px solid ${error ? '#c83535' : 'var(--rule)'}`,
          borderRadius: 10,
          color: 'var(--fg)',
          outline: 'none',
          transition: 'border-color .15s ease, box-shadow .15s ease',
        }} onFocus={(e) => { e.target.style.borderColor = 'var(--accent)'; e.target.style.boxShadow = '0 0 0 3px var(--accent-soft)'; }}
           onBlur={(e) => { e.target.style.borderColor = error ? '#c83535' : 'var(--rule)'; e.target.style.boxShadow = 'none'; }} />
      )}
    </label>
  );
}

function addThirty(hhmm) {
  const [h, m] = hhmm.split(':').map(Number);
  const total = h * 60 + m + 30;
  return `${String(Math.floor(total / 60)).padStart(2, '0')}:${String(total % 60).padStart(2, '0')}`;
}

function DoneStep({ selected, form, onReset }) {
  return (
    <div style={{
      padding: 'clamp(36px, 5vw, 64px)',
      minHeight: 480,
      display: 'flex', flexDirection: 'column', justifyContent: 'center',
      gap: 28, maxWidth: 720, margin: '0 auto',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <span style={{
          width: 56, height: 56, borderRadius: '50%',
          background: 'var(--positive)', color: '#fff',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 28, fontWeight: 700,
        }}>✓</span>
        <Eyebrow>¡Reserva confirmada!</Eyebrow>
      </div>

      <h3 style={{
        margin: 0, fontSize: 'clamp(30px, 4vw, 44px)',
        fontWeight: 700, lineHeight: 1.05,
        letterSpacing: '-0.025em',
      }}>
        ¡Hasta pronto, <span style={{
          background: 'linear-gradient(120deg, var(--accent) 0%, var(--accent-deep) 100%)',
          WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text',
        }}>{form.name.split(' ')[0] || 'amigo'}</span>!
      </h3>

      <p style={{
        margin: 0, fontSize: 17, lineHeight: 1.55,
        color: 'var(--fg-soft)',
      }}>
        Nos hablamos el <strong style={{ color: 'var(--fg)' }}>{selected.dayName} {selected.dateLabel} a las {selected.time}</strong>.
        Encontrarás la invitación de Google Meet en <strong style={{ color: 'var(--fg)' }}>{form.email}</strong> en unos minutos.
      </p>

      <div style={{
        background: 'var(--bg)',
        border: '1px solid var(--rule)',
        borderRadius: 'var(--radius)',
        padding: 24,
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
        gap: 20,
      }}>
        <Detail k="Qué preparamos nosotros" v="Nada. Venimos a escucharte." />
        <Detail k="Qué preparas tú" v="Un ejemplo del trabajo repetitivo que querrías eliminar." />
        <Detail k="Duración" v="30 minutos netos." />
      </div>

      <button onClick={onReset} style={{
        alignSelf: 'flex-start',
        appearance: 'none', border: 'none', background: 'transparent',
        color: 'var(--fg-soft)', cursor: 'pointer',
        fontSize: 13, fontWeight: 600,
        padding: 0, fontFamily: 'var(--sans)',
      }}>← Reservar otra llamada</button>
    </div>
  );
}

function Detail({ k, v }) {
  return (
    <div>
      <div style={{
        fontSize: 11, fontWeight: 700, color: 'var(--fg-mute)',
        fontFamily: 'var(--mono)', letterSpacing: '0.04em',
        textTransform: 'uppercase', marginBottom: 6,
      }}>{k}</div>
      <div style={{ fontSize: 14, color: 'var(--fg)', lineHeight: 1.45 }}>{v}</div>
    </div>
  );
}

window.Booking = Booking;
