// Extra input kinds: toggles, link-list, flow-tree, chips with AI
const { useState: useExtraState, useEffect: useExtraEffect } = React;

// ---- TOGGLES (binary dimensions) ----
function TogglesInput({ question, value, onChange, context }) {
  const v = value || {};
  const set = (id, side) => onChange({ ...v, [id]: side });
  const emojiOn = v.emoji === 'right';

  // Initialize defaults on first mount so user can see the highlight animate when switching
  useExtraEffect(() => {
    const toggles = question.toggles || [];
    const needsInit = toggles.some(t => t.defaultSide && v[t.id] === undefined);
    if (needsInit) {
      const next = { ...v };
      toggles.forEach(t => {
        if (t.defaultSide && next[t.id] === undefined) next[t.id] = t.defaultSide;
      });
      onChange(next);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 18, marginTop: 8}}>
      {(question.toggles || []).map((t) => {
        const side = v[t.id]; // 'left' | 'right' | undefined
        const highlightX = side === 'left' ? '0%' : side === 'right' ? '50%' : null;
        return (
        <div key={t.id}>
        {t.title && (
          <div style={{fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 13, letterSpacing: '0.02em', color: 'var(--ink)', marginBottom: 8, paddingLeft: 2}}>
            {t.title}
          </div>
        )}
        <div style={{background: 'white', border: '1.5px solid var(--border)', borderRadius: 14, padding: 14, position: 'relative'}}>
          {highlightX !== null && (
            <div
              aria-hidden
              style={{
                position: 'absolute',
                top: 14,
                bottom: 14,
                left: `calc(${highlightX} + 14px)`,
                width: 'calc(50% - 19px)',
                background: 'linear-gradient(180deg, #FFF 0%, #F6F2FF 100%)',
                border: '1.5px solid var(--violet)',
                borderRadius: 12,
                boxShadow: '0 4px 14px rgba(119,47,249,0.12)',
                transition: 'left 520ms cubic-bezier(.34,1.56,.64,1)',
                pointerEvents: 'none',
                zIndex: 0,
              }}
            />
          )}
          <div style={{display: 'flex', gap: 10, position: 'relative', zIndex: 1}}>
          <button
            className="toggle-side"
            style={{padding: '12px 14px', flex: 1, textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 6, background: 'transparent', border: 'none', cursor: 'pointer', borderRadius: 12}}
            onClick={() => set(t.id, 'left')}
          >
            <div style={{fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 14}}>{t.left}</div>
            <div style={{fontSize: 13, color: 'var(--muted-2)'}}>{t.leftDesc}</div>
            {t.leftEx && (
              <div style={{fontSize: 12.5, color: 'var(--muted)', fontStyle: 'italic', background: 'rgba(0,0,0,0.035)', padding: '8px 10px', borderRadius: 8, marginTop: 2, lineHeight: 1.45}}>
                "{t.leftEx}"
              </div>
            )}
          </button>
          <button
            className="toggle-side"
            style={{padding: '12px 14px', flex: 1, textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 6, background: 'transparent', border: 'none', cursor: 'pointer', borderRadius: 12}}
            onClick={() => set(t.id, 'right')}
          >
            <div style={{fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 14}}>{t.right}</div>
            <div style={{fontSize: 13, color: 'var(--muted-2)'}}>{t.rightDesc}</div>
            {t.rightEx && (
              <div style={{fontSize: 12.5, color: 'var(--muted)', fontStyle: 'italic', background: 'rgba(0,0,0,0.035)', padding: '8px 10px', borderRadius: 8, marginTop: 2, lineHeight: 1.45}}>
                "{t.rightEx}"
              </div>
            )}
          </button>
          </div>
        </div>
        {t.id === 'emoji' && emojiOn && (
          <EmojiSuggestions
            context={context}
            value={v.emojiList}
            onChange={(list) => onChange({ ...v, emojiList: list })}
          />
        )}
        </div>
        );
      })}
    </div>
  );
}

// ---- LINK LIST (name + url, multiple) ----
function LinkListInput({ question, value, onChange }) {
  const list = value || [];
  const add = () => onChange([...list, { name: '', url: '' }]);
  const update = (i, k, val) => onChange(list.map((item, idx) => idx === i ? { ...item, [k]: val } : item));
  const remove = (i) => onChange(list.filter((_, idx) => idx !== i));

  useExtraEffect(() => { if (list.length === 0) add(); }, []);

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 10, marginTop: 8}}>
      {list.map((item, i) => (
        <div key={i} style={{background: 'white', border: '1.5px solid var(--border)', borderRadius: 14, padding: 14, display: 'grid', gridTemplateColumns: '1fr 1.6fr auto', gap: 10, alignItems: 'center'}}>
          <input
            className="textfield"
            style={{fontSize: 15, padding: '8px 0', borderBottomWidth: 1.5}}
            placeholder="Nombre (ej: Plan Pro)"
            value={item.name}
            onChange={(e) => update(i, 'name', e.target.value)}
          />
          <input
            className="textfield"
            style={{fontSize: 15, padding: '8px 0', borderBottomWidth: 1.5}}
            placeholder="https://…"
            value={item.url}
            onChange={(e) => update(i, 'url', e.target.value)}
          />
          <button onClick={() => remove(i)} style={{background: 'none', border: '1px solid var(--border)', borderRadius: 8, padding: '6px 10px', cursor: 'pointer', color: 'var(--muted)', fontSize: 13}}>×</button>
        </div>
      ))}
      <button className="freeform-toggle" onClick={add} style={{alignSelf: 'flex-start'}}>+ Agregar otro link</button>
    </div>
  );
}

// ---- FLOW TREE (ordered decision tree) ----
function FlowTreeInput({ question, value, onChange, context }) {
  const source = context[question.dependsOn] || [];
  const current = value || source;
  const [dragIdx, setDragIdx] = useExtraState(null);
  const [overIdx, setOverIdx] = useExtraState(null);
  useExtraEffect(() => { if (!value && source.length) onChange(source); }, [source.length]);
  const move = (from, to) => {
    if (to < 0 || to >= current.length || from === to) return;
    const next = [...current];
    const [item] = next.splice(from, 1);
    next.splice(to, 0, item);
    onChange(next);
  };
  const onDragStart = (i) => (e) => { setDragIdx(i); e.dataTransfer.effectAllowed = 'move'; };
  const onDragOver = (i) => (e) => { e.preventDefault(); setOverIdx(i); };
  const onDrop = (i) => (e) => { e.preventDefault(); if (dragIdx !== null) move(dragIdx, i); setDragIdx(null); setOverIdx(null); };
  const onDragEnd = () => { setDragIdx(null); setOverIdx(null); };
  if (!source.length) return <div className="summary-empty">Primero elige algunas tareas en la pregunta anterior.</div>;
  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 8, marginTop: 8, position: 'relative'}}>
      <div style={{fontSize: 12, color: 'var(--muted)', marginBottom: 4, display: 'flex', alignItems: 'center', gap: 6}}>
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M4 3h4M4 6h4M4 9h4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
        Arrastra las tarjetas para reordenar
      </div>
      {current.map((item, i) => (
        <div key={item} style={{position: 'relative'}}>
          <div
            draggable
            onDragStart={onDragStart(i)}
            onDragOver={onDragOver(i)}
            onDrop={onDrop(i)}
            onDragEnd={onDragEnd}
            className="card"
            style={{
              display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px',
              cursor: dragIdx === i ? 'grabbing' : 'grab',
              opacity: dragIdx === i ? 0.4 : 1,
              borderColor: overIdx === i && dragIdx !== null && dragIdx !== i ? 'var(--violet)' : undefined,
              boxShadow: overIdx === i && dragIdx !== null && dragIdx !== i ? '0 0 0 3px rgba(119, 47, 249, 0.15)' : undefined,
              transition: 'border-color 0.15s, box-shadow 0.15s, opacity 0.15s',
              userSelect: 'none',
            }}
          >
            <div style={{color: 'var(--muted)', cursor: 'grab', fontSize: 16, lineHeight: 1}} aria-label="arrastrar">⋮⋮</div>
            <div style={{width: 28, height: 28, borderRadius: 8, background: 'var(--violet)', color: 'white', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 13}}>{i + 1}</div>
            <div style={{flex: 1, fontWeight: 600, fontSize: 15}}>{item}</div>
            <div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700}}>
              {i === 0 ? 'primero' : i === current.length - 1 ? 'último' : 'luego'}
            </div>
            <button onClick={() => move(i, i - 1)} disabled={i === 0} style={{background: 'none', border: '1px solid var(--border)', borderRadius: 6, padding: '4px 8px', cursor: i === 0 ? 'default' : 'pointer', opacity: i === 0 ? 0.3 : 1}}>↑</button>
            <button onClick={() => move(i, i + 1)} disabled={i === current.length - 1} style={{background: 'none', border: '1px solid var(--border)', borderRadius: 6, padding: '4px 8px', cursor: i === current.length - 1 ? 'default' : 'pointer', opacity: i === current.length - 1 ? 0.3 : 1}}>↓</button>
          </div>
          {i < current.length - 1 && (
            <div style={{height: 14, width: 2, background: 'var(--border-strong)', marginLeft: 30}}></div>
          )}
        </div>
      ))}
    </div>
  );
}

// ---- AI CHIPS (dynamic options) ----
function AIChipsInput({ question, value, onChange, context }) {
  const [options, setOptions] = useExtraState(question.fallback || []);
  const [loading, setLoading] = useExtraState(false);
  const [seen, setSeen] = useExtraState([]);
  const selected = value || [];
  const [customChips, setCustomChips] = useExtraState([]);
  const [adding, setAdding] = useExtraState(false);
  const [addText, setAddText] = useExtraState('');

  useExtraEffect(() => {
    if (question.aiGeneratedChips) regenerate(true); // try cache first
  }, [question.id]);

  async function regenerate(useCache = false) {
    setLoading(true);
    try {
      // First pass: try cache
      if (useCache && window.aiCache) {
        const depsRaw = question.aiDeps || ['business_description'];
        const allDeps = depsRaw.map(d => d.startsWith('?') ? d.slice(1) : d);
        const contextHash = allDeps.map(d => {
          try { return JSON.stringify(context[d]); } catch { return ''; }
        }).join('|').slice(0, 500);
        const cached = window.aiCache.get(question.id, contextHash);
        if (cached) {
          const arr = cached.data;
          if (Array.isArray(arr) && arr.length) {
            setOptions(arr.filter(x => typeof x === 'string'));
            setLoading(false);
            return;
          }
        }
        // Not cached — trigger via generateForQuestion (respects inflight dedup)
        const data = await window.aiCache.generateForQuestion(question, context);
        if (Array.isArray(data) && data.length) {
          setOptions(data.filter(x => typeof x === 'string'));
        }
        setLoading(false);
        return;
      }

      // Fresh call with exclusion
      if (!window.aiComplete) {
        setLoading(false);
        return;
      }
      const contextSummary = window.aiCache?.buildContextSummary?.(context) || window.buildContextSummary(context);
      const prevAll = [...seen, ...options];
      const exclusion = prevAll.length ? `\n\nYA MOSTRADAS (NO REPITAS ni uses variaciones cercanas, genera nuevas y distintas):\n${prevAll.map(p => '- ' + p).join('\n')}` : '';
      const prompt = `Contexto del negocio:\n${contextSummary}\n\nTarea: ${question.aiPrompt}${exclusion}\n\nResponde SOLO con un JSON object con clave "items" que contenga un array de strings. Ejemplo: {"items": ["opción 1", "opción 2"]}.`;
      const res = await window.aiComplete(prompt, { jsonMode: true, temperature: 0.8 }, question.id);
      if (res.ok) {
        try {
          const parsed = JSON.parse(res.data);
          const arr = Array.isArray(parsed) ? parsed : (parsed.items || parsed.options || null);
          if (Array.isArray(arr) && arr.length) {
            setOptions(arr.filter(x => typeof x === 'string'));
            setSeen(prevAll);
          }
        } catch (e) {
          const arr = window.aiCache?.parseJsonArray?.(res.data);
          if (arr && arr.length) setOptions(arr.filter(x => typeof x === 'string'));
        }
      }
    } catch (e) { console.warn(e); }
    setLoading(false);
  }

  const all = [...options, ...customChips];
  const toggle = (opt) => {
    onChange(selected.includes(opt) ? selected.filter(x => x !== opt) : [...selected, opt]);
  };
  const addCustom = () => {
    if (!addText.trim()) { setAdding(false); return; }
    const c = addText.trim();
    setCustomChips([...customChips, c]);
    onChange([...selected, c]);
    setAddText(''); setAdding(false);
  };

  return (
    <>
      <div className="ai-badge">
        <span className="pulse"></span>
        {loading ? 'Generando sugerencias para tu negocio…' : 'Sugerencias para tu rubro'}
      </div>
      {loading ? (
        <div className="chips">{[1,2,3,4,5,6].map(i => <div key={i} className="skeleton" style={{height: 36, width: 100 + (i*20), borderRadius: 999}} />)}</div>
      ) : (
        <div className="chips">
          {all.map((opt) => (
            <button key={opt} className={`chip ${selected.includes(opt) ? 'selected' : ''}`} onClick={() => toggle(opt)}>
              {selected.includes(opt) && (
                <svg width="10" height="10" viewBox="0 0 10 10" fill="none"><path d="M1.5 5.5L4 8L8.5 2" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
              )}
              {opt}
            </button>
          ))}
          {adding ? (
            <input autoFocus className="chip" style={{border: '1.5px solid var(--violet)', outline: 'none', minWidth: 160}} value={addText} onChange={(e) => setAddText(e.target.value)} onBlur={addCustom} onKeyDown={(e) => { if (e.key === 'Enter') addCustom(); }} placeholder="Agregar propio…" />
          ) : (
            <button className="chip chip-add" onClick={() => setAdding(true)}>+ agregar</button>
          )}
        </div>
      )}
      <button className={`ai-refresh ${loading ? 'loading' : ''}`} onClick={regenerate}>
        <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>
        {loading ? 'Generando…' : 'Regenerar sugerencias'}
      </button>
    </>
  );
}

// ---- EMOJI PICKER (suggests 5 emojis based on business rubro) ----
function EmojiSuggestions({ context, value, onChange }) {
  const [emojis, setEmojis] = useExtraState(value || []);
  const [loading, setLoading] = useExtraState(false);
  const [editingIdx, setEditingIdx] = useExtraState(null);
  const [editText, setEditText] = useExtraState('');

  useExtraEffect(() => {
    if (!value || value.length === 0) regenerate();
    else setEmojis(value);
  }, []);

  async function regenerate() {
    setLoading(true);
    try {
      if (!window.aiComplete) { setLoading(false); return; }
      const ctx = window.aiCache?.buildContextSummary?.(context) || window.buildContextSummary(context);
      const prompt = `Contexto del negocio:\n${ctx}\n\nTarea: Sugiere exactamente 5 emojis relacionados al rubro del negocio, que un agente de atención al cliente de este negocio podría usar naturalmente. IMPORTANTE: al menos 1 (idealmente 2) debe ser una CARA/emoticon (ej: 😊 🙌 🙂 👋 😄 🤝) porque son los más usados en conversaciones. Ej: para clínica dental 🦷 😁 ✨ 🪥 🙌. Para bienes raíces 🏡 🔑 📍 😊 💼.\n\nResponde SOLO con un JSON object con clave "items" que contenga un array de 5 strings de emoji. Ejemplo: {"items": ["😊", "🙌", "✨", "👋", "🤝"]}.`;
      const res = await window.aiComplete(prompt, { jsonMode: true, temperature: 0.7 }, 'emoji_suggestions');
      if (res.ok) {
        try {
          const parsed = JSON.parse(res.data);
          const arr = Array.isArray(parsed) ? parsed : (parsed.items || parsed.emojis || null);
          if (Array.isArray(arr) && arr.length) {
            const items = arr.slice(0, 5).map(x => String(x));
            setEmojis(items);
            onChange(items);
          }
        } catch (e) {
          const arr = window.aiCache?.parseJsonArray?.(res.data);
          if (arr && arr.length) {
            const items = arr.slice(0, 5).map(x => String(x));
            setEmojis(items);
            onChange(items);
          }
        }
      }
    } catch (e) { console.warn(e); }
    setLoading(false);
  }

  const commitEdit = (i) => {
    const next = [...emojis];
    next[i] = editText || emojis[i];
    setEmojis(next); onChange(next);
    setEditingIdx(null); setEditText('');
  };

  return (
    <div style={{marginTop: 12, padding: '14px 16px', background: '#FAF7FF', border: '1.5px dashed var(--violet)', borderRadius: 12}}>
      <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10}}>
        <div style={{fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 13, color: 'var(--violet)', textTransform: 'uppercase', letterSpacing: '0.06em'}}>
          Emojis sugeridos para tu rubro
        </div>
        <button className={`ai-refresh ${loading ? 'loading' : ''}`} onClick={regenerate} style={{margin: 0}}>
          <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>
          {loading ? 'Generando…' : 'Regenerar'}
        </button>
      </div>
      <div style={{fontSize: 12.5, color: 'var(--muted-2)', marginBottom: 10}}>Click en cualquiera para reemplazarlo manualmente.</div>
      <div style={{display: 'flex', gap: 10, flexWrap: 'wrap'}}>
        {loading && emojis.length === 0 ? (
          [1,2,3,4,5].map(i => <div key={i} className="skeleton" style={{width: 52, height: 52, borderRadius: 12}} />)
        ) : emojis.map((em, i) => (
          editingIdx === i ? (
            <input
              key={i}
              autoFocus
              value={editText}
              onChange={(e) => setEditText(e.target.value)}
              onBlur={() => commitEdit(i)}
              onKeyDown={(e) => { if (e.key === 'Enter') commitEdit(i); if (e.key === 'Escape') { setEditingIdx(null); setEditText(''); } }}
              maxLength={4}
              style={{width: 52, height: 52, border: '2px solid var(--violet)', borderRadius: 12, background: 'white', textAlign: 'center', fontSize: 26, outline: 'none'}}
            />
          ) : (
            <button
              key={i}
              onClick={() => { setEditingIdx(i); setEditText(em); }}
              style={{width: 52, height: 52, border: '1.5px solid var(--border)', borderRadius: 12, background: 'white', fontSize: 28, cursor: 'pointer', lineHeight: 1, transition: 'transform 0.1s'}}
              onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.06)'}
              onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
              title="Click para reemplazar"
            >{em}</button>
          )
        ))}
      </div>
    </div>
  );
}

// ---- THRESHOLDS (per-criterion textfields) ----
function ThresholdsInput({ question, value, onChange, context }) {
  const criteria = context[question.dependsOn] || [];
  const v = value || {};
  const update = (k, val) => onChange({ ...v, [k]: val });
  if (!criteria.length) {
    return <div className="summary-empty">Primero selecciona algunos criterios en la pregunta anterior.</div>;
  }
  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 10, marginTop: 8}}>
      {criteria.map((c) => (
        <div key={c} style={{background: 'white', border: '1.5px solid var(--border)', borderRadius: 12, padding: '12px 14px', display: 'grid', gridTemplateColumns: '180px 1fr', gap: 14, alignItems: 'center'}}>
          <div style={{fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 14}}>{c}</div>
          <input
            className="textfield"
            style={{fontSize: 15, padding: '6px 0'}}
            placeholder={`Ej: por lo menos $100.000 USD · más de 2 años · etc.`}
            value={v[c] || ''}
            onChange={(e) => update(c, e.target.value)}
          />
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { TogglesInput, LinkListInput, FlowTreeInput, AIChipsInput, EmojiSuggestions, ThresholdsInput });
