/* ============================================================
   CHAT LEGAL — main section
   ============================================================ */

const CHAT_SUGGESTIONS = [
  { t: '¿Cómo doy de alta una factura como autónomo?', ic: 'euro' },
  { t: 'Un cliente no me paga, ¿qué puedo hacer?', ic: 'shield' },
  { t: '¿Qué debe incluir mi política de privacidad (RGPD)?', ic: 'file' },
  { t: '¿Cuándo tengo que presentar el modelo 303?', ic: 'calendar' },
];

const WELCOME = 'Hola, soy Lexly. Tu asesor legal inteligente. ¿En qué puedo ayudarte hoy?';

function ChatLegal({ isGuest, guestQueries = 0, guestLimit = 3, onGuestQuery, onRegister, initialConversation, initialInput }) {
  const [messages, setMessages] = useState(() =>
    initialConversation && Array.isArray(initialConversation.messages) && initialConversation.messages.length
      ? initialConversation.messages
      : [{ role: 'assistant', content: WELCOME, welcome: true }]
  );
  const convId = useRef(initialConversation?.id || lxId());
  const createdAt = useRef(initialConversation?.createdAt || Date.now());
  const [input, setInput] = useState(initialInput || '');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const scrollRef = useRef(null);
  const taRef = useRef(null);

  const hasConversation = messages.some(m => m.role === 'user');
  const guestBlocked = isGuest && guestQueries >= guestLimit;
  const remaining = Math.max(0, guestLimit - guestQueries);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, loading]);

  const autoGrow = () => {
    const ta = taRef.current;
    if (!ta) return;
    ta.style.height = 'auto';
    ta.style.height = Math.min(ta.scrollHeight, 180) + 'px';
  };

  // Persist conversation to history (additive — does not alter chat behavior)
  const saveConversation = (msgs) => {
    const real = msgs.filter(m => !m.welcome);
    const firstUser = real.find(m => m.role === 'user');
    if (!firstUser) return;
    const last = real[real.length - 1];
    lxUpsertChat({
      id: convId.current,
      title: firstUser.content.slice(0, 70),
      preview: (last ? last.content : '').replace(/\s+/g, ' ').slice(0, 96),
      messages: real,
      createdAt: createdAt.current,
      updatedAt: Date.now(),
    });
  };

  const send = async (text) => {
    const content = (text != null ? text : input).trim();
    if (!content || loading) return;
    if (guestBlocked) return;
    setError(null);
    setInput('');
    if (taRef.current) taRef.current.style.height = 'auto';

    const history = messages
      .filter(m => !m.welcome)
      .map(m => ({ role: m.role, content: m.content }));
    const next = [...messages, { role: 'user', content }];
    setMessages(next);
    setLoading(true);
    if (isGuest && onGuestQuery) onGuestQuery();
    // Registrar el uso del chat en el contador mensual central (todos los usuarios).
    try { if (typeof lxRegisterUse === 'function') lxRegisterUse('chat'); } catch (e) {}

    try {
      const reply = await callLexly([...history, { role: 'user', content }], undefined, 2000);
      const updated = [...next, { role: 'assistant', content: reply }];
      setMessages(updated);
      saveConversation(updated);
    } catch (e) {
      setError(e.message === 'NO_API'
        ? 'No se ha podido conectar con el servicio. Revisa tu conexión e inténtalo de nuevo.'
        : 'Lexly no ha respondido. Comprueba tu conexión e inténtalo de nuevo.');
      setMessages(m => m.filter(x => x !== next[next.length - 1]));
      setInput(content);
    } finally {
      setLoading(false);
    }
  };

  const onKey = (e) => {
    if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); send(); }
  };

  const clearChat = () => {
    convId.current = lxId();
    createdAt.current = Date.now();
    setMessages([{ role: 'assistant', content: WELCOME, welcome: true }]);
    setError(null);
  };

  return (
    <div className="chat-wrap">
      <div className="chat-scroll" ref={scrollRef}>
        <div className="chat-inner">
          {!hasConversation && (
            <div className="chat-hero fade-up">
              <LexAvatar size={56} />
              <h2>{WELCOME}</h2>
              <p>Pregúntame sobre contratos, fiscalidad de autónomos, RGPD, reclamación de deudas o derechos del consumidor.</p>
              <div className="suggest-grid">
                {CHAT_SUGGESTIONS.map((s, i) => (
                  <button key={i} className="suggest" onClick={() => send(s.t)}>
                    <Icon name={s.ic} size={16} />
                    <span>{s.t}</span>
                    <Icon name="arrowRight" size={14} className="arr" />
                  </button>
                ))}
              </div>
            </div>
          )}

          {hasConversation && messages.map((m, i) => (
            <Message key={i} role={m.role} content={m.content} />
          ))}

          {loading && (
            <div className="msg-row assistant">
              <LexAvatar size={34} />
              <div className="bubble assistant"><Typing /></div>
            </div>
          )}

          {error && <ErrorNote onRetry={() => send(input)}>{error}</ErrorNote>}

          {guestBlocked && <GuestLimitBanner onRegister={onRegister} />}
        </div>
      </div>

      <div className="composer-zone">
        <div className={'composer' + (guestBlocked ? ' disabled' : '')}>
          <textarea
            ref={taRef}
            className="composer-input"
            placeholder={guestBlocked ? 'Regístrate para seguir consultando…' : 'Escribe tu consulta legal…'}
            value={input}
            rows={1}
            disabled={guestBlocked}
            onChange={(e) => { setInput(e.target.value); autoGrow(); }}
            onKeyDown={onKey}
          />
          <div className="composer-foot">
            <div className="composer-hint">
              {isGuest && !guestBlocked && (
                <span className="guest-count"><Icon name="bolt" size={12} /> {remaining} de {guestLimit} consultas gratuitas</span>
              )}
              {!isGuest && hasConversation && (
                <button className="clear-btn" onClick={clearChat}>
                  <Icon name="trash" size={13} /> Nueva conversación
                </button>
              )}
            </div>
            <div className="composer-actions">
              <span className="kbd-hint"><kbd>Ctrl</kbd>+<kbd>Enter</kbd></span>
              <button
                className="send-btn"
                disabled={!input.trim() || loading || guestBlocked}
                onClick={() => send()}
                aria-label="Enviar"
              >
                {loading ? <Spinner /> : <Icon name="send" size={16} />}
              </button>
            </div>
          </div>
        </div>
        <p className="composer-disclaimer">Lexly ofrece información legal, no asesoramiento jurídico profesional.</p>
        <div className="composer-terr"><TerritoryBadge /></div>
      </div>

      <style>{`
        .chat-wrap { display: flex; flex-direction: column; height: 100%; }
        .chat-scroll { flex: 1; min-height: 0; overflow-y: auto; }
        .chat-inner { max-width: 760px; margin: 0 auto; padding: 30px 24px 16px; }

        .chat-hero { text-align: center; padding: clamp(24px, 7vh, 64px) 8px 20px; display: flex; flex-direction: column; align-items: center; }
        .chat-hero h2 { font-size: 23px; font-weight: 600; letter-spacing: -0.02em; color: var(--white); margin: 18px 0 8px; line-height: 1.3; max-width: 460px; }
        .chat-hero p { font-size: 14px; color: var(--text-2); max-width: 440px; line-height: 1.55; }
        .suggest-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 28px; width: 100%; max-width: 560px; }
        .suggest {
          display: flex; align-items: center; gap: 11px;
          text-align: left; padding: 13px 14px;
          background: var(--surface); border: 1px solid var(--line);
          border-radius: 12px; font-size: 13px; color: var(--text-2);
          transition: border-color .15s, background .15s, transform .12s;
        }
        .suggest:hover { border-color: var(--violet-line); background: var(--surface-2); color: var(--text); transform: translateY(-1px); }
        .suggest .ic:first-child { color: var(--violet-soft); flex-shrink: 0; }
        .suggest span { flex: 1; line-height: 1.35; }
        .suggest .arr { color: var(--text-4); opacity: 0; transition: opacity .15s, transform .15s; }
        .suggest:hover .arr { opacity: 1; transform: translateX(2px); }

        .msg-row { display: flex; gap: 13px; margin: 22px 0; animation: fadeUp .3s ease; }
        .msg-row.user { flex-direction: row-reverse; }
        .bubble { max-width: 82%; border-radius: 16px; padding: 13px 16px; }
        .bubble.assistant {
          background: var(--surface); border: 1px solid var(--line);
          border-top-left-radius: 5px;
        }
        .bubble.user {
          background: linear-gradient(180deg, var(--violet-bright), var(--violet));
          color: white; border-top-right-radius: 5px;
          font-size: 14px; line-height: 1.55; box-shadow: 0 6px 20px -8px rgba(124,58,237,0.6);
        }
        .bubble.user .md, .bubble.user p { color: white; }
        .user-avatar {
          width: 34px; height: 34px; border-radius: 10px; flex-shrink: 0;
          background: linear-gradient(150deg, #3a3a4a, #23232e);
          border: 1px solid var(--line-2);
          display: grid; place-items: center; color: var(--text-2);
        }

        .composer-zone { flex-shrink: 0; padding: 6px 24px 14px; }
        .composer {
          max-width: 760px; margin: 0 auto;
          background: var(--surface); border: 1px solid var(--line-2);
          border-radius: 16px; padding: 6px 6px 6px;
          box-shadow: var(--shadow-md);
          transition: border-color .15s, box-shadow .15s;
        }
        .composer:focus-within { border-color: var(--violet-line); box-shadow: 0 0 0 3px var(--violet-dim), var(--shadow-md); }
        .composer-input {
          width: 100%; background: transparent; border: none; outline: none; resize: none;
          color: var(--text); font-size: 14.5px; line-height: 1.55;
          padding: 11px 12px 4px; max-height: 180px;
        }
        .composer-input::placeholder { color: var(--text-4); }
        .composer-foot { display: flex; align-items: center; padding: 4px 6px 4px 10px; gap: 10px; }
        .composer-hint { flex: 1; min-width: 0; }
        .clear-btn {
          display: inline-flex; align-items: center; gap: 6px;
          font-size: 12px; color: var(--text-3); font-weight: 500;
          padding: 5px 8px; border-radius: 7px; transition: color .15s, background .15s;
        }
        .clear-btn:hover { color: var(--text); background: rgba(255,255,255,0.04); }
        .composer-actions { display: flex; align-items: center; gap: 12px; }
        .kbd-hint { font-size: 11px; color: var(--text-4); }
        .kbd-hint kbd {
          font-family: inherit; font-size: 10px; background: var(--surface-3);
          border: 1px solid var(--line-2); border-radius: 4px; padding: 1px 5px; color: var(--text-3);
        }
        .send-btn {
          width: 36px; height: 36px; border-radius: 10px; display: grid; place-items: center;
          background: linear-gradient(180deg, var(--violet-bright), var(--violet)); color: white;
          box-shadow: 0 4px 14px -4px rgba(124,58,237,0.7), inset 0 1px 0 rgba(255,255,255,0.2);
          transition: transform .12s, opacity .15s;
        }
        .send-btn:hover:not(:disabled) { transform: translateY(-1px); }
        .send-btn:disabled { opacity: 0.4; cursor: not-allowed; background: var(--surface-3); box-shadow: none; }
        .composer-disclaimer { text-align: center; font-size: 11px; color: var(--text-4); margin-top: 10px; }
        .composer-terr { display: flex; justify-content: center; margin-top: 9px; }
        .composer.disabled { opacity: 0.6; }
        .composer.disabled:focus-within { border-color: var(--line-2); box-shadow: none; }
        .guest-count { display: inline-flex; align-items: center; gap: 6px; font-size: 11.5px; color: var(--violet-soft); font-weight: 500; padding: 5px 8px; }
        .guest-count .ic { color: var(--violet-soft); }

        @media (max-width: 860px) {
          .suggest-grid { grid-template-columns: 1fr; }
          .chat-inner { padding: 20px 16px 10px; }
          .composer-zone { padding: 6px 12px 12px; }
          .bubble { max-width: 88%; }
        }
      `}</style>
    </div>
  );
}

function Message({ role, content }) {
  return (
    <div className={'msg-row ' + role}>
      {role === 'assistant'
        ? <LexAvatar size={34} />
        : <div className="user-avatar"><Icon name="user" size={17} /></div>}
      <div className={'bubble ' + role}>
        {role === 'assistant'
          ? <Markdown text={content} />
          : <span style={{ whiteSpace: 'pre-wrap' }}>{content}</span>}
      </div>
    </div>
  );
}

Object.assign(window, { ChatLegal });
