// wh-envios-section.jsx - extracted EnviosSection

(() => {

const { useState, useEffect, useRef } = React;
const {
  Icon,
  Badge,
  SecHead,
  FormField,
  apiFetch,
  DisconnectedBanner,
} = window;

const toast = (msg, type, dur) => window.showToast?.(msg, type, dur);

const EMOJIS = ['✅', '⚠️', '📌', '📣', '🙏', '👍', '🚀', '😊', '⛽', '🚨', '👋', '🚗', '💳'];

const MAX_FILE_BYTES = 16 * 1024 * 1024;

function humanSize(bytes) {
  if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  return `${(bytes / 1024).toFixed(1)} KB`;
}

function EnviosSection({ groupLists = [], onJobCreated, whStatus }) {
  const isReady = whStatus?.status === 'ready';
  const [selList, setSelList] = useState('');
  const [msg, setMsg] = useState('');
  const [busy, setBusy] = useState(false);
  const [attachment, setAttachment] = useState(null); // { file: File, previewUrl: string|null }
  const txRef = useRef();
  const fileInputRef = useRef();

  useEffect(() => {
    if (groupLists.length && !selList) {
      setSelList(groupLists[0].id);
    }
  }, [groupLists, selList]);

  // Limpiar previewUrl al cambiar adjunto o desmontar
  useEffect(() => {
    return () => {
      if (attachment?.previewUrl) {
        URL.revokeObjectURL(attachment.previewUrl);
      }
    };
  }, [attachment]);

  const insertEmoji = (emoji) => {
    const el = txRef.current;
    if (!el) {
      setMsg((current) => current + emoji);
      return;
    }

    const start = el.selectionStart;
    const end = el.selectionEnd;
    const next = msg.slice(0, start) + emoji + msg.slice(end);
    setMsg(next);

    setTimeout(() => {
      el.selectionStart = start + emoji.length;
      el.selectionEnd = start + emoji.length;
      el.focus();
    }, 0);
  };

  const handleFileChange = (e) => {
    const file = e.target.files?.[0];
    if (!file) {
      setAttachment(null);
      return;
    }

    if (file.size > MAX_FILE_BYTES) {
      toast('El archivo supera el limite de 16 MB.', 'error');
      if (fileInputRef.current) fileInputRef.current.value = '';
      return;
    }

    const isImage = file.type.startsWith('image/');
    const previewUrl = isImage ? URL.createObjectURL(file) : null;
    setAttachment({ file, previewUrl });
  };

  const clearAttachment = () => {
    if (attachment?.previewUrl) {
      URL.revokeObjectURL(attachment.previewUrl);
    }
    setAttachment(null);
    if (fileInputRef.current) fileInputRef.current.value = '';
  };

  const send = async () => {
    if (!msg.trim() || !selList) return;
    if (!isReady) {
      toast('WhatsApp no esta conectado. Conectalo desde la seccion Conexion.', 'warning');
      return;
    }

    setBusy(true);
    try {
      let res;
      if (attachment) {
        const formData = new FormData();
        formData.append('groupListId', selList);
        formData.append('message', msg.trim());
        formData.append('file', attachment.file);
        res = await apiFetch('/api/send', {
          method: 'POST',
          body: formData,
        });
      } else {
        res = await apiFetch('/api/send', {
          method: 'POST',
          body: JSON.stringify({ groupListId: selList, message: msg.trim() }),
        });
      }

      if (!res.ok) {
        const err = await res.json();
        toast(err.error, 'error');
        setBusy(false);
        return;
      }

      const job = await res.json();
      onJobCreated?.(job);
      setMsg('');
      clearAttachment();
      toast('Envio iniciado. Segui el progreso en la seccion Actividad.', 'success', 6000);
    } catch (error) {
      toast(`Error al enviar mensaje: ${error.message}`, 'error');
    } finally {
      setBusy(false);
    }
  };

  const now = new Date();
  const previewTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
  const destination = groupLists.find((list) => list.id === selList);

  return (
    <div>
      <SecHead eyebrow="Campanas" title="Enviar Mensaje" />

      <div className="split-2">
        <div className="card card-pad">
          <div className="stack">
            <FormField label="Lista de grupos destino">
              {groupLists.length === 0
                ? <div className="t-muted t-sm">No hay listas. Crea una en la seccion Grupos.</div>
                : (
                  <select className="sel" value={selList} onChange={(e) => setSelList(e.target.value)}>
                    {groupLists.map((list) => (
                      <option key={list.id} value={list.id}>
                        {list.name} ({list.groupIds.length} grupos)
                      </option>
                    ))}
                  </select>
                )}
            </FormField>

            <FormField label="Emojis rapidos">
              <div className="emoji-bar">
                {EMOJIS.map((emoji) => (
                  <button key={emoji} className="emj" onClick={() => insertEmoji(emoji)} type="button">
                    {emoji}
                  </button>
                ))}
              </div>
            </FormField>

            <FormField label="Mensaje">
              <textarea
                className="txta"
                ref={txRef}
                rows={6}
                style={{ minHeight: 150 }}
                placeholder="Escribe el mensaje para los grupos seleccionados..."
                value={msg}
                onChange={(e) => setMsg(e.target.value)}
              />
              <div style={{ textAlign: 'right', fontSize: 11.5, color: 'var(--muted)', marginTop: 3 }}>
                {msg.length} caracteres
              </div>
            </FormField>

            <FormField label="Adjunto (opcional)">
              <div className="flex-r" style={{ gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/jpeg,image/png,image/gif,image/webp,application/pdf,.docx,.xlsx"
                  onChange={handleFileChange}
                  style={{ flex: 1, minWidth: 0 }}
                />
                {attachment && (
                  <button
                    type="button"
                    className="btn btn-sm"
                    onClick={clearAttachment}
                    title="Quitar adjunto"
                  >
                    <Icon name="x" size={14} /> Quitar adjunto
                  </button>
                )}
              </div>
            </FormField>

            {!isReady && <DisconnectedBanner />}
            <button
              className="btn btn-primary btn-lg"
              onClick={send}
              disabled={!msg.trim() || !selList || busy || !isReady}
            >
              {busy
                ? <><Icon name="clock" size={15} />Iniciando envio...</>
                : <><Icon name="send" size={15} />Enviar mensaje</>}
            </button>
          </div>
        </div>

        <div className="flex-c" style={{ gap: 14 }}>
          <div className="card card-pad">
            <div className="flex-r" style={{ marginBottom: 12 }}>
              <div className="card-title">Vista previa</div>
              <div className="mla t-sm t-muted">{msg.length} car.</div>
            </div>
            {msg.trim()
              ? (
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <div className="bubble" style={{ maxWidth: '90%' }}>
                    {attachment && (
                      <div style={{ marginBottom: 6 }}>
                        {attachment.previewUrl
                          ? <img src={attachment.previewUrl} style={{ maxWidth: '100%', borderRadius: 8 }} alt={attachment.file.name} />
                          : (
                            <div className="flex-r" style={{ gap: 6, alignItems: 'center', padding: '6px 8px', background: 'var(--surface-2, rgba(0,0,0,0.06))', borderRadius: 6 }}>
                              <Icon name="layers" size={16} />
                              <span className="t-sm">{attachment.file.name}</span>
                              <span className="t-sm t-muted">({humanSize(attachment.file.size)})</span>
                            </div>
                          )}
                      </div>
                    )}
                    {msg}
                    <span className="bubble-time">{previewTime} ✓✓</span>
                  </div>
                </div>
              )
              : <div className="bubble empty">El mensaje se previsualizara aqui...</div>}
          </div>

          <div className="card card-pad">
            <div className="card-title" style={{ marginBottom: 10 }}>Destino</div>
            {destination
              ? (
                <div className="stack" style={{ gap: 8 }}>
                  <div className="flex-r">
                    <Badge color="teal">{destination.name}</Badge>
                    <span className="t-muted t-sm">{destination.groupIds.length} grupos</span>
                  </div>
                  {attachment && (
                    <div className="flex-r" style={{ gap: 6, alignItems: 'center' }}>
                      <Icon name="layers" size={14} />
                      <span className="t-sm">{attachment.file.name}</span>
                      <span className="t-sm t-muted">({humanSize(attachment.file.size)})</span>
                    </div>
                  )}
                  <p className="t-sm t-muted">Se enviara con delay aleatorio entre cada grupo para evitar bloqueos.</p>
                </div>
              )
              : <div className="t-muted t-sm">Selecciona una lista</div>}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { EnviosSection });

})();
