/* global React, Placeholder, SectionHead, StarRow */

// ───────────── GERENTE ─────────────
const Gerente = ({ onReserve }) => (
  <section id="gerente" className="bb-section bb-section--paper">
    <SectionHead num="05" title="El Gerente" subtitle="Detrás de cada silla hay una historia." />

    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ position: 'relative' }}>
        <Placeholder label="Retrato · Gerente" height={340} />
        <div style={{
          position: 'absolute', bottom: 12, left: 12,
          background: 'var(--bg)',
          padding: '10px 12px',
          borderLeft: '2px solid var(--gold)',
        }}>
          <div className="bb-label" style={{ color: 'var(--gold)' }}>FUNDADOR</div>
          <div style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontStyle: 'italic', fontSize: 22,
            lineHeight: 1, marginTop: 4,
          }}>Matías Bread</div>
        </div>
      </div>

      <div>
        <div className="bb-label" style={{ color: 'var(--gold)', marginBottom: 10 }}>— MENSAJE —</div>
        <p style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontStyle: 'italic', fontWeight: 500,
          fontSize: 22, lineHeight: 1.3,
          margin: 0,
        }}>
          "Empecé a cortar el pelo a los dieciséis. Hoy, una década después,
          quiero que cada cliente sienta que pasar por nuestra silla es un acto de cuidado, no un trámite."
        </p>
      </div>

      <div style={{
        borderTop: '1px solid var(--line)',
        borderBottom: '1px solid var(--line)',
        padding: '18px 0',
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16,
      }}>
        <Stat label="Visión" value="Ser la casa de oficio referente del norte de Chile." />
        <Stat label="Misión" value="Cuidar a cada cliente como si fuera familia." />
        <Stat label="Especialidad" value="Fades clásicos y diseño moderno." />
        <Stat label="Experiencia" value="10+ años en barbería y formación." />
      </div>

      <button className="bb-btn bb-btn--gold bb-btn--block" onClick={onReserve}>
        Agenda con Matías
      </button>
    </div>
  </section>
);

const Stat = ({ label, value }) => (
  <div>
    <div className="bb-label" style={{ color: 'var(--gold)', marginBottom: 6 }}>{label}</div>
    <div style={{
      fontFamily: 'Inter, sans-serif', fontSize: 12, lineHeight: 1.45,
      color: 'var(--ink-soft)',
    }}>{value}</div>
  </div>
);

// ───────────── RESERVAS (inline mini form) ─────────────
const SERVICES_LIST = [
  { id: 's1', name: 'Corte clásico', time: '40min', price: 10000 },
  { id: 's2', name: 'Fade premium', time: '50min', price: 13000 },
  { id: 's5', name: 'Tratamiento barba', time: '40min', price: 13000 },
  { id: 's6', name: 'Pack Bread Way', time: '90min', price: 24000 },
];

const BARBERS = [
  { id: 'b1', name: 'Matías', role: 'Fundador' },
  { id: 'b2', name: 'Diego', role: 'Barber' },
  { id: 'b3', name: 'Andrés', role: 'Barber' },
];

const TIMES = ['12:00', '13:30', '15:00', '16:30', '18:00', '19:00'];

const Reservas = () => {
  const [service, setService] = React.useState('s2');
  const [barber, setBarber] = React.useState('b1');
  const [day, setDay] = React.useState(2);
  const [time, setTime] = React.useState('15:00');
  const [nombre, setNombre] = React.useState('');
  const [telefono, setTelefono] = React.useState('');
  const [enviando, setEnviando] = React.useState(false);
  const [error, setError] = React.useState('');

  const days = React.useMemo(() => {
    const today = new Date();
    return Array.from({ length: 7 }, (_, i) => {
      const d = new Date(today);
      d.setDate(today.getDate() + i);
      return d;
    });
  }, []);

  const dayLabels = ['Dom','Lun','Mar','Mié','Jue','Vie','Sáb'];
  const monthLabels = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];

  const selected = SERVICES_LIST.find(s => s.id === service);
  const selBarber = BARBERS.find(b => b.id === barber);
  const selDate = days[day];

  const confirmar = async () => {
    setError('');
    if (!nombre.trim() || !telefono.trim()) {
      setError('Completa tu nombre y teléfono para reservar.');
      return;
    }
    const fechaTexto = `${dayLabels[selDate.getDay()]} ${selDate.getDate()} ${monthLabels[selDate.getMonth()]}`;
    setEnviando(true);
    try {
      await fetch('/guardar-reserva.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          servicio: selected.name,
          precio: selected.price,
          profesional: selBarber.name,
          fecha: fechaTexto,
          hora: time,
          cliente_nombre: nombre.trim(),
          cliente_telefono: telefono.trim(),
        }),
      });
    } catch (e) {
      // Si falla el guardado igual dejamos que el cliente confirme por WhatsApp.
    }
    setEnviando(false);
    const texto = `Hola! Quiero reservar:\n• Nombre: ${nombre.trim()}\n• Servicio: ${selected.name}\n• Profesional: ${selBarber.name}\n• Fecha: ${fechaTexto}\n• Hora: ${time}\n• Total: $${selected.price.toLocaleString('es-CL')}`;
    window.open(`https://wa.me/56984740024?text=${encodeURIComponent(texto)}`, '_blank', 'noreferrer');
  };

  const pagarConTarjeta = async () => {
    setError('');
    if (!nombre.trim() || !telefono.trim()) {
      setError('Completa tu nombre y teléfono para reservar.');
      return;
    }
    const fechaTexto = `${dayLabels[selDate.getDay()]} ${selDate.getDate()} ${monthLabels[selDate.getMonth()]}`;
    setEnviando(true);
    try {
      const res = await fetch('/guardar-reserva.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          servicio: selected.name,
          precio: selected.price,
          profesional: selBarber.name,
          fecha: fechaTexto,
          hora: time,
          cliente_nombre: nombre.trim(),
          cliente_telefono: telefono.trim(),
        }),
      });
      const data = await res.json();
      if (!data || !data.id) throw new Error('sin id');
      const form = document.createElement('form');
      form.method = 'POST';
      form.action = '/pago/iniciar.php';
      form.style.display = 'none';
      form.innerHTML =
        '<input type="hidden" name="tipo" value="reserva">' +
        '<input type="hidden" name="id" value="' + data.id + '">';
      document.body.appendChild(form);
      form.submit();
    } catch (e) {
      setEnviando(false);
      setError('No se pudo iniciar el pago con tarjeta. Intenta de nuevo o confirma por WhatsApp.');
    }
  };

  return (
    <section id="reservas" className="bb-section">
      <SectionHead num="06" title="Reservar" subtitle="Selecciona servicio, profesional y horario. Confirmación por WhatsApp." />

      {/* 1. Service */}
      <Field label="01 · Servicio">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {SERVICES_LIST.map(s => (
            <button
              key={s.id}
              onClick={() => setService(s.id)}
              style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '12px 14px',
                background: service === s.id ? 'var(--ink)' : 'var(--paper)',
                color: service === s.id ? 'var(--bg)' : 'var(--ink)',
                border: '1px solid ' + (service === s.id ? 'var(--ink)' : 'var(--line)'),
                cursor: 'pointer', textAlign: 'left',
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{
                  width: 14, height: 14, borderRadius: '50%',
                  border: '1px solid ' + (service === s.id ? 'var(--gold)' : 'var(--line)'),
                  background: service === s.id ? 'var(--gold)' : 'transparent',
                }} />
                <span style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 18 }}>
                  {s.name}
                </span>
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                <span className="bb-label" style={{ color: service === s.id ? 'rgba(250,248,243,0.5)' : 'var(--muted)' }}>
                  {s.time}
                </span>
                <span style={{ fontFamily: "'Cormorant Garamond', serif", fontStyle: 'italic', fontSize: 16 }}>
                  ${s.price.toLocaleString('es-CL')}
                </span>
              </div>
            </button>
          ))}
        </div>
      </Field>

      {/* 2. Barber */}
      <Field label="02 · Profesional">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
          {BARBERS.map(b => (
            <button
              key={b.id}
              onClick={() => setBarber(b.id)}
              style={{
                padding: '14px 6px',
                border: '1px solid ' + (barber === b.id ? 'var(--ink)' : 'var(--line)'),
                background: barber === b.id ? 'var(--ink)' : 'var(--paper)',
                color: barber === b.id ? 'var(--bg)' : 'var(--ink)',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
                cursor: 'pointer',
              }}
            >
              <Placeholder label="" height={48} dark={barber === b.id} style={{ width: 48, borderRadius: '50%' }} />
              <div style={{ fontFamily: "'Cormorant Garamond', serif", fontStyle: 'italic', fontSize: 16, lineHeight: 1 }}>
                {b.name}
              </div>
              <div className="bb-label" style={{
                fontSize: 7, color: barber === b.id ? 'var(--gold)' : 'var(--muted)',
              }}>{b.role}</div>
            </button>
          ))}
        </div>
      </Field>

      {/* 3. Day */}
      <Field label="03 · Día">
        <div className="bb-rail">
          {days.map((d, i) => (
            <button
              key={i}
              onClick={() => setDay(i)}
              style={{
                width: 56, padding: '12px 4px',
                border: '1px solid ' + (day === i ? 'var(--gold)' : 'var(--line)'),
                background: day === i ? 'var(--gold)' : 'var(--paper)',
                color: day === i ? 'var(--paper)' : 'var(--ink)',
                cursor: 'pointer', textAlign: 'center',
              }}
            >
              <div className="bb-label" style={{
                fontSize: 7,
                color: day === i ? 'rgba(255,255,255,0.7)' : 'var(--muted)',
              }}>
                {dayLabels[d.getDay()]}
              </div>
              <div style={{
                fontFamily: "'Cormorant Garamond', serif",
                fontStyle: 'italic', fontSize: 22, lineHeight: 1.1,
              }}>
                {d.getDate()}
              </div>
              <div className="bb-label" style={{
                fontSize: 7,
                color: day === i ? 'rgba(255,255,255,0.7)' : 'var(--muted)',
              }}>
                {monthLabels[d.getMonth()]}
              </div>
            </button>
          ))}
        </div>
      </Field>

      {/* 4. Time */}
      <Field label="04 · Hora">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
          {TIMES.map(t => (
            <button
              key={t}
              onClick={() => setTime(t)}
              style={{
                padding: '14px 4px',
                border: '1px solid ' + (time === t ? 'var(--ink)' : 'var(--line)'),
                background: time === t ? 'var(--ink)' : 'var(--paper)',
                color: time === t ? 'var(--bg)' : 'var(--ink)',
                cursor: 'pointer',
                fontFamily: 'JetBrains Mono, monospace',
                fontSize: 13, letterSpacing: '0.1em',
              }}
            >
              {t}
            </button>
          ))}
        </div>
      </Field>

      {/* 5. Datos de contacto */}
      <Field label="05 · Tus datos">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <input
            type="text"
            placeholder="Nombre completo"
            value={nombre}
            onChange={(e) => setNombre(e.target.value)}
            style={{
              padding: '12px 14px',
              border: '1px solid var(--line)',
              background: 'var(--paper)',
              color: 'var(--ink)',
              fontFamily: 'Inter, sans-serif',
              fontSize: 14,
            }}
          />
          <input
            type="tel"
            placeholder="Teléfono (WhatsApp)"
            value={telefono}
            onChange={(e) => setTelefono(e.target.value)}
            style={{
              padding: '12px 14px',
              border: '1px solid var(--line)',
              background: 'var(--paper)',
              color: 'var(--ink)',
              fontFamily: 'Inter, sans-serif',
              fontSize: 14,
            }}
          />
        </div>
      </Field>

      {/* Summary */}
      <div style={{
        marginTop: 24,
        padding: '18px 16px',
        background: 'var(--ink)',
        color: 'var(--bg)',
      }}>
        <div className="bb-label" style={{ color: 'var(--gold)', marginBottom: 12 }}>— RESUMEN —</div>
        <SummaryRow label="Servicio" value={selected.name} />
        <SummaryRow label="Profesional" value={selBarber.name} />
        <SummaryRow label="Fecha" value={`${dayLabels[selDate.getDay()]} ${selDate.getDate()} ${monthLabels[selDate.getMonth()]} · ${time}`} />
        <SummaryRow label="Total" value={`$${selected.price.toLocaleString('es-CL')}`} bold />

        {error && (
          <div style={{ color: '#ff9d9d', fontSize: 12, marginTop: 10 }}>{error}</div>
        )}

        <button
          onClick={confirmar}
          disabled={enviando}
          className="bb-btn bb-btn--gold bb-btn--block"
          style={{ marginTop: 16, textDecoration: 'none', border: 0, cursor: enviando ? 'default' : 'pointer', opacity: enviando ? 0.7 : 1 }}
        >
          {enviando ? 'Enviando…' : 'Confirmar por WhatsApp'}
        </button>
        <button
          onClick={pagarConTarjeta}
          disabled={enviando}
          className="bb-btn bb-btn--card bb-btn--block"
          style={{ marginTop: 8, cursor: enviando ? 'default' : 'pointer', opacity: enviando ? 0.7 : 1 }}
        >
          Pagar ahora con tarjeta
        </button>
        <div className="bb-small" style={{
          color: 'rgba(250,248,243,0.5)', textAlign: 'center', marginTop: 10,
        }}>
          Recibirás confirmación por WhatsApp al +56 9 8474 0024
        </div>
      </div>
    </section>
  );
};

const Field = ({ label, children }) => (
  <div style={{ marginBottom: 24 }}>
    <div className="bb-label" style={{ color: 'var(--gold)', marginBottom: 10 }}>{label}</div>
    {children}
  </div>
);

const SummaryRow = ({ label, value, bold }) => (
  <div style={{
    display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
    padding: '8px 0',
    borderBottom: '1px solid rgba(250,248,243,0.1)',
  }}>
    <span className="bb-label" style={{ color: 'rgba(250,248,243,0.5)' }}>{label}</span>
    <span style={{
      fontFamily: bold ? "'Cormorant Garamond', serif" : 'Inter',
      fontStyle: bold ? 'italic' : 'normal',
      fontSize: bold ? 22 : 13,
      color: bold ? 'var(--gold)' : 'var(--bg)',
    }}>{value}</span>
  </div>
);

Object.assign(window, { Gerente, Reservas });
