// agendar.jsx — Booking flow (Encuadrado-style multi-step)

const { useState: useStateB } = React;

const BOOKING_SERVICES = [
  { id: 'primera', name: 'Primera conversación', desc: 'Llamada inicial gratuita de 20 min para conocernos y orientarte.', duration: '20 min', price: 'Gratis', color: 'var(--c-sage-ink)', Icon: IconPhone },
  { id: 'deteccion', name: 'Evaluación de AACC', desc: 'Aplicación + entrevista + informe + reunión de devolución.', duration: '2 sesiones · 1h cada una', price: 'Desde $180.000', color: 'var(--c-primary)', Icon: IconSearch },
  { id: 'terapia-individual', name: 'Terapia individual', desc: 'Sesión de psicoterapia o terapia ocupacional.', duration: '45 min', price: '$45.000', color: 'var(--c-accent)', Icon: IconHeart },
  { id: 'taller', name: 'Inscripción a taller', desc: 'Reserva tu cupo en un taller del próximo trimestre.', duration: 'Trimestre completo', price: 'Desde $280.000', color: 'var(--c-sage-ink)', Icon: IconPalette },
  { id: 'kicamp', name: 'Ki Camp vacaciones', desc: 'Inscripción a Camp de verano o invierno.', duration: 'Semana 9-17h', price: '$320.000', color: 'var(--c-mustard-ink)', Icon: IconTent },
  { id: 'academia', name: 'Postulación Academia Ki', desc: 'Agenda una visita a la escuela y reunión informativa.', duration: '1.5h', price: 'Gratis', color: 'var(--c-primary)', Icon: IconSchool },
];

const SPECIALISTS = {
  primera:        ['antonia'],
  deteccion:      ['javiera', 'camila'],
  'terapia-individual': ['javiera', 'isidora', 'camila'],
  taller:         ['sebastian', 'matias'],
  kicamp:         ['sebastian', 'antonia'],
  academia:       ['matias', 'antonia'],
};

const TIME_SLOTS = ['09:00', '10:00', '11:00', '12:00', '15:00', '16:00', '17:00', '18:00'];

// Generate calendar — month grid
function buildMonth(year, month) {
  const first = new Date(year, month, 1);
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const startDow = (first.getDay() + 6) % 7; // Mon=0
  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);
  return cells;
}

const MONTHS_ES = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];

const BookingShell = ({ children, currentStep, onPrev, onNext, canNext, nextLabel = 'Siguiente', showPrev = true, hideFooter = false }) => {
  const steps = [
    { id: 1, label: 'Servicio' },
    { id: 2, label: 'Especialista' },
    { id: 3, label: 'Fecha y hora' },
    { id: 4, label: 'Tus datos' },
    { id: 5, label: 'Confirmación' },
  ];
  return (
    <div className="booking-shell">
      <aside className="booking-aside">
        <div>
          <div style={{fontFamily: 'var(--font-display)', fontSize: 28, letterSpacing: '-0.03em', lineHeight: 1, color: 'var(--bg-soft)'}}>Agenda en Ki</div>
          <p style={{fontSize: 13, opacity: 0.7, marginTop: 8, lineHeight: 1.5}}>
            En menos de 2 minutos reservas tu hora. Te enviamos confirmación al correo.
          </p>
        </div>
        <div className="step-list">
          {steps.map(s => (
            <div key={s.id} className={`step-item ${s.id === currentStep ? 'active' : s.id < currentStep ? 'done' : ''}`}>
              <div className="step-num">{s.id < currentStep ? <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 7 L6 10 L11 4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg> : s.id}</div>
              <div className="step-label">{s.label}</div>
            </div>
          ))}
        </div>
        <div className="booking-brand">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor"><circle cx="7" cy="7" r="6" opacity="0.4" /><circle cx="7" cy="7" r="3" /></svg>
          powered by <b style={{color: 'var(--c-mustard)', marginLeft: 4}}>encuadrado</b>
        </div>
      </aside>
      <div className="booking-main">
        {children}
        {!hideFooter && (
          <div className="booking-foot">
            {showPrev ? (
              <button className="btn-link" onClick={onPrev}><IconChevronLeft /> Volver</button>
            ) : <span />}
            <button className="btn btn-primary" disabled={!canNext} onClick={onNext} style={{opacity: canNext ? 1 : 0.4, pointerEvents: canNext ? 'auto' : 'none'}}>
              {nextLabel} <IconArrowRight />
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

const StepService = ({ value, onChange }) => (
  <>
    <h2>¿Qué necesitas?</h2>
    <p className="sub">Elige el servicio que te interesa. Si no estás seguro, parte por la primera conversación: es gratis.</p>
    <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
      {BOOKING_SERVICES.map(s => (
        <div key={s.id} className={`svc-option ${value === s.id ? 'selected' : ''}`} onClick={() => onChange(s.id)}>
          <div className="svc-icon" style={{background: s.color}}><s.Icon size={28} color="white" /></div>
          <div>
            <h4>{s.name}</h4>
            <p>{s.desc}</p>
            <div className="svc-meta">
              <span><IconClock size={12} /> {s.duration}</span>
              <span>· {s.price}</span>
            </div>
          </div>
          <div style={{width: 22, height: 22, borderRadius: '50%', border: `2px solid ${value === s.id ? 'var(--c-accent)' : 'var(--line)'}`, background: value === s.id ? 'var(--c-accent)' : 'transparent', display: 'grid', placeItems: 'center'}}>
            {value === s.id && <div style={{width: 8, height: 8, borderRadius: '50%', background: 'white'}} />}
          </div>
        </div>
      ))}
    </div>
  </>
);

const StepSpecialist = ({ serviceId, value, onChange }) => {
  const teamByKey = TEAM.reduce((m, p) => { m[p.name.split(' ')[0].toLowerCase()] = p; return m; }, {});
  const ids = SPECIALISTS[serviceId] || Object.keys(teamByKey);
  return (
    <>
      <h2>¿Con quién?</h2>
      <p className="sub">Estos son los especialistas disponibles para este servicio. Todos están formados en altas capacidades.</p>
      <div className="spc-grid">
        {ids.map(id => {
          const p = teamByKey[id];
          if (!p) return null;
          return (
            <div key={id} className={`spc-card ${value === id ? 'selected' : ''}`} onClick={() => onChange(id)}>
              <div className="spc-photo">
                <Placeholder label={p.name} color={p.color} style={{position: 'absolute', inset: 0}} />
              </div>
              <div>
                <h4>{p.name}</h4>
                <div className="role">{p.role}</div>
              </div>
            </div>
          );
        })}
        <div className={`spc-card ${value === 'cualquiera' ? 'selected' : ''}`} onClick={() => onChange('cualquiera')}>
          <div className="spc-photo" style={{background: 'var(--bg-soft)', border: '1.5px dashed var(--line)', display: 'grid', placeItems: 'center'}}>
            <Sparkle size={26} color="var(--c-accent)" />
          </div>
          <div>
            <h4>Cualquiera disponible</h4>
            <div className="role">Más opciones de horario</div>
          </div>
        </div>
      </div>
    </>
  );
};

const StepDateTime = ({ dateValue, timeValue, onChangeDate, onChangeTime }) => {
  const today = new Date(); today.setHours(0,0,0,0);
  const [view, setView] = useStateB({ year: today.getFullYear(), month: today.getMonth() });
  const cells = buildMonth(view.year, view.month);
  const isPast = (d) => {
    if (!d) return false;
    const dd = new Date(view.year, view.month, d);
    return dd < today;
  };
  const isSelected = (d) => {
    if (!d || !dateValue) return false;
    return dateValue.getFullYear() === view.year && dateValue.getMonth() === view.month && dateValue.getDate() === d;
  };
  // Pseudo: weekend = unavailable, plus a few random Tuesdays etc.
  const isUnavail = (d) => {
    if (!d) return false;
    const dd = new Date(view.year, view.month, d);
    const dow = dd.getDay();
    return dow === 0; // domingo
  };
  return (
    <>
      <h2>Elige fecha y hora</h2>
      <p className="sub">Mostramos disponibilidad real. Los horarios se confirman al instante.</p>
      <div className="cal-wrap">
        <div className="cal">
          <div className="cal-head">
            <button onClick={() => setView(v => v.month === 0 ? { year: v.year - 1, month: 11 } : { ...v, month: v.month - 1 })}>
              <IconChevronLeft />
            </button>
            <h4>{MONTHS_ES[view.month]} {view.year}</h4>
            <button onClick={() => setView(v => v.month === 11 ? { year: v.year + 1, month: 0 } : { ...v, month: v.month + 1 })}>
              <IconChevronRight />
            </button>
          </div>
          <div className="cal-grid">
            {['L','M','X','J','V','S','D'].map(d => <div key={d} className="cal-dow">{d}</div>)}
            {cells.map((d, i) => {
              if (!d) return <div key={i} className="cal-day muted"></div>;
              const past = isPast(d);
              const unavail = isUnavail(d);
              const disabled = past || unavail;
              const cls = ['cal-day'];
              if (disabled) cls.push('disabled');
              else cls.push('available');
              if (isSelected(d)) cls.push('selected');
              if (d === today.getDate() && view.year === today.getFullYear() && view.month === today.getMonth()) cls.push('today');
              return (
                <div
                  key={i}
                  className={cls.join(' ')}
                  onClick={() => !disabled && onChangeDate(new Date(view.year, view.month, d))}
                >
                  {d}
                </div>
              );
            })}
          </div>
        </div>
        <div className="time-slots">
          <div className="ts-head">
            {dateValue
              ? dateValue.toLocaleDateString('es-CL', { weekday: 'long', day: 'numeric', month: 'long' })
              : 'Selecciona una fecha primero'}
          </div>
          {dateValue && TIME_SLOTS.map((slot, i) => {
            const taken = i === 2 || i === 5;
            return (
              <div
                key={slot}
                className={`ts-slot ${timeValue === slot ? 'selected' : ''}`}
                onClick={() => !taken && onChangeTime(slot)}
                style={taken ? { opacity: 0.35, textDecoration: 'line-through', cursor: 'not-allowed' } : {}}
              >
                {slot}
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
};

const StepDetails = ({ data, onChange }) => (
  <>
    <h2>Cuéntanos sobre ti</h2>
    <p className="sub">Esta info solo la usamos para preparar la sesión y enviarte la confirmación.</p>
    <div>
      <div className="form-grid">
        <div className="form-row">
          <label>Tu nombre</label>
          <input value={data.parentName} onChange={e => onChange('parentName', e.target.value)} placeholder="María González" />
        </div>
        <div className="form-row">
          <label>Tu teléfono</label>
          <input value={data.phone} onChange={e => onChange('phone', e.target.value)} placeholder="+56 9 ..." />
        </div>
      </div>
      <div className="form-row">
        <label>Correo electrónico</label>
        <input type="email" value={data.email} onChange={e => onChange('email', e.target.value)} placeholder="tu@correo.cl" />
      </div>
      <div className="form-grid">
        <div className="form-row">
          <label>Nombre del niño/a</label>
          <input value={data.childName} onChange={e => onChange('childName', e.target.value)} placeholder="Martín" />
        </div>
        <div className="form-row">
          <label>Edad</label>
          <input value={data.childAge} onChange={e => onChange('childAge', e.target.value)} placeholder="9 años" />
        </div>
      </div>
      <div className="form-row">
        <label>¿Algo que quieras contarnos? (opcional)</label>
        <textarea value={data.notes} onChange={e => onChange('notes', e.target.value)} placeholder="Por ejemplo: ya tiene evaluación previa, lo deriva el colegio, etc." />
      </div>
    </div>
  </>
);

const StepConfirm = ({ summary, onNavigate }) => (
  <div className="confirm-state">
    <div className="check"><IconCheck size={44} color="white" /></div>
    <h2>¡Reserva confirmada!</h2>
    <p>Te enviamos los detalles a <b style={{color: 'var(--ink)'}}>{summary.email || 'tu correo'}</b>. Llegará un recordatorio 24h antes.</p>
    <div className="summary">
      <div className="summary-row"><span>Servicio</span><b>{summary.serviceName}</b></div>
      <div className="summary-row"><span>Con</span><b>{summary.specialistName}</b></div>
      <div className="summary-row"><span>Cuándo</span><b>{summary.when}</b></div>
      <div className="summary-row"><span>Dónde</span><b>Av. Los Leones 1234, Providencia</b></div>
    </div>
    <button className="btn btn-soft" onClick={() => onNavigate('inicio')}>Volver al inicio</button>
  </div>
);

const AgendarScreen = ({ onNavigate, initialService }) => {
  const [step, setStep] = useStateB(1);
  const [service, setService] = useStateB(initialService || '');
  const [specialist, setSpecialist] = useStateB('');
  const [date, setDate] = useStateB(null);
  const [time, setTime] = useStateB('');
  const [data, setData] = useStateB({ parentName: '', email: '', phone: '', childName: '', childAge: '', notes: '' });

  const updateData = (k, v) => useStateB(prev => ({ ...prev, [k]: v })); // placeholder, replaced below
  const onChangeData = (k, v) => {
    const next = { ...data, [k]: v };
    setData(next);
  };

  const canNext = (
    (step === 1 && service) ||
    (step === 2 && specialist) ||
    (step === 3 && date && time) ||
    (step === 4 && data.parentName && data.email && data.childName)
  );

  const teamByKey = TEAM.reduce((m, p) => { m[p.name.split(' ')[0].toLowerCase()] = p; return m; }, {});
  const svcObj = BOOKING_SERVICES.find(s => s.id === service);
  const spcObj = specialist === 'cualquiera' ? { name: 'Cualquier especialista' } : teamByKey[specialist];
  const summary = {
    serviceName: svcObj?.name,
    specialistName: spcObj?.name,
    when: date ? `${date.toLocaleDateString('es-CL', { weekday: 'long', day: 'numeric', month: 'long' })} · ${time}` : '',
    email: data.email,
  };

  return (
    <div data-screen-label="Agendar">
      <section className="hero" style={{paddingBottom: 30, paddingTop: 48}}>
        <div className="container">
          <div style={{maxWidth: 720, position: 'relative'}}>
            <div className="eyebrow"><span className="dot"></span> Agendamiento</div>
            <h1 style={{marginTop: 16, fontSize: 'clamp(36px, 5vw, 56px)'}}>
              Reserva en <span className="hand" style={{color: 'var(--c-accent)', fontSize: '1.1em'}}>2 minutos</span>
            </h1>
            <p className="hero-sub" style={{marginTop: 14}}>
              Elige el servicio, el especialista y el horario que mejor te acomode. Recibirás la confirmación al instante.
            </p>
            <div style={{position: 'absolute', top: -10, right: 0, color: 'var(--c-mustard)'}}><Sun size={70} /></div>
          </div>
        </div>
      </section>
      <section style={{paddingTop: 20, paddingBottom: 80}}>
        <div className="container">
          <BookingShell
            currentStep={step}
            onPrev={() => setStep(s => Math.max(1, s - 1))}
            onNext={() => setStep(s => Math.min(5, s + 1))}
            canNext={canNext}
            showPrev={step > 1 && step < 5}
            nextLabel={step === 4 ? 'Confirmar reserva' : 'Siguiente'}
            hideFooter={step === 5}
          >
            {step === 1 && <StepService value={service} onChange={setService} />}
            {step === 2 && <StepSpecialist serviceId={service} value={specialist} onChange={setSpecialist} />}
            {step === 3 && <StepDateTime dateValue={date} timeValue={time} onChangeDate={setDate} onChangeTime={setTime} />}
            {step === 4 && <StepDetails data={data} onChange={onChangeData} />}
            {step === 5 && <StepConfirm summary={summary} onNavigate={onNavigate} />}
          </BookingShell>
        </div>
      </section>
    </div>
  );
};

Object.assign(window, { AgendarScreen });
