// === Specialized composite inputs: Schedule, FAQ builder, Identity ===

const { useState: useState2, useEffect: useEffect2 } = React;

// ---- SCHEDULE (multi-field) ----
function ScheduleInput({ question, value, onChange }) {
  const v = value || {};
  const update = (k, val) => onChange({ ...v, [k]: val });

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 14, marginTop: 8}}>
      <div className="input-row">
        <div className="input-group">
          <label>Duración</label>
          <select value={v.duration || ''} onChange={(e) => update('duration', e.target.value)}>
            <option value="">Elige...</option>
            <option>15 min</option>
            <option>20 min</option>
            <option>30 min</option>
            <option>45 min</option>
            <option>60 min</option>
          </select>
        </div>
        <div className="input-group">
          <label>Mínimo de anticipación</label>
          <select value={v.advance || ''} onChange={(e) => update('advance', e.target.value)}>
            <option value="">Elige...</option>
            <option>1 hora</option>
            <option>4 horas</option>
            <option>8 horas</option>
            <option>24 horas</option>
            <option>48 horas</option>
          </select>
        </div>
      </div>
      <div className="input-row">
        <div className="input-group">
          <label>Zona horaria</label>
          <input
            value={v.timezone || ''}
            onChange={(e) => update('timezone', e.target.value)}
            placeholder="Santiago"
          />
        </div>
        <div className="input-group">
          <label>Días disponibles</label>
          <input
            value={v.days || ''}
            onChange={(e) => update('days', e.target.value)}
            placeholder="Ej: Lunes a viernes"
          />
        </div>
      </div>
      <div className="input-group">
        <label>Horarios</label>
        <input
          value={v.hours || ''}
          onChange={(e) => update('hours', e.target.value)}
          placeholder="Ej: 10:00 – 14:00 y 16:00 – 18:00"
        />
      </div>
    </div>
  );
}

// ---- FAQ BUILDER ----
function FAQBuilder({ question, value, onChange, context }) {
  const [suggestions, setSuggestions] = useState2([]);
  const [loading, setLoading] = useState2(false);
  const [addingNew, setAddingNew] = useState2(false);
  const [newQ, setNewQ] = useState2('');
  const [newA, setNewA] = useState2('');
  const [editing, setEditing] = useState2(null);
  const [seen, setSeen] = useState2([]);
  const [dragIdx, setDragIdx] = useState2(null);
  const [overIdx, setOverIdx] = useState2(null);

  const selected = value || [];

  function moveSelected(from, to) {
    if (to < 0 || to >= selected.length || from === to) return;
    const next = [...selected];
    const [item] = next.splice(from, 1);
    next.splice(to, 0, item);
    onChange(next);
  }

  useEffect2(() => {
    if (question.aiGenerated) regenerate();
  }, [question.id]);

  async function regenerate() {
    setLoading(true);
    const prev = [...seen, ...suggestions.map(s => s.q)];
    const opts = await window.generateExamples(question, context, prev);
    setSuggestions(opts);
    setSeen(prev);
    setLoading(false);
  }

  const isSelected = (faq) => selected.some(s => s.q === faq.q);

  const toggle = (faq) => {
    if (isSelected(faq)) {
      onChange(selected.filter(s => s.q !== faq.q));
    } else {
      onChange([...selected, faq]);
    }
  };

  const addCustom = () => {
    if (!newQ.trim()) return;
    const n = { q: newQ.trim(), a: newA.trim() || '', custom: true };
    onChange([...selected, n]);
    setNewQ(''); setNewA(''); setAddingNew(false);
  };

  const startEdit = (faq) => setEditing({ ...faq, originalQ: faq.q });

  const saveEdit = () => {
    const next = selected.map(s => s.q === editing.originalQ ? { q: editing.q, a: editing.a, custom: true } : s);
    const nextSuggestions = suggestions.map(s => s.q === editing.originalQ ? { q: editing.q, a: editing.a } : s);
    setSuggestions(nextSuggestions);
    onChange(next.length ? next : [{ q: editing.q, a: editing.a, custom: true }]);
    setEditing(null);
  };

  const keyWord = question.aiGenerateKey === 'questions' ? 'preguntas' : 'FAQs';

  return (
    <>
      {question.aiGenerated && (
        <div className="ai-badge">
          <span className="pulse"></span>
          {loading ? `Generando ${keyWord} para tu negocio…` : `${keyWord} sugeridas para tu negocio`}
        </div>
      )}
      {loading ? (
        <div className="faq-list">
          {[1,2,3,4].map(i => <div key={i} className="skeleton" style={{height: 72}} />)}
        </div>
      ) : (
        <>
        {question.maxSelect && selected.length > question.maxSelect && (
          <div style={{padding: '10px 14px', background: '#FFF4E5', border: '1px solid #F5B95C', borderRadius: 10, fontSize: 13.5, color: '#8A5A00', marginBottom: 10}}>
            ⚠️ Has elegido {selected.length} preguntas. Te recomendamos máximo {question.maxSelect} — más de eso fatiga al lead.
          </div>
        )}
        <div className="faq-list">
          {question.orderable && selected.length > 0 && (
            <div style={{fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 700, color: 'var(--muted)', marginBottom: 2}}>Orden en que se harán</div>
          )}
          {question.orderable && selected.map((faq, si) => (
            <div
              key={`sel-${si}`}
              className="faq-item selected"
              draggable
              onDragStart={(e) => { setDragIdx(si); e.dataTransfer.effectAllowed = 'move'; }}
              onDragOver={(e) => { e.preventDefault(); setOverIdx(si); }}
              onDrop={(e) => { e.preventDefault(); if (dragIdx !== null) moveSelected(dragIdx, si); setDragIdx(null); setOverIdx(null); }}
              onDragEnd={() => { setDragIdx(null); setOverIdx(null); }}
              style={{
                cursor: dragIdx === si ? 'grabbing' : 'grab',
                opacity: dragIdx === si ? 0.4 : 1,
                borderColor: overIdx === si && dragIdx !== null && dragIdx !== si ? 'var(--violet)' : undefined,
                boxShadow: overIdx === si && dragIdx !== null && dragIdx !== si ? '0 0 0 3px rgba(119,47,249,0.15)' : undefined,
                transition: 'border-color 0.15s, box-shadow 0.15s, opacity 0.15s',
              }}
            >
              <div style={{display: 'flex', gap: 10, alignItems: 'flex-start'}}>
                <div style={{color: 'var(--muted)', fontSize: 14, userSelect: 'none', marginTop: 4, cursor: 'grab', letterSpacing: '-2px'}}>⋮⋮</div>
                <div style={{width: 24, height: 24, borderRadius: 6, background: 'var(--violet)', color: 'white', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 11, flexShrink: 0, marginTop: 2}}>{si + 1}</div>
                <div style={{flex: 1}}>
                  <div className="faq-q">{faq.q}</div>
                  <div className="faq-a">{faq.a}</div>
                </div>
                <div style={{display: 'flex', gap: 4}}>
                  <button onClick={() => { if (si === 0) return; const n = [...selected]; [n[si-1], n[si]] = [n[si], n[si-1]]; onChange(n); }} disabled={si === 0} style={{background: 'none', border: '1px solid var(--border)', borderRadius: 6, padding: '2px 8px', cursor: si === 0 ? 'default' : 'pointer', opacity: si === 0 ? 0.3 : 1, fontSize: 12}}>↑</button>
                  <button onClick={() => { if (si === selected.length - 1) return; const n = [...selected]; [n[si+1], n[si]] = [n[si], n[si+1]]; onChange(n); }} disabled={si === selected.length - 1} style={{background: 'none', border: '1px solid var(--border)', borderRadius: 6, padding: '2px 8px', cursor: si === selected.length - 1 ? 'default' : 'pointer', opacity: si === selected.length - 1 ? 0.3 : 1, fontSize: 12}}>↓</button>
                  <button onClick={() => onChange(selected.filter(s => s.q !== faq.q))} style={{background: 'none', border: '1px solid var(--border)', borderRadius: 6, padding: '2px 8px', cursor: 'pointer', fontSize: 12, color: 'var(--muted)'}}>×</button>
                </div>
              </div>
            </div>
          ))}
          {question.orderable && <div style={{fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 700, color: 'var(--muted)', marginTop: 8, marginBottom: 2}}>Sugerencias</div>}
          {suggestions.filter(s => !question.orderable || !isSelected(s)).map((faq, i) => (
            <div key={i} className={`faq-item ${isSelected(faq) ? 'selected' : ''}`}>
              {editing?.originalQ === faq.q ? (
                <>
                  <input
                    className="textfield"
                    style={{fontSize: 16, padding: '4px 0'}}
                    value={editing.q}
                    autoFocus
                    onChange={(e) => setEditing({...editing, q: e.target.value})}
                  />
                  <textarea
                    className="textarea"
                    style={{minHeight: 60, fontSize: 14.5, padding: '8px 10px'}}
                    value={editing.a}
                    onChange={(e) => setEditing({...editing, a: e.target.value})}
                  />
                  <div className="faq-item-controls" style={{opacity: 1}}>
                    <button className="faq-control-btn" onClick={saveEdit} style={{color: 'var(--violet)'}}>Guardar</button>
                    <button className="faq-control-btn" onClick={() => setEditing(null)}>Cancelar</button>
                  </div>
                </>
              ) : (
                <>
                  <div onClick={() => toggle(faq)} style={{cursor: 'pointer'}}>
                    <div className="faq-q">{faq.q}</div>
                    <div className="faq-a">{faq.a}</div>
                  </div>
                  <div className="faq-item-controls">
                    <button className="faq-control-btn" onClick={() => toggle(faq)}>
                      {isSelected(faq) ? '✓ Incluida' : 'Incluir'}
                    </button>
                    <button className="faq-control-btn" onClick={() => startEdit(faq)}>Editar</button>
                  </div>
                </>
              )}
            </div>
          ))}
          {selected.filter(s => s.custom && !suggestions.some(sg => sg.q === s.q)).map((faq, i) => (
            <div key={`custom-${i}`} className="faq-item selected">
              <div className="faq-q">{faq.q}</div>
              <div className="faq-a">{faq.a || <span style={{color: 'var(--muted)'}}>(sin respuesta)</span>}</div>
              <div className="faq-item-controls" style={{opacity: 1}}>
                <span className="faq-control-btn" style={{color: 'var(--violet)', cursor: 'default'}}>Tuya</span>
                <button className="faq-control-btn" onClick={() => onChange(selected.filter(s => s.q !== faq.q))}>Quitar</button>
              </div>
            </div>
          ))}
        </div>
        </>
      )}

      {addingNew ? (
        <div className="faq-item" style={{marginTop: 10, borderColor: 'var(--violet)'}}>
          <input
            autoFocus
            className="textfield"
            style={{fontSize: 16, padding: '4px 0'}}
            value={newQ}
            onChange={(e) => setNewQ(e.target.value)}
            placeholder="Pregunta..."
          />
          <textarea
            className="textarea"
            style={{minHeight: 60, fontSize: 14.5, padding: '8px 10px'}}
            value={newA}
            onChange={(e) => setNewA(e.target.value)}
            placeholder="Respuesta..."
          />
          <div className="faq-item-controls" style={{opacity: 1}}>
            <button className="faq-control-btn" onClick={addCustom} style={{color: 'var(--violet)'}}>Guardar</button>
            <button className="faq-control-btn" onClick={() => { setAddingNew(false); setNewQ(''); setNewA(''); }}>Cancelar</button>
          </div>
        </div>
      ) : (
        <button className="freeform-toggle" onClick={() => setAddingNew(true)} style={{marginTop: 12}}>
          + Agregar una propia
        </button>
      )}

      {question.aiGenerated && (
        <button className={`ai-refresh ${loading ? 'loading' : ''}`} onClick={regenerate} style={{marginLeft: 12}}>
          <svg className={loading ? 'spin' : ''} width="12" height="12" viewBox="0 0 12 12" fill="none">
            <path d="M10.5 6a4.5 4.5 0 1 1-1.32-3.18M10.5 1.5v3h-3" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          Regenerar sugerencias
        </button>
      )}
    </>
  );
}

// ---- IDENTITY FIELDS ----
function IdentityFields({ question, value, onChange, context }) {
  const v = value || {};
  const update = (k, val) => onChange({ ...v, [k]: val });

  const initials = (v.name || '').split(' ').map(x => x[0]).slice(0,2).join('').toUpperCase() || '??';

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 14, marginTop: 8}}>
      <div className="input-row">
        <div className="input-group">
          <label>Nombre del agente</label>
          <input
            value={v.name || ''}
            onChange={(e) => update('name', e.target.value)}
            placeholder="Ej: Laura"
          />
        </div>
        <div className="input-group">
          <label>Cargo / rol</label>
          <input
            value={v.role || ''}
            onChange={(e) => update('role', e.target.value)}
            placeholder="Ej: asesora del equipo"
          />
        </div>
      </div>
    </div>
  );
}

// ---- SECTION INTROS (textos del intersticial por sección) ----
const SECTION_INTROS = {
  1:  { eyebrow: 'Sección 1', title: 'Empecemos por <em>tu negocio</em>', desc: 'Lo básico para que el agente hable tu idioma.' },
  2:  { eyebrow: 'Sección 2', title: 'Ahora la <em>identidad</em> del agente', desc: 'Cómo se presenta y con qué personalidad.' },
  3:  { eyebrow: 'Sección 3', title: 'Tu <em>cliente ideal</em>', desc: 'A quién vamos a atender.' },
  4:  { eyebrow: 'Sección 4', title: 'Los <em>problemas</em> que resuelves', desc: 'Para que el agente conecte con su contexto.' },
  5:  { eyebrow: 'Sección 5', title: 'Elige tus <em>tipos de agente</em>', desc: 'Puedes combinar varios.' },
  6:  { eyebrow: 'Sección 6', title: 'Preguntas <em>frecuentes</em>', desc: 'Lo que llega una y otra vez.' },
  7:  { eyebrow: 'Sección 7', title: 'Flujo de <em>conversación</em>', desc: 'Cómo abrir y qué hacer con casos difíciles.' },
  8:  { eyebrow: 'Sección 8', title: 'Límites y <em>restricciones</em>', desc: 'Lo que el agente no debe decir.' },
  9:  { eyebrow: 'Sección 9', title: 'Tono y <em>personalidad</em>', desc: 'Cómo debe sonar.' },
  10: { eyebrow: '', title: '', desc: '' },
};

// ---- INTERSTITIAL ----
function Interstitial({ section, onContinue }) {
  const data = SECTION_INTROS[section] || { eyebrow: `Sección ${section}`, title: 'Continuamos', desc: '' };
  React.useEffect(() => {
    function onKey(e) {
      if (e.key === 'Enter' || e.key === 'ArrowRight') {
        e.preventDefault();
        onContinue?.();
      }
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onContinue]);
  return (
    <div className="interstitial">
      <div className="interstitial-inner">
        <div className="interstitial-eyebrow">{data.eyebrow}</div>
        <h1 className="interstitial-title" dangerouslySetInnerHTML={{ __html: data.title }} />
        {data.desc && <p className="interstitial-desc">{data.desc}</p>}
        <button className="btn btn-primary" onClick={onContinue} style={{marginTop: 32}}>
          Continuar
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>
    </div>
  );
}

// ---- AGENT TYPES MULTI ----
const AGENT_TYPES_META = [
  {
    id: 'agendador',
    title: 'Agendador',
    desc: 'Califica leads y reserva reuniones en tu calendario.',
    icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="4" width="18" height="18" rx="2"/>
        <line x1="16" y1="2" x2="16" y2="6"/>
        <line x1="8" y1="2" x2="8" y2="6"/>
        <line x1="3" y1="10" x2="21" y2="10"/>
      </svg>
    ),
    steps: ['Saluda','Pre-califica','Entiende objetivo / problema','Presenta reunión','Acuerda horario','Genera agenda'],
  },
  {
    id: 'cotizador',
    title: 'Cotizador',
    desc: 'Pide datos, calcula precios y entrega propuestas.',
    icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <rect x="4" y="2" width="16" height="20" rx="2"/>
        <line x1="8" y1="7" x2="16" y2="7"/>
        <line x1="8" y1="11" x2="16" y2="11"/>
        <line x1="8" y1="15" x2="14" y2="15"/>
      </svg>
    ),
    steps: ['Saluda','Toma datos','Calcula','Entrega precio','Ofrece siguiente paso'],
  },
  {
    id: 'recepcionista',
    title: 'Recepcionista',
    desc: 'Saluda, entiende intención y deriva al agente o persona correcta.',
    icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>
      </svg>
    ),
    steps: ['Saluda','Pregunta intención','Deriva'],
  },
];

function AgentTypesMulti({ question, value, onChange }) {
  const selected = Array.isArray(value) ? value : [];
  function toggle(id) {
    if (selected.includes(id)) onChange(selected.filter(x => x !== id));
    else onChange([...selected, id]);
  }
  return (
    <div className="agent-types-grid">
      {AGENT_TYPES_META.map(t => {
        const isSel = selected.includes(t.id);
        return (
          <div
            key={t.id}
            className={`agent-type-card ${isSel ? 'is-selected' : ''}`}
            data-agent-type={t.id}
            onClick={() => toggle(t.id)}
            role="button"
            tabIndex={0}
            onKeyDown={(e) => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); toggle(t.id); } }}
          >
            <div className="agent-type-check" aria-hidden>{isSel ? '✓' : ''}</div>
            <div className="agent-type-header">
              <div className="agent-type-icon">{t.icon}</div>
              <h3 className="agent-type-title">{t.title}</h3>
            </div>
            <p className="agent-type-desc">{t.desc}</p>
            <div className="agent-flow">
              {t.steps.map((s, i) => (
                <React.Fragment key={i}>
                  <div className="flow-node">
                    <span className="flow-num">{i + 1}</span>
                    <span className="flow-label">{s}</span>
                  </div>
                  {i < t.steps.length - 1 && (
                    <div className="flow-arrow" aria-hidden>
                      <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1.5">
                        <path d="M5 1v8M2 6l3 3 3-3" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                      {isSel && <span className="flow-dot" style={{ animationDelay: `${i * 0.4}s` }}></span>}
                    </div>
                  )}
                </React.Fragment>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ---- STEPPED SLIDER (non-proportional stops) ----
// Usa el mismo layout visual que LinearSlider para máxima consistencia.
// Cada stop ocupa un paso uniforme del track (step=1 sobre el índice).
function SteppedSlider({ question, value, onChange }) {
  const stops = question.stops || [];
  const currentIdx = Math.max(0, stops.findIndex(s => s.value === value?.value));
  const idx = currentIdx === -1 ? 0 : currentIdx;
  const maxIdx = Math.max(1, stops.length - 1);
  const pct = (idx / maxIdx) * 100;
  const currentLabel = stops[idx]?.label || '—';
  return (
    <div className="linear-slider">
      <div className="linear-slider-value">
        <span className="value-big">{currentLabel}</span>
      </div>
      <input
        type="range"
        min={0}
        max={maxIdx}
        step={1}
        value={idx}
        onChange={(e) => onChange(stops[Number(e.target.value)])}
        style={{ '--pct': `${pct}%` }}
      />
      <div className="linear-slider-bounds">
        <span>{stops[0]?.label || ''}</span>
        <span>{stops[maxIdx]?.label || ''}</span>
      </div>
    </div>
  );
}

// ---- LINEAR SLIDER ----
function LinearSlider({ question, value, onChange }) {
  const min = question.min ?? 10;
  const max = question.max ?? 120;
  const step = question.step ?? 5;
  const unit = question.unit ?? 'min';
  const current = typeof value === 'number' ? value : (question.default ?? min);
  const pct = ((current - min) / (max - min)) * 100;
  return (
    <div className="linear-slider">
      <div className="linear-slider-value">
        <span className="value-big">{current}</span>
        <span className="value-unit">{unit}</span>
      </div>
      <input
        type="range"
        min={min}
        max={max}
        step={step}
        value={current}
        onChange={(e) => onChange(Number(e.target.value))}
        style={{ '--pct': `${pct}%` }}
      />
      <div className="linear-slider-bounds">
        <span>{min} {unit}</span>
        <span>{max} {unit}</span>
      </div>
    </div>
  );
}

// ---- INFO CARD (non-interactive informational block) ----
function InfoCard({ question }) {
  return (
    <div className="info-card">
      <div className="info-card-icon" aria-hidden>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="10"/>
          <line x1="12" y1="8" x2="12" y2="12"/>
          <line x1="12" y1="16" x2="12.01" y2="16"/>
        </svg>
      </div>
      <div className="info-card-body">
        <h4>{question.infoTitle || 'Listo'}</h4>
        <p>{question.infoBody}</p>
      </div>
    </div>
  );
}

// ---- WEEKLY AVAILABILITY GRID ----
const DAYS = [
  { id: 'mon', label: 'LUN' },
  { id: 'tue', label: 'MAR' },
  { id: 'wed', label: 'MIÉ' },
  { id: 'thu', label: 'JUE' },
  { id: 'fri', label: 'VIE' },
  { id: 'sat', label: 'SÁB' },
  { id: 'sun', label: 'DOM' },
];
const HOUR_START = 8;
const HOUR_END = 22;

function toHHMM(hour) { return `${String(hour).padStart(2, '0')}:00`; }

function mergeBlocks(blocks) {
  if (!blocks || blocks.length < 2) return blocks || [];
  const sorted = [...blocks].sort((a, b) => a.start.localeCompare(b.start));
  const out = [sorted[0]];
  for (let i = 1; i < sorted.length; i++) {
    const prev = out[out.length - 1];
    const cur = sorted[i];
    if (cur.start <= prev.end) {
      prev.end = cur.end > prev.end ? cur.end : prev.end;
    } else {
      out.push(cur);
    }
  }
  return out;
}

function WeeklyAvailabilityGrid({ value, onChange, accent }) {
  const availability = value || {};
  const [dragState, setDragState] = React.useState(null);

  function updateDay(day, blocks) {
    const merged = mergeBlocks(blocks.filter(b => b.start !== b.end));
    onChange({ ...availability, [day]: merged });
  }

  function onMouseDownCell(day, hour, e) {
    e.preventDefault();
    setDragState({ day, startHour: hour, currentHour: hour });
  }
  function onMouseEnterCell(day, hour) {
    if (dragState && dragState.day === day) {
      setDragState({ ...dragState, currentHour: hour });
    }
  }

  React.useEffect(() => {
    if (!dragState) return;
    function onUp() {
      const { day, startHour, currentHour } = dragState;
      const s = Math.min(startHour, currentHour);
      const e = Math.max(startHour, currentHour) + 1;
      const newBlock = { start: toHHMM(s), end: toHHMM(e) };
      const existing = availability[day] || [];
      updateDay(day, [...existing, newBlock]);
      setDragState(null);
    }
    window.addEventListener('mouseup', onUp);
    return () => window.removeEventListener('mouseup', onUp);
  }, [dragState, availability]);

  function removeBlock(day, idx) {
    const existing = [...(availability[day] || [])];
    existing.splice(idx, 1);
    updateDay(day, existing);
  }

  function dragPreviewFor(day) {
    if (!dragState || dragState.day !== day) return null;
    const s = Math.min(dragState.startHour, dragState.currentHour);
    const e = Math.max(dragState.startHour, dragState.currentHour) + 1;
    return { s, e };
  }

  const hours = [];
  for (let h = HOUR_START; h < HOUR_END; h++) hours.push(h);

  return (
    <div className="avail-grid" style={{ '--avail-accent': accent || 'var(--accent)' }}>
      <div className="avail-header-row">
        <div className="avail-time-header"></div>
        {DAYS.map(d => <div key={d.id} className="avail-day-header">{d.label}</div>)}
      </div>
      <div className="avail-body">
        <div className="avail-time-col">
          {hours.map(h => (
            <div key={h} className="avail-time-label">{toHHMM(h)}</div>
          ))}
        </div>
        {DAYS.map(d => {
          const blocks = availability[d.id] || [];
          const preview = dragPreviewFor(d.id);
          return (
            <div key={d.id} className="avail-day-col">
              {hours.map(h => (
                <div
                  key={h}
                  className="avail-cell"
                  onMouseDown={(e) => onMouseDownCell(d.id, h, e)}
                  onMouseEnter={() => onMouseEnterCell(d.id, h)}
                ></div>
              ))}
              {blocks.map((b, i) => {
                const sH = parseInt(b.start.split(':')[0]);
                const eH = parseInt(b.end.split(':')[0]);
                const top = ((sH - HOUR_START) / (HOUR_END - HOUR_START)) * 100;
                const height = ((eH - sH) / (HOUR_END - HOUR_START)) * 100;
                return (
                  <div
                    key={i}
                    className="avail-block"
                    style={{ top: `${top}%`, height: `${height}%` }}
                    onClick={(e) => { e.stopPropagation(); removeBlock(d.id, i); }}
                    title="Click para eliminar"
                  >
                    <div className="avail-block-range">{b.start} - {b.end}</div>
                    <div className="avail-block-dur">{eH - sH}h</div>
                  </div>
                );
              })}
              {preview && (
                <div
                  className="avail-block is-preview"
                  style={{
                    top: `${((preview.s - HOUR_START) / (HOUR_END - HOUR_START)) * 100}%`,
                    height: `${((preview.e - preview.s) / (HOUR_END - HOUR_START)) * 100}%`,
                  }}
                ></div>
              )}
            </div>
          );
        })}
      </div>
      <p className="avail-hint">Arrastra para crear bloques · click en un bloque para eliminar</p>
    </div>
  );
}

// ---- CALLERS LIST ----
function colorFromName(name) {
  if (!name) return 'var(--lavender)';
  let hash = 0;
  for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) | 0;
  const palette = ['#772FF9', '#7B89FF', '#2B246C', '#9B3FE3', '#2D8A5F', '#C4632C'];
  return palette[Math.abs(hash) % palette.length];
}

function CallersList({ value, onChange }) {
  const callers = Array.isArray(value) ? value : [];
  function update(idx, patch) {
    const next = [...callers];
    next[idx] = { ...next[idx], ...patch };
    onChange(next);
  }
  function add() {
    const id = 'c_' + Date.now();
    onChange([...callers, { id, name: '', email: '', availability: {} }]);
  }
  function remove(idx) {
    const next = [...callers];
    next.splice(idx, 1);
    onChange(next);
  }
  return (
    <div className="callers-list">
      {callers.length === 0 && (
        <div className="callers-empty">Aún no hay personas. Agrega al menos una.</div>
      )}
      {callers.map((c, idx) => {
        const color = colorFromName(c.name);
        return (
          <div key={c.id} className="caller-card">
            <div className="caller-header">
              <div className="caller-avatar" style={{ background: color }}>
                {(c.name?.[0] || '?').toUpperCase()}
              </div>
              <div className="caller-fields">
                <input
                  type="text"
                  placeholder="Nombre"
                  value={c.name}
                  onChange={(e) => update(idx, { name: e.target.value })}
                />
                <input
                  type="email"
                  placeholder="correo@empresa.com"
                  value={c.email}
                  onChange={(e) => update(idx, { email: e.target.value })}
                />
              </div>
              <button
                type="button"
                className="caller-remove"
                onClick={() => remove(idx)}
                aria-label="Eliminar persona"
              >×</button>
            </div>
            <div className="caller-cal-label">Disponibilidad semanal</div>
            <WeeklyAvailabilityGrid
              value={c.availability}
              onChange={(a) => update(idx, { availability: a })}
              accent={color}
            />
          </div>
        );
      })}
      <button type="button" className="caller-add" onClick={add}>
        + Agregar persona
      </button>
    </div>
  );
}

// ---- DRAG ORDER QUESTIONS ----
function DragOrderQuestions({ question, value, onChange, context }) {
  const items = Array.isArray(value) ? value : [];
  const [suggestions, setSuggestions] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [newText, setNewText] = React.useState('');
  const [dragIdx, setDragIdx] = React.useState(null);
  const [overIdx, setOverIdx] = React.useState(null);

  React.useEffect(() => {
    if (!question.aiGenerated) return;
    let cancelled = false;
    (async () => {
      setLoading(true);
      const opts = await window.generateExamples(question, context, []);
      if (!cancelled) {
        const texts = (opts || []).map(o => typeof o === 'string' ? o : (o.q || o.label || ''));
        setSuggestions(texts.filter(Boolean));
        setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [question.id]);

  function add(text) {
    const t = text.trim();
    if (!t) return;
    onChange([...items, t]);
  }
  function remove(i) {
    const next = [...items]; next.splice(i, 1); onChange(next);
  }
  function move(from, to) {
    if (from === to || to < 0 || to >= items.length) return;
    const next = [...items];
    const [it] = next.splice(from, 1);
    next.splice(to, 0, it);
    onChange(next);
  }

  return (
    <div className="drag-order">
      <div className="drag-order-items">
        {items.map((it, i) => (
          <div
            key={i}
            className={`drag-order-item ${dragIdx === i ? 'is-dragging' : ''} ${overIdx === i ? 'is-over' : ''}`}
            draggable
            onDragStart={() => setDragIdx(i)}
            onDragOver={(e) => { e.preventDefault(); setOverIdx(i); }}
            onDragEnd={() => { setDragIdx(null); setOverIdx(null); }}
            onDrop={() => { move(dragIdx, i); setDragIdx(null); setOverIdx(null); }}
          >
            <span className="drag-order-handle" aria-hidden>⋮⋮</span>
            <span className="drag-order-num">{i + 1}</span>
            <input
              type="text"
              value={it}
              onChange={(e) => { const n = [...items]; n[i] = e.target.value; onChange(n); }}
            />
            <button type="button" className="drag-order-del" onClick={() => remove(i)} aria-label="Eliminar">×</button>
          </div>
        ))}
      </div>
      <div className="drag-order-add">
        <input
          type="text"
          placeholder="Agregar una pregunta…"
          value={newText}
          onChange={(e) => setNewText(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); add(newText); setNewText(''); } }}
        />
        <button type="button" onClick={() => { add(newText); setNewText(''); }}>Agregar</button>
      </div>
      {suggestions.length > 0 && (
        <div className="drag-order-suggestions">
          <div className="drag-order-suggestions-label">Sugerencias</div>
          {suggestions.filter(s => !items.includes(s)).map((s, i) => (
            <button key={i} type="button" className="suggestion-chip" onClick={() => add(s)}>+ {s}</button>
          ))}
        </div>
      )}
      {loading && <div className="drag-order-loading">Generando sugerencias…</div>}
    </div>
  );
}

// ---- TEAM MEMBER FIELD (name + email) ----
function TeamMemberField({ value, onChange }) {
  const v = value || { name: '', email: '' };
  return (
    <div className="team-member-field">
      <div className="input-group">
        <label>Nombre</label>
        <input type="text" value={v.name} onChange={(e) => onChange({ ...v, name: e.target.value })} placeholder="Ej: Carlos Díaz" />
      </div>
      <div className="input-group">
        <label>Correo</label>
        <input type="email" value={v.email} onChange={(e) => onChange({ ...v, email: e.target.value })} placeholder="carlos@empresa.com" />
      </div>
    </div>
  );
}

// ---- ROUTING LIST (intención → destino) ----
function RoutingList({ question, value, onChange, context }) {
  const items = Array.isArray(value) ? value : [];
  const [suggestions, setSuggestions] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const otherAgents = (context.agent_types || []).filter(t => t !== 'recepcionista');

  React.useEffect(() => {
    if (!question.aiGenerated) return;
    let cancelled = false;
    (async () => {
      setLoading(true);
      const opts = await window.generateExamples(question, context, []);
      if (!cancelled) {
        const texts = (opts || []).map(o => typeof o === 'string' ? o : (o.intent || o.label || ''));
        setSuggestions(texts.filter(Boolean));
        setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [question.id]);

  function add(intent) {
    onChange([...items, { intent: intent || '', kind: otherAgents[0] ? 'agent' : 'team', agent: otherAgents[0] || '', teamName: '', teamEmail: '' }]);
  }
  function update(i, patch) {
    const next = [...items]; next[i] = { ...next[i], ...patch }; onChange(next);
  }
  function remove(i) {
    const next = [...items]; next.splice(i, 1); onChange(next);
  }

  return (
    <div className="routing-list">
      {items.map((it, i) => (
        <div key={i} className="routing-item">
          <div className="routing-intent">
            <label>Cuando el cliente…</label>
            <input
              type="text"
              value={it.intent}
              onChange={(e) => update(i, { intent: e.target.value })}
              placeholder="Ej: quiere cotizar"
            />
          </div>
          <div className="routing-arrow">→</div>
          <div className="routing-dest">
            <label>Deriva a…</label>
            <select
              value={it.kind}
              onChange={(e) => update(i, { kind: e.target.value })}
            >
              <option value="agent" disabled={otherAgents.length === 0}>
                {otherAgents.length === 0 ? 'Otro agente (no hay otros configurados)' : 'Otro agente'}
              </option>
              <option value="team">Persona del equipo</option>
            </select>
            {it.kind === 'agent' && otherAgents.length > 0 && (
              <select value={it.agent} onChange={(e) => update(i, { agent: e.target.value })} style={{ marginTop: 6 }}>
                {otherAgents.map(a => <option key={a} value={a}>{a[0].toUpperCase() + a.slice(1)}</option>)}
              </select>
            )}
            {it.kind === 'team' && (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginTop: 6 }}>
                <input type="text" placeholder="Nombre" value={it.teamName} onChange={(e) => update(i, { teamName: e.target.value })} />
                <input type="email" placeholder="correo@empresa.com" value={it.teamEmail} onChange={(e) => update(i, { teamEmail: e.target.value })} />
              </div>
            )}
          </div>
          <button type="button" className="routing-del" onClick={() => remove(i)} aria-label="Eliminar">×</button>
        </div>
      ))}
      <button type="button" className="routing-add" onClick={() => add('')}>+ Agregar derivación</button>
      {suggestions.length > 0 && (
        <div className="routing-suggestions">
          <div className="routing-suggestions-label">Sugerencias</div>
          {suggestions.filter(s => !items.some(it => it.intent === s)).map((s, i) => (
            <button key={i} type="button" className="suggestion-chip" onClick={() => add(s)}>+ {s}</button>
          ))}
        </div>
      )}
      {loading && <div className="drag-order-loading">Generando sugerencias…</div>}
    </div>
  );
}

// ---- AGENT INTRO (intro screen before a sub-flow) ----
function AgentIntro({ question }) {
  // Look up agent meta for the icon if available
  const meta = (window.AGENT_TYPES_META || []).find(m => m.id === question.agentId);
  return (
    <div className="agent-intro">
      {meta && (
        <div className="agent-intro-icon" style={{ color: `var(--accent)` }}>
          {meta.icon}
        </div>
      )}
      {question.bullets && question.bullets.length > 0 && (
        <ul className="agent-intro-bullets">
          {question.bullets.map((b, i) => <li key={i}>{b}</li>)}
        </ul>
      )}
    </div>
  );
}

Object.assign(window, { ScheduleInput, FAQBuilder, IdentityFields, Interstitial, SECTION_INTROS, AgentTypesMulti, AGENT_TYPES_META, SteppedSlider, LinearSlider, InfoCard, WeeklyAvailabilityGrid, CallersList, DragOrderQuestions, TeamMemberField, RoutingList, AgentIntro });
