// dr-diagnostic.jsx — PROFESSIONAL APPOINTMENT SCHEDULER (calendar + slots)

function Diagnostic() {
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

  const [viewY, setViewY] = React.useState(today.getFullYear());
  const [viewM, setViewM] = React.useState(today.getMonth());
  const [sel, setSel] = React.useState(null);          // selected Date
  const [time, setTime] = React.useState('');
  const [modality, setModality] = React.useState('tel');
  const [f, setF] = React.useState({ nombre: '', empresa: '', correo: '', telefono: '' });
  const [errors, setErrors] = React.useState({});
  const [confirmed, setConfirmed] = React.useState(false);

  const MONTHS = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
  const DOW = ['L', 'M', 'M', 'J', 'V', 'S', 'D'];
  const SLOTS = ['09:00', '10:00', '11:00', '12:00', '16:00', '17:00'];
  const MODES = [
    {
      id: 'tel', label: 'Teléfono', sub: 'Le llamamos',
      icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 4h4l2 5-2.5 1.5a11 11 0 005 5L15 13l5 2v4a2 2 0 01-2 2A16 16 0 013 6a2 2 0 012-2z"/></svg>,
    },
    {
      id: 'correo', label: 'Correo', sub: 'Le escribimos',
      icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M2 7l10 7 10-7"/></svg>,
    },
  ];

  // ---- calendar grid ----
  const firstDay = new Date(viewY, viewM, 1);
  let startOffset = (firstDay.getDay() + 6) % 7; // Monday-first
  const daysInMonth = new Date(viewY, viewM + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < startOffset; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(viewY, viewM, d));

  const isPast = (date) => date < today;
  const isWeekend = (date) => { const g = date.getDay(); return g === 0 || g === 6; };
  const disabled = (date) => !date || isPast(date) || isWeekend(date);
  const sameDay = (a, b) => a && b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();

  const atFirstMonth = viewY === today.getFullYear() && viewM === today.getMonth();
  const prevMonth = () => { if (atFirstMonth) return; const m = viewM - 1; if (m < 0) { setViewM(11); setViewY(viewY - 1); } else setViewM(m); };
  const nextMonth = () => { const m = viewM + 1; if (m > 11) { setViewM(0); setViewY(viewY + 1); } else setViewM(m); };

  const validate = () => {
    const e = {};
    if (!sel) e.date = 1;
    if (!time) e.time = 1;
    if (!f.nombre.trim()) e.nombre = 1;
    if (!f.empresa.trim()) e.empresa = 1;
    if (!f.correo.trim()) e.correo = 1;
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.correo)) e.correo = 1;
    if (!f.telefono.trim()) e.telefono = 1;
    setErrors(e);
    return Object.keys(e).length === 0;
  };
  const confirm = () => { if (validate()) setConfirmed(true); };
  const reset = () => { setSel(null); setTime(''); setModality('tel'); setF({ nombre: '', empresa: '', correo: '', telefono: '' }); setErrors({}); setConfirmed(false); };

  const fmtDate = (d) => d ? `${['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'][d.getDay()]} ${d.getDate()} de ${MONTHS[d.getMonth()].toLowerCase()}, ${d.getFullYear()}` : '';

  // ---------- styles ----------
  const sec = { padding: '116px 0', borderTop: '1px solid var(--line)' };
  const card = { display: 'grid', gridTemplateColumns: '0.82fr 1.18fr', border: '1px solid var(--line)', borderRadius: 16, overflow: 'hidden', background: 'var(--panel)', boxShadow: '0 40px 110px -55px rgba(0,0,0,0.9)' };

  // left context pane
  const ctx = { padding: '40px 36px', background: 'var(--void-2)', borderRight: '1px solid var(--line)', display: 'flex', flexDirection: 'column' };
  const ctxIcon = { width: 46, height: 46, borderRadius: 11, background: 'rgba(255,255,255,0.05)', border: '1px solid var(--line)', display: 'grid', placeItems: 'center', marginBottom: 22 };
  const ctxTitle = { fontFamily: "'Space Grotesk', sans-serif", fontWeight: 500, fontSize: 26, lineHeight: 1.15, letterSpacing: '-0.02em', color: 'var(--text)' };
  const ctxMeta = { marginTop: 22, display: 'flex', flexDirection: 'column', gap: 13 };
  const metaItem = { display: 'flex', alignItems: 'center', gap: 11, fontSize: 14, color: 'var(--muted)' };
  const metaIco = { color: 'var(--muted)', fontFamily: "'JetBrains Mono', monospace", fontSize: 13, width: 18, textAlign: 'center' };
  const ctxList = { marginTop: 26, paddingTop: 22, borderTop: '1px solid var(--line)', display: 'flex', flexDirection: 'column', gap: 12 };
  const listItem = { display: 'flex', gap: 11, fontSize: 13.5, lineHeight: 1.5, color: 'var(--muted)' };
  const check = { color: 'var(--text)', flexShrink: 0 };

  // right booking pane
  const book = { padding: '36px 36px' };
  const label = { fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: '0.16em', color: 'var(--muted)', textTransform: 'uppercase', marginBottom: 12 };

  const modeRow = { display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10, marginBottom: 26 };
  const modeCard = (on) => ({
    padding: '14px 16px', borderRadius: 10, cursor: 'pointer',
    border: '1px solid ' + (on ? 'rgba(45,212,191,0.35)' : 'var(--line)'),
    background: on ? 'rgba(255,255,255,0.04)' : 'var(--void-2)',
    transition: 'all 0.2s', display: 'flex', flexDirection: 'column', gap: 10,
    boxShadow: on ? 'inset 0 0 0 1px rgba(45,212,191,0.15)' : 'none',
  });
  const modeIcon = (on) => ({ color: on ? 'var(--text)' : 'var(--muted)', transition: 'color 0.2s' });
  const modeLabel = (on) => ({ fontFamily: "'Space Grotesk', sans-serif", fontSize: 14, fontWeight: 500, color: 'var(--text)', letterSpacing: '-0.01em' });
  const modeSub = { fontSize: 11, color: 'var(--muted)', fontFamily: "'JetBrains Mono', monospace", letterSpacing: '0.06em' };

  const splitRow = { display: 'grid', gridTemplateColumns: '1.15fr 0.85fr', gap: 26, marginBottom: 26 };

  // calendar
  const calHead = { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 };
  const calNav = (dis) => ({ width: 30, height: 30, borderRadius: 8, border: '1px solid var(--line)', background: 'var(--void-2)', color: dis ? 'rgba(133,147,163,0.3)' : 'var(--text)', cursor: dis ? 'not-allowed' : 'pointer', display: 'grid', placeItems: 'center', fontSize: 15, transition: 'all 0.18s' });
  const calMonth = { fontFamily: "'Space Grotesk', sans-serif", fontSize: 16, fontWeight: 500, color: 'var(--text)' };
  const dowRow = { display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 4, marginBottom: 6 };
  const dowCell = { textAlign: 'center', fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: 'var(--muted)', padding: '4px 0' };
  const calGrid = { display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 4 };
  const dayCell = (date) => {
    const on = sameDay(date, sel);
    const dis = disabled(date);
    return {
      aspectRatio: '1/1', display: 'grid', placeItems: 'center', borderRadius: 8,
      fontFamily: "'IBM Plex Sans', sans-serif", fontSize: 13.5,
      cursor: !date ? 'default' : dis ? 'not-allowed' : 'pointer',
      color: !date ? 'transparent' : on ? '#fff' : dis ? 'rgba(133,147,163,0.32)' : 'var(--text)',
      background: on ? 'rgba(255,255,255,0.12)' : 'transparent',
      border: '1px solid ' + (on ? 'rgba(255,255,255,0.3)' : 'transparent'),
      fontWeight: on ? 600 : 400, transition: 'all 0.15s',
      textDecoration: dis && date && !isWeekend(date) ? 'line-through' : 'none',
    };
  };

  // time slots
  const slotsWrap = { display: 'flex', flexDirection: 'column', gap: 8 };
  const slot = (on) => ({ padding: '11px 0', textAlign: 'center', borderRadius: 9, cursor: sel ? 'pointer' : 'not-allowed', border: '1px solid ' + (on ? 'rgba(255,255,255,0.25)' : 'var(--line)'), background: on ? 'rgba(255,255,255,0.08)' : 'var(--void-2)', color: on ? 'var(--text)' : sel ? 'var(--text)' : 'rgba(133,147,163,0.4)', fontFamily: "'JetBrains Mono', monospace", fontSize: 13.5, transition: 'all 0.15s' });

  // contact
  const inputRow = { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12 };
  const inp = (err) => ({ width: '100%', border: '1px solid ' + (err ? 'rgba(255,95,87,0.6)' : 'var(--line)'), borderRadius: 9, background: 'var(--void-2)', padding: '12px 14px', fontFamily: "'IBM Plex Sans', sans-serif", fontSize: 14, color: 'var(--text)', outline: 'none', transition: 'border-color 0.2s' });

  const footer = { marginTop: 24, paddingTop: 22, borderTop: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' };
  const summary = { fontFamily: "'JetBrains Mono', monospace", fontSize: 12, color: 'var(--muted)', letterSpacing: '0.04em' };

  // ---------- confirmation ----------
  if (confirmed) {
    const conf = { padding: '64px 48px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center' };
    const ring = { width: 76, height: 76, borderRadius: '50%', background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.2)', display: 'grid', placeItems: 'center', marginBottom: 26 };
    const recap = { marginTop: 30, border: '1px solid var(--line)', borderRadius: 12, background: 'var(--void-2)', overflow: 'hidden', textAlign: 'left', width: '100%', maxWidth: 460 };
    const recapRow = (last) => ({ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '15px 20px', borderBottom: last ? 'none' : '1px solid var(--line)' });
    const rk = { fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: '0.1em', color: 'var(--muted)', textTransform: 'uppercase' };
    const rv = { fontFamily: "'IBM Plex Sans', sans-serif", fontSize: 14, color: 'var(--text)', fontWeight: 500, textAlign: 'right' };
    const modeLabelOf = MODES.find((m) => m.id === modality)?.label;
    return (
      <section id="diagnostico" style={sec}>
        <div className="container">
          <SectionHeaderLocal />
          <div style={card} data-reveal>
            <div style={{ ...conf, gridColumn: '1 / -1' }}>
              <div style={ring}><svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--text)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg></div>
              <div style={{ fontFamily: "'Space Grotesk', sans-serif", fontWeight: 500, fontSize: 34, letterSpacing: '-0.02em', color: 'var(--text)' }}>Cita confirmada</div>
              <p style={{ fontSize: 15.5, lineHeight: 1.6, color: 'var(--muted)', marginTop: 12, maxWidth: 440 }}>
                Le enviamos la invitación a <strong style={{ color: 'var(--text)' }}>{f.correo}</strong> con los detalles y el enlace. Le esperamos.
              </p>
              <div style={recap}>
                <div style={recapRow(false)}><span style={rk}>Fecha</span><span style={rv}>{fmtDate(sel)}</span></div>
                <div style={recapRow(false)}><span style={rk}>Hora</span><span style={rv}>{time} h · 30 min</span></div>
                <div style={recapRow(false)}><span style={rk}>Modalidad</span><span style={rv}>{modeLabelOf}</span></div>
                <div style={recapRow(true)}><span style={rk}>A nombre de</span><span style={rv}>{f.nombre} · {f.empresa}</span></div>
              </div>
              <div style={{ marginTop: 28, display: 'flex', gap: 12 }}>
                <button onClick={reset} type="button" className="dr-btn dr-btn-ghost">Agendar otra</button>
                <a href="#top" className="dr-btn dr-btn-primary">Volver al inicio<span className="dr-arrow">→</span></a>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section id="diagnostico" style={sec}>
      <div className="container">
        <SectionHeaderLocal />
        <div style={card} data-reveal className="dr-sched-card">
          {/* LEFT — context */}
          <div style={ctx} className="dr-sched-ctx">
            <div style={ctxIcon}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--signal)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" /><path d="M16 2v4M8 2v4M3 10h18" /></svg>
            </div>
            <div style={ctxTitle}>Diagnóstico técnico</div>
            <div style={ctxMeta}>
              <div style={metaItem}><span style={metaIco}>◷</span> 30 minutos</div>
              <div style={metaItem}><span style={metaIco}>$</span> Sin costo, sin compromiso</div>
              <div style={metaItem}><span style={metaIco}>◆</span> Con un ingeniero, no un vendedor</div>
            </div>
            <div style={ctxList}>
              {['Revisamos su infraestructura y sistemas actuales.', 'Identificamos riesgos y oportunidades concretas.', 'Le proponemos un plan — o le decimos si no aplica.'].map((t, i) => (
                <div key={i} style={listItem}><span style={check}>✓</span><span>{t}</span></div>
              ))}
            </div>
            <div style={{ marginTop: 'auto', paddingTop: 26, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: 'var(--muted)', letterSpacing: '0.06em', lineHeight: 1.8 }}>
              Horario CDMX (GMT-6)<br />Lun–Vie · 09:00–18:00
            </div>
          </div>

          {/* RIGHT — booking */}
          <div style={book} className="dr-sched-book">
            <div style={label}>Modalidad</div>
            <div style={modeRow}>
              {MODES.map((m) => (
                <div key={m.id} style={modeCard(modality === m.id)} onClick={() => setModality(m.id)}>
                  <span style={modeIcon(modality === m.id)}>{m.icon}</span>
                  <div>
                    <div style={modeLabel(modality === m.id)}>{m.label}</div>
                    <div style={modeSub}>{m.sub}</div>
                  </div>
                </div>
              ))}
            </div>

            <div style={splitRow} className="dr-sched-split">
              {/* calendar */}
              <div>
                <div style={label}>Elija un día {errors.date && <span style={{ color: '#FF5F57' }}>·</span>}</div>
                <div style={calHead}>
                  <button type="button" style={calNav(atFirstMonth)} onClick={prevMonth} disabled={atFirstMonth}>‹</button>
                  <span style={calMonth}>{MONTHS[viewM]} {viewY}</span>
                  <button type="button" style={calNav(false)} onClick={nextMonth}>›</button>
                </div>
                <div style={dowRow}>{DOW.map((d, i) => <div key={i} style={dowCell}>{d}</div>)}</div>
                <div style={calGrid}>
                  {cells.map((date, i) => (
                    <div key={i} style={dayCell(date)}
                      onClick={() => { if (!disabled(date)) { setSel(date); setTime(''); } }}>
                      {date ? date.getDate() : ''}
                    </div>
                  ))}
                </div>
              </div>

              {/* slots */}
              <div>
                <div style={label}>Horario {errors.time && <span style={{ color: '#FF5F57' }}>·</span>}</div>
                {sel ? (
                  <div style={slotsWrap}>
                    {SLOTS.map((s) => (
                      <div key={s} style={slot(time === s)} onClick={() => setTime(s)}>{s} h</div>
                    ))}
                  </div>
                ) : (
                  <div style={{ fontSize: 13, color: 'var(--muted)', lineHeight: 1.6, padding: '14px 0', fontFamily: "'IBM Plex Sans', sans-serif" }}>
                    Seleccione un día disponible para ver los horarios.
                  </div>
                )}
              </div>
            </div>

            <div style={label}>Sus datos</div>
            <div style={inputRow}>
              <input style={inp(errors.nombre)} placeholder="Nombre" value={f.nombre} onChange={(e) => setF({ ...f, nombre: e.target.value })} />
              <input style={inp(errors.empresa)} placeholder="Empresa" value={f.empresa} onChange={(e) => setF({ ...f, empresa: e.target.value })} />
            </div>
            <div style={inputRow}>
              <input style={inp(errors.correo)} placeholder="Correo" type="email" value={f.correo} onChange={(e) => setF({ ...f, correo: e.target.value })} />
              <input style={inp(errors.telefono)} placeholder="Teléfono" type="tel" value={f.telefono} onChange={(e) => setF({ ...f, telefono: e.target.value })} />
            </div>

            <div style={footer}>
              <div style={summary}>
                {sel && time
                  ? <span><span style={{ color: 'var(--muted)' }}>●</span> {sel.getDate()} {MONTHS[sel.getMonth()].toLowerCase()} · {time} h</span>
                  : <span style={{ color: 'rgba(133,147,163,0.7)' }}>○ elija día y horario</span>}
              </div>
              <button type="button" onClick={confirm} className="dr-btn dr-btn-primary">Confirmar diagnóstico<span className="dr-arrow">→</span></button>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 880px){
          .dr-sched-card{ grid-template-columns:1fr !important; }
          .dr-sched-ctx{ border-right:none !important; border-bottom:1px solid var(--line); }
        }
        @media (max-width: 520px){
          .dr-sched-split{ grid-template-columns:1fr !important; }
        }
      `}</style>
    </section>
  );
}

function SectionHeaderLocal() {
  const wrap = { marginBottom: 48, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48, alignItems: 'end' };
  const eyebrow = { marginBottom: 20, display: 'flex', alignItems: 'baseline', gap: 14 };
  const rule = { flex: 1, height: 1, background: 'var(--line)', maxWidth: 80 };
  const h2 = { fontFamily: "'Space Grotesk', sans-serif", fontWeight: 500, fontSize: 'clamp(34px, 4.6vw, 60px)', lineHeight: 1.04, letterSpacing: '-0.028em', color: 'var(--text)', maxWidth: '15ch' };
  const right = { fontSize: 16, lineHeight: 1.65, color: 'var(--muted)', maxWidth: 440 };
  return (
    <div style={wrap} className="dr-section-header">
      <div>
        <div style={eyebrow}><span className="dr-eyebrow">Agendar · Diagnóstico</span><span style={rule}></span></div>
        <h2 style={h2} data-word-reveal>Elija el día. <span style={{ color: 'var(--signal)' }}>Nosotros</span> llegamos.</h2>
      </div>
      <div style={right}>Reserve 30 minutos con un ingeniero. Elija modalidad, día y horario — confirmación inmediata, sin llamadas de venta.</div>
      <style>{`@media (max-width: 880px){ .dr-section-header{ grid-template-columns:1fr !important; align-items:start !important; } }`}</style>
    </div>
  );
}

Object.assign(window, { Diagnostic });
