{% extends 'base.html' %}
{% block content %}
<div class="page-toolbar">
  <div>
    <h1 class="h3 mb-1">WhatsApp Bot</h1>
    <p class="text-muted mb-0">Menú, autorespondedor y base de conocimiento leída desde tu web.</p>
  </div>
  <a class="btn btn-outline-secondary" href="{{ url_for('admin_site_settings', tab='general') }}"><i class="bi bi-globe2"></i> Sitio Web</a>
</div>

<ul class="nav nav-tabs mb-4" role="tablist">
  <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#wa-config" type="button">Configuración API</button></li>
  <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#wa-menu" type="button">Menú / Autorespondedor</button></li>
  <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#wa-knowledge" type="button">Estudiar web</button></li>
  <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#wa-logs" type="button">Mensajes</button></li>
</ul>

<div class="tab-content">
  <div class="tab-pane fade show active" id="wa-config">
    <div class="card table-panel"><div class="card-body">
      <form method="post" class="row g-3">
        <input type="hidden" name="csrf_token" value="{{ csrf_token }}"><input type="hidden" name="action" value="settings">
        <div class="col-12"><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="wa_bot_enabled" id="wa_bot_enabled" {% if cfg.enabled %}checked{% endif %}><label class="form-check-label" for="wa_bot_enabled">Activar bot de WhatsApp</label></div></div>
        <div class="col-md-6"><label class="form-label">Phone Number ID</label><input class="form-control" name="wa_phone_number_id" value="{{ cfg.phone_number_id }}" placeholder="ID del número en Meta"></div>
        <div class="col-md-6"><label class="form-label">API version</label><input class="form-control" name="wa_api_version" value="{{ cfg.api_version or 'v23.0' }}"></div>
        <div class="col-md-6"><label class="form-label">Verify token webhook</label><input class="form-control" name="wa_verify_token" value="{{ cfg.verify_token }}"></div>
        <div class="col-md-6"><label class="form-label">Webhook público</label><input class="form-control" readonly value="{{ request.url_root.rstrip('/') }}/webhooks/whatsapp"></div>
        <div class="col-12"><label class="form-label">Access token permanente / temporal</label><textarea class="form-control" name="wa_access_token" rows="2" placeholder="Token de Meta Cloud API">{{ cfg.access_token }}</textarea></div>
        <div class="col-md-6"><label class="form-label">Título del menú</label><input class="form-control" name="wa_menu_title" value="{{ cfg.menu_title }}"></div>
        <div class="col-md-6"><label class="form-label">Respuesta por defecto</label><input class="form-control" name="wa_default_reply" value="{{ cfg.default_reply }}"></div>
        <div class="col-12"><hr class="my-2"><h3 class="h6 mb-0">Botón flotante del frontend</h3><p class="text-muted small mb-0">Este botón aparece en la web pública junto al botón de subir y abre WhatsApp con un mensaje inicial.</p></div>
        <div class="col-12"><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="wa_floating_button_enabled" id="wa_floating_button_enabled" {% if cfg.floating_enabled %}checked{% endif %}><label class="form-check-label" for="wa_floating_button_enabled">Mostrar botón flotante de WhatsApp en el frontend</label></div></div>
        <div class="col-md-6"><label class="form-label">Número público WhatsApp</label><input class="form-control" name="wa_public_number" value="{{ cfg.public_number }}" placeholder="Ej.: 5491123456789, sin + ni espacios"><div class="form-text">Usar código de país + característica + número. Ejemplo Argentina: 54911...</div></div>
        <div class="col-md-6"><label class="form-label">Etiqueta accesible</label><input class="form-control" name="wa_public_label" value="{{ cfg.public_label }}" placeholder="Escribinos por WhatsApp"></div>
        <div class="col-12"><label class="form-label">Mensaje inicial</label><input class="form-control" name="wa_public_message" value="{{ cfg.public_message }}" placeholder="Hola, quiero solicitar información."></div>
        <div class="col-12 d-grid"><button class="btn btn-primary btn-lg">Guardar configuración</button></div>
      </form>
    </div></div>
  </div>

  <div class="tab-pane fade" id="wa-menu">
    <div class="row g-4">
      <div class="col-lg-5"><div class="card table-panel h-100"><div class="card-header"><strong>Nueva respuesta</strong></div><div class="card-body">
        <form method="post" class="row g-3">
          <input type="hidden" name="csrf_token" value="{{ csrf_token }}"><input type="hidden" name="action" value="save_rule">
          <div class="col-md-7"><label class="form-label">Disparador</label><input class="form-control" name="trigger" placeholder="turnos, horarios, obrasocial"></div>
          <div class="col-md-5"><label class="form-label">Coincidencia</label><select class="form-select" name="match_mode"><option value="contains">Contiene</option><option value="exact">Exacta</option><option value="startswith">Comienza con</option></select></div>
          <div class="col-md-8"><label class="form-label">Título en menú</label><input class="form-control" name="title" placeholder="Solicitar turno"></div>
          <div class="col-md-4"><label class="form-label">Orden</label><input class="form-control" name="sort_order" value="0"></div>
          <div class="col-12"><label class="form-label">Respuesta enriquecida</label><textarea class="form-control html-editor" name="response_html" rows="8" placeholder="Podés escribir HTML simple; para WhatsApp se enviará como texto limpio."></textarea></div>
          <div class="col-12"><div class="form-check"><input class="form-check-input" type="checkbox" name="is_active" checked><label class="form-check-label">Activo</label></div></div>
          <div class="col-12 d-grid"><button class="btn btn-primary">Guardar autorespuesta</button></div>
        </form>
      </div></div></div>
      <div class="col-lg-7"><div class="card table-panel"><div class="card-header"><strong>Respuestas configuradas</strong></div><div class="table-responsive"><table class="table align-middle mb-0"><thead><tr><th>Orden</th><th>Disparador</th><th>Título</th><th>Modo</th><th>Estado</th><th></th></tr></thead><tbody>
        {% for rule in rules %}<tr><td>{{ rule.sort_order }}</td><td><code>{{ rule.trigger }}</code></td><td>{{ rule.title or '—' }}</td><td>{{ rule.match_mode }}</td><td>{% if rule.is_active %}<span class="badge text-bg-success">Activo</span>{% else %}<span class="badge text-bg-secondary">Inactivo</span>{% endif %}</td><td class="text-end"><form method="post" onsubmit="return confirm('¿Eliminar respuesta?')"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><input type="hidden" name="action" value="delete_rule"><input type="hidden" name="rule_id" value="{{ rule.id }}"><button class="btn btn-sm btn-outline-danger">Eliminar</button></form></td></tr>{% else %}<tr><td colspan="6" class="text-center text-muted py-4">Todavía no hay respuestas.</td></tr>{% endfor %}
      </tbody></table></div></div></div>
    </div>
  </div>

  <div class="tab-pane fade" id="wa-knowledge">
    <div class="row g-4">
      <div class="col-lg-5"><div class="card table-panel"><div class="card-header"><strong>Leer página web</strong></div><div class="card-body">
        <form method="post" class="row g-3">
          <input type="hidden" name="csrf_token" value="{{ csrf_token }}"><input type="hidden" name="action" value="train_url">
          <div class="col-12"><label class="form-label">URL</label><input class="form-control" name="source_url" placeholder="https://tuclinica.com/servicios" required></div>
          <div class="col-12"><label class="form-label">Palabras clave opcionales</label><input class="form-control" name="keywords" placeholder="turnos, cardiología, horarios"></div>
          <div class="col-12"><div class="alert alert-info mb-0">El sistema extrae texto útil de la página y lo usa para responder cuando no encuentra una regla exacta.</div></div>
          <div class="col-12 d-grid"><button class="btn btn-primary">Estudiar esta página</button></div>
        </form>
      </div></div></div>
      <div class="col-lg-7"><div class="card table-panel"><div class="card-header"><strong>Fuentes aprendidas</strong></div><div class="table-responsive"><table class="table align-middle mb-0"><thead><tr><th>Fuente</th><th>Texto</th><th></th></tr></thead><tbody>
        {% for item in knowledge %}<tr><td><div class="fw-semibold">{{ item.title }}</div><small class="text-muted">{{ item.source_url }}</small></td><td>{{ item.content[:180] }}...</td><td class="text-end"><form method="post" onsubmit="return confirm('¿Eliminar fuente?')"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><input type="hidden" name="action" value="delete_knowledge"><input type="hidden" name="knowledge_id" value="{{ item.id }}"><button class="btn btn-sm btn-outline-danger">Eliminar</button></form></td></tr>{% else %}<tr><td colspan="3" class="text-center text-muted py-4">Sin fuentes cargadas.</td></tr>{% endfor %}
      </tbody></table></div></div></div>
    </div>
  </div>

  <div class="tab-pane fade" id="wa-logs">
    <div class="card table-panel"><div class="card-header"><strong>Últimos mensajes</strong></div><div class="table-responsive"><table class="table align-middle mb-0"><thead><tr><th>Fecha</th><th>Cliente</th><th>Entrada</th><th>Respuesta</th><th>Estado</th></tr></thead><tbody>
      {% for log in logs %}<tr><td>{{ log.created_at.strftime('%d/%m/%Y %H:%M') if log.created_at else '' }}</td><td>{{ log.customer_name or log.wa_id }}</td><td>{{ log.incoming_text }}</td><td>{{ log.outgoing_text }}</td><td><span class="badge text-bg-light">{{ log.status }}</span>{% if log.error %}<div class="small text-danger">{{ log.error[:120] }}</div>{% endif %}</td></tr>{% else %}<tr><td colspan="5" class="text-center text-muted py-4">Aún no hay mensajes.</td></tr>{% endfor %}
    </tbody></table></div></div>
  </div>
</div>
{% endblock %}
