unit frm_ChatInterno;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Types,
  System.Generics.Collections, System.UITypes, System.DateUtils, System.Math,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
  Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Param;

type
  TChatContacto = record
    UsuarioId: Integer; // 0 = Canal General
    Nombre: string;
    Username: string;
    NoLeidos: Integer;
    UltimoMensaje: string;
    UltimaFecha: TDateTime;
  end;

  TChatMensajeItem = record
    Id: Int64;
    EsSeparadorFecha: Boolean;
    RemitenteId: Integer;
    RemitenteNombre: string;
    Texto: string;
    FechaEnvio: TDateTime;
    Leido: Boolean;
    EsPropio: Boolean;
  end;

  TfrmChatInterno = class(TForm)
  private
    FPnlLeft: TPanel;
    FPnlLeftHeader: TPanel;
    FEdtBuscarContacto: TEdit;
    FLbContactos: TListBox;
    FSplitter: TSplitter;

    FPnlRight: TPanel;
    FPnlChatHeader: TPanel;
    FLblChatTitulo: TLabel;
    FLblChatSubtitulo: TLabel;
    FBtnCargarMas: TButton;
    FBtnRefrescar: TButton;

    FLbMensajes: TListBox;

    FPnlInput: TPanel;
    FMemMensaje: TMemo;
    FBtnEnviar: TButton;

    FTmrPoll: TTimer;

    FCurrentUserId: Integer;
    FSelectedContactId: Integer; // 0 = Canal General, >0 = Usuario
    FSelectedContactName: string;
    FLastMaxMsgId: Int64;
    FLimitMensajes: Integer;

    FContactosAll: TList<TChatContacto>;
    FContactosFiltrados: TList<TChatContacto>;
    FMensajes: TList<TChatMensajeItem>;

    procedure AsegurarTablaChat;
    procedure ConstruirUI;
    procedure CargarContactos;
    procedure AplicarFiltroContactos;
    procedure CargarMensajesConversacion(AScrollAlFinal: Boolean = True);
    procedure MarcarLeidosConversacionActual;
    procedure EnviarMensajeActual;

    procedure EdtBuscarContactoChange(Sender: TObject);
    procedure LbContactosDrawItem(Control: TWinControl; Index: Integer;
      Rect: TRect; State: TOwnerDrawState);
    procedure LbContactosClick(Sender: TObject);

    procedure LbMensajesMeasureItem(Control: TWinControl; Index: Integer;
      var Height: Integer);
    procedure LbMensajesDrawItem(Control: TWinControl; Index: Integer;
      Rect: TRect; State: TOwnerDrawState);

    procedure BtnEnviarClick(Sender: TObject);
    procedure BtnCargarMasClick(Sender: TObject);
    procedure BtnRefrescarClick(Sender: TObject);
    procedure MemMensajeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure TmrPollTimer(Sender: TObject);
    procedure FormResize(Sender: TObject);
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure SeleccionarConversacion(AContactId: Integer);
    class function GetTotalNoLeidos(AConn: TFDConnection; AUserId: Integer): Integer;
    class function GetMaxMessageId(AConn: TFDConnection): Int64;
    class function GetUltimoMensajeEntrante(AConn: TFDConnection; AUserId: Integer; ADespuesDeId: Int64;
      out AMsgId: Int64; out ARemitenteId: Integer; out ARemitenteNombre, AMensaje: string;
      out AEsGeneral: Boolean): Boolean;
  end;

  TChatBubbleClickEvent = procedure(Sender: TObject; AContactId: Integer) of object;

  TfrmChatBurbujaToast = class(TForm)
  private
    FContactId: Integer;
    FTitulo: string;
    FSubtitulo: string;
    FMensaje: string;
    FIniciales: string;
    FHora: string;
    FTmrAutoHide: TTimer;
    FCloseRect: TRect;
    FOnOpenChat: TChatBubbleClickEvent;
    procedure OnAutoHideTimer(Sender: TObject);
  protected
    procedure CreateParams(var Params: TCreateParams); override;
    procedure Paint; override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
  public
    constructor Create(AOwner: TComponent); override;
    procedure MostrarMensaje(AOwnerForm: TForm; AContactId: Integer;
      const ARemitenteNombre, AMensaje: string; AEsGeneral: Boolean);
    property OnOpenChat: TChatBubbleClickEvent read FOnOpenChat write FOnOpenChat;
  end;

implementation

uses
  dmg_Main, uAppTheme;

const
  CLR_WA_HEADER   = $005E7807; // Verde oscuro estilo WhatsApp (#075E54 en BGR) -> RGB(7, 94, 84)
  CLR_WA_BG       = $00E2EAEF; // Fondo beige suave (#EFEAE2 en BGR) -> RGB(239, 234, 226)
  CLR_WA_OWN      = $00D3FDD9; // Burbuja propia (#D9FDD3 en BGR) -> RGB(217, 253, 211)
  CLR_WA_OTHER    = $00FFFFFF; // Burbuja recibida
  CLR_WA_BADGE    = $005ED325; // Verde brillante (#25D366 en BGR)

{ TfrmChatInterno }

constructor TfrmChatInterno.Create(AOwner: TComponent);
begin
  inherited CreateNew(AOwner);
  FContactosAll := TList<TChatContacto>.Create;
  FContactosFiltrados := TList<TChatContacto>.Create;
  FMensajes := TList<TChatMensajeItem>.Create;
  FCurrentUserId := StrToIntDef(dmgMain.CurrentUserId, 1);
  FSelectedContactId := 0;
  FSelectedContactName := 'Canal General (Todos)';
  FLastMaxMsgId := 0;
  FLimitMensajes := 150;

  AsegurarTablaChat;
  ConstruirUI;
  TAppTheme.ApplyToForm(Self);

  // Asegurar colores propios del chat tras ApplyToForm
  FPnlChatHeader.Color := RGB(7, 94, 84);
  FPnlChatHeader.ParentBackground := False;
  FLblChatTitulo.Font.Color := clWhite;
  FLblChatSubtitulo.Font.Color := RGB(210, 240, 230);
  FLbMensajes.Color := RGB(239, 234, 226);
  FMemMensaje.CharCase := ecNormal;
  FEdtBuscarContacto.CharCase := ecNormal;

  CargarContactos;
  CargarMensajesConversacion(True);
  FTmrPoll.Enabled := True;
end;

destructor TfrmChatInterno.Destroy;
begin
  if Assigned(FTmrPoll) then
    FTmrPoll.Enabled := False;
  FreeAndNil(FMensajes);
  FreeAndNil(FContactosFiltrados);
  FreeAndNil(FContactosAll);
  inherited Destroy;
end;

procedure TfrmChatInterno.AsegurarTablaChat;
var
  LQry: TFDQuery;
begin
  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;
    LQry.SQL.Text :=
      'CREATE TABLE IF NOT EXISTS `ge_chat_mensajes` (' +
      '  `id` BIGINT(20) NOT NULL AUTO_INCREMENT,' +
      '  `id_remitente` INT(11) NOT NULL,' +
      '  `id_destinatario` INT(11) DEFAULT NULL,' +
      '  `mensaje` TEXT NOT NULL,' +
      '  `leido` TINYINT(1) NOT NULL DEFAULT 0,' +
      '  `fecha_envio` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,' +
      '  `fecha_lectura` DATETIME DEFAULT NULL,' +
      '  PRIMARY KEY (`id`),' +
      '  KEY `idx_chat_conv` (`id_remitente`, `id_destinatario`, `id`),' +
      '  KEY `idx_chat_dest_leido` (`id_destinatario`, `leido`, `id`)' +
      ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
    LQry.ExecSQL;
  finally
    LQry.Free;
  end;
end;

procedure TfrmChatInterno.ConstruirUI;
var
  LPnlSearch: TPanel;
  LLblLeftTitle: TLabel;
begin
  Caption := 'Chat Interno';
  Width := 1050;
  Height := 680;
  Position := poScreenCenter;
  OnResize := FormResize;

  // Panel izquierdo: Contactos
  FPnlLeft := TPanel.Create(Self);
  FPnlLeft.Parent := Self;
  FPnlLeft.Align := alLeft;
  FPnlLeft.Width := 285;
  FPnlLeft.BevelOuter := bvNone;

  FPnlLeftHeader := TPanel.Create(Self);
  FPnlLeftHeader.Parent := FPnlLeft;
  FPnlLeftHeader.Align := alTop;
  FPnlLeftHeader.Height := 48;
  FPnlLeftHeader.BevelOuter := bvNone;
  FPnlLeftHeader.Color := RGB(7, 94, 84);
  FPnlLeftHeader.ParentBackground := False;

  LLblLeftTitle := TLabel.Create(Self);
  LLblLeftTitle.Parent := FPnlLeftHeader;
  LLblLeftTitle.Left := 14;
  LLblLeftTitle.Top := 14;
  LLblLeftTitle.Caption := 'Conversaciones';
  LLblLeftTitle.Font.Name := 'Segoe UI';
  LLblLeftTitle.Font.Size := 11;
  LLblLeftTitle.Font.Style := [fsBold];
  LLblLeftTitle.Font.Color := clWhite;

  LPnlSearch := TPanel.Create(Self);
  LPnlSearch.Parent := FPnlLeft;
  LPnlSearch.Align := alTop;
  LPnlSearch.Height := 40;
  LPnlSearch.BevelOuter := bvNone;
  LPnlSearch.Padding.SetBounds(8, 6, 8, 6);

  FEdtBuscarContacto := TEdit.Create(Self);
  FEdtBuscarContacto.Parent := LPnlSearch;
  FEdtBuscarContacto.Align := alClient;
  FEdtBuscarContacto.TextHint := 'Buscar usuario...';
  FEdtBuscarContacto.OnChange := EdtBuscarContactoChange;

  FLbContactos := TListBox.Create(Self);
  FLbContactos.Parent := FPnlLeft;
  FLbContactos.Align := alClient;
  FLbContactos.Style := lbOwnerDrawFixed;
  FLbContactos.ItemHeight := 54;
  FLbContactos.BorderStyle := bsNone;
  FLbContactos.OnDrawItem := LbContactosDrawItem;
  FLbContactos.OnClick := LbContactosClick;

  FSplitter := TSplitter.Create(Self);
  FSplitter.Parent := Self;
  FSplitter.Align := alLeft;
  FSplitter.Width := 4;

  // Panel derecho: Conversación
  FPnlRight := TPanel.Create(Self);
  FPnlRight.Parent := Self;
  FPnlRight.Align := alClient;
  FPnlRight.BevelOuter := bvNone;

  FPnlChatHeader := TPanel.Create(Self);
  FPnlChatHeader.Parent := FPnlRight;
  FPnlChatHeader.Align := alTop;
  FPnlChatHeader.Height := 48;
  FPnlChatHeader.BevelOuter := bvNone;
  FPnlChatHeader.Color := RGB(7, 94, 84);
  FPnlChatHeader.ParentBackground := False;

  FLblChatTitulo := TLabel.Create(Self);
  FLblChatTitulo.Parent := FPnlChatHeader;
  FLblChatTitulo.Left := 14;
  FLblChatTitulo.Top := 6;
  FLblChatTitulo.Font.Name := 'Segoe UI';
  FLblChatTitulo.Font.Size := 11;
  FLblChatTitulo.Font.Style := [fsBold];
  FLblChatTitulo.Font.Color := clWhite;
  FLblChatTitulo.Caption := 'Canal General (Todos)';

  FLblChatSubtitulo := TLabel.Create(Self);
  FLblChatSubtitulo.Parent := FPnlChatHeader;
  FLblChatSubtitulo.Left := 14;
  FLblChatSubtitulo.Top := 26;
  FLblChatSubtitulo.Font.Name := 'Segoe UI';
  FLblChatSubtitulo.Font.Size := 8;
  FLblChatSubtitulo.Font.Color := RGB(210, 240, 230);
  FLblChatSubtitulo.Caption := 'Mensajes visibles para todos los usuarios del ERP';

  FBtnRefrescar := TButton.Create(Self);
  FBtnRefrescar.Parent := FPnlChatHeader;
  FBtnRefrescar.Top := 10;
  FBtnRefrescar.Width := 90;
  FBtnRefrescar.Height := 28;
  FBtnRefrescar.Left := FPnlChatHeader.ClientWidth - 102;
  FBtnRefrescar.Anchors := [akTop, akRight];
  FBtnRefrescar.Caption := 'Actualizar';
  FBtnRefrescar.OnClick := BtnRefrescarClick;

  FBtnCargarMas := TButton.Create(Self);
  FBtnCargarMas.Parent := FPnlChatHeader;
  FBtnCargarMas.Top := 10;
  FBtnCargarMas.Width := 125;
  FBtnCargarMas.Height := 28;
  FBtnCargarMas.Left := FPnlChatHeader.ClientWidth - 235;
  FBtnCargarMas.Anchors := [akTop, akRight];
  FBtnCargarMas.Caption := 'Ver anteriores';
  FBtnCargarMas.OnClick := BtnCargarMasClick;

  // Área inferior de escritura
  FPnlInput := TPanel.Create(Self);
  FPnlInput.Parent := FPnlRight;
  FPnlInput.Align := alBottom;
  FPnlInput.Height := 72;
  FPnlInput.BevelOuter := bvNone;
  FPnlInput.Padding.SetBounds(10, 8, 10, 8);

  FBtnEnviar := TButton.Create(Self);
  FBtnEnviar.Parent := FPnlInput;
  FBtnEnviar.Align := alRight;
  FBtnEnviar.Width := 96;
  FBtnEnviar.Caption := 'Enviar';
  FBtnEnviar.Font.Style := [fsBold];
  FBtnEnviar.OnClick := BtnEnviarClick;

  FMemMensaje := TMemo.Create(Self);
  FMemMensaje.Parent := FPnlInput;
  FMemMensaje.Align := alClient;
  FMemMensaje.AlignWithMargins := True;
  FMemMensaje.Margins.SetBounds(0, 0, 8, 0);
  FMemMensaje.ScrollBars := ssVertical;
  FMemMensaje.Font.Name := 'Segoe UI';
  FMemMensaje.Font.Size := 10;
  FMemMensaje.OnKeyDown := MemMensajeKeyDown;

  // Lista de mensajes (burbujas)
  FLbMensajes := TListBox.Create(Self);
  FLbMensajes.Parent := FPnlRight;
  FLbMensajes.Align := alClient;
  FLbMensajes.Style := lbOwnerDrawVariable;
  FLbMensajes.BorderStyle := bsNone;
  FLbMensajes.Color := RGB(239, 234, 226);
  FLbMensajes.OnMeasureItem := LbMensajesMeasureItem;
  FLbMensajes.OnDrawItem := LbMensajesDrawItem;

  // Polling en tiempo real cada 2.5s
  FTmrPoll := TTimer.Create(Self);
  FTmrPoll.Interval := 2500;
  FTmrPoll.Enabled := False;
  FTmrPoll.OnTimer := TmrPollTimer;
end;

class function TfrmChatInterno.GetTotalNoLeidos(AConn: TFDConnection; AUserId: Integer): Integer;
var
  LQry: TFDQuery;
begin
  Result := 0;
  if (not Assigned(AConn)) or (not AConn.Connected) or (AUserId <= 0) then
    Exit;
  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := AConn;
    LQry.SQL.Text :=
      'SELECT COUNT(*) FROM information_schema.tables ' +
      'WHERE table_schema = DATABASE() AND table_name = ''ge_chat_mensajes''';
    LQry.Open;
    if LQry.Fields[0].AsInteger = 0 then
      Exit;
    LQry.Close;

    LQry.SQL.Text :=
      'SELECT COUNT(*) FROM ge_chat_mensajes WHERE id_destinatario = :yo AND leido = 0';
    LQry.ParamByName('yo').AsInteger := AUserId;
    LQry.Open;
    Result := LQry.Fields[0].AsInteger;
  except
    Result := 0;
  end;
  LQry.Free;
end;

procedure TfrmChatInterno.CargarContactos;
var
  LQry: TFDQuery;
  LItem: TChatContacto;
begin
  FContactosAll.Clear;

  // 1. Canal General
  LItem.UsuarioId := 0;
  LItem.Nombre := 'Canal General (Todos)';
  LItem.Username := 'todos';
  LItem.NoLeidos := 0;
  LItem.UltimoMensaje := 'Mensajes visibles para todo el equipo';
  LItem.UltimaFecha := 0;

  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;

    LQry.SQL.Text :=
      'SELECT m.mensaje, m.fecha_envio, u.nombre_completo ' +
      'FROM ge_chat_mensajes m ' +
      'LEFT JOIN ge_usuarios u ON u.id = m.id_remitente ' +
      'WHERE m.id_destinatario IS NULL OR m.id_destinatario = 0 ' +
      'ORDER BY m.id DESC LIMIT 1';
    LQry.Open;
    if not LQry.IsEmpty then
    begin
      LItem.UltimoMensaje := Trim(LQry.FieldByName('nombre_completo').AsString) + ': ' +
        StringReplace(LQry.FieldByName('mensaje').AsString, sLineBreak, ' ', [rfReplaceAll]);
      LItem.UltimaFecha := LQry.FieldByName('fecha_envio').AsDateTime;
    end;
    LQry.Close;
    FContactosAll.Add(LItem);

    // 2. Usuarios activos con resumen de no leídos y último mensaje
    LQry.SQL.Text :=
      'SELECT u.id, u.nombre_completo, u.username, ' +
      '  (SELECT COUNT(*) FROM ge_chat_mensajes m1 ' +
      '   WHERE m1.id_remitente = u.id AND m1.id_destinatario = :yo1 AND m1.leido = 0) AS no_leidos, ' +
      '  (SELECT m2.mensaje FROM ge_chat_mensajes m2 ' +
      '   WHERE (m2.id_remitente = u.id AND m2.id_destinatario = :yo2) ' +
      '      OR (m2.id_remitente = :yo3 AND m2.id_destinatario = u.id) ' +
      '   ORDER BY m2.id DESC LIMIT 1) AS ultimo_msg, ' +
      '  (SELECT MAX(m3.fecha_envio) FROM ge_chat_mensajes m3 ' +
      '   WHERE (m3.id_remitente = u.id AND m3.id_destinatario = :yo4) ' +
      '      OR (m3.id_remitente = :yo5 AND m3.id_destinatario = u.id)) AS ultima_fecha ' +
      'FROM ge_usuarios u ' +
      'WHERE u.activo = 1 AND u.id <> :yo6 ' +
      'ORDER BY (no_leidos > 0) DESC, ultima_fecha DESC, u.nombre_completo ASC';
    LQry.ParamByName('yo1').AsInteger := FCurrentUserId;
    LQry.ParamByName('yo2').AsInteger := FCurrentUserId;
    LQry.ParamByName('yo3').AsInteger := FCurrentUserId;
    LQry.ParamByName('yo4').AsInteger := FCurrentUserId;
    LQry.ParamByName('yo5').AsInteger := FCurrentUserId;
    LQry.ParamByName('yo6').AsInteger := FCurrentUserId;
    LQry.Open;

    while not LQry.Eof do
    begin
      LItem.UsuarioId := LQry.FieldByName('id').AsInteger;
      LItem.Nombre := Trim(LQry.FieldByName('nombre_completo').AsString);
      if LItem.Nombre = '' then
        LItem.Nombre := Trim(LQry.FieldByName('username').AsString);
      LItem.Username := Trim(LQry.FieldByName('username').AsString);
      LItem.NoLeidos := LQry.FieldByName('no_leidos').AsInteger;
      LItem.UltimoMensaje := StringReplace(Trim(LQry.FieldByName('ultimo_msg').AsString), sLineBreak, ' ', [rfReplaceAll]);
      if LItem.UltimoMensaje = '' then
        LItem.UltimoMensaje := '@' + LItem.Username;
      if not LQry.FieldByName('ultima_fecha').IsNull then
        LItem.UltimaFecha := LQry.FieldByName('ultima_fecha').AsDateTime
      else
        LItem.UltimaFecha := 0;

      FContactosAll.Add(LItem);
      LQry.Next;
    end;
  finally
    LQry.Free;
  end;

  AplicarFiltroContactos;
end;

procedure TfrmChatInterno.AplicarFiltroContactos;
var
  LFiltro: string;
  C: TChatContacto;
  I, LSelIdx: Integer;
begin
  LFiltro := LowerCase(Trim(FEdtBuscarContacto.Text));
  FContactosFiltrados.Clear;
  FLbContactos.Items.BeginUpdate;
  try
    FLbContactos.Items.Clear;
    LSelIdx := 0;
    for I := 0 to FContactosAll.Count - 1 do
    begin
      C := FContactosAll[I];
      if (LFiltro = '') or (C.UsuarioId = 0) or
         (Pos(LFiltro, LowerCase(C.Nombre)) > 0) or
         (Pos(LFiltro, LowerCase(C.Username)) > 0) then
      begin
        FContactosFiltrados.Add(C);
        FLbContactos.Items.Add(C.Nombre);
        if C.UsuarioId = FSelectedContactId then
          LSelIdx := FContactosFiltrados.Count - 1;
      end;
    end;
    if (LSelIdx >= 0) and (LSelIdx < FLbContactos.Items.Count) then
      FLbContactos.ItemIndex := LSelIdx;
  finally
    FLbContactos.Items.EndUpdate;
  end;
end;

procedure TfrmChatInterno.MarcarLeidosConversacionActual;
var
  LQry: TFDQuery;
begin
  if FSelectedContactId <= 0 then
    Exit;

  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;
    LQry.SQL.Text :=
      'UPDATE ge_chat_mensajes SET leido = 1, fecha_lectura = NOW() ' +
      'WHERE id_remitente = :rem AND id_destinatario = :yo AND leido = 0';
    LQry.ParamByName('rem').AsInteger := FSelectedContactId;
    LQry.ParamByName('yo').AsInteger := FCurrentUserId;
    LQry.ExecSQL;
  finally
    LQry.Free;
  end;
end;

procedure TfrmChatInterno.CargarMensajesConversacion(AScrollAlFinal: Boolean);
var
  LQry: TFDQuery;
  LRec: TChatMensajeItem;
  LSep: TChatMensajeItem;
  LUltDia, LDiaMsg: TDate;
  LMaxId: Int64;
begin
  MarcarLeidosConversacionActual;

  FMensajes.Clear;
  LMaxId := 0;
  LUltDia := 0;

  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;

    if FSelectedContactId = 0 then
    begin
      LQry.SQL.Text :=
        'SELECT * FROM (' +
        '  SELECT m.id, m.id_remitente, m.mensaje, m.fecha_envio, CAST(m.leido AS SIGNED) AS leido, ' +
        '         COALESCE(NULLIF(u.nombre_completo, ''''), u.username, ''Usuario'') AS rem_nombre ' +
        '  FROM ge_chat_mensajes m ' +
        '  LEFT JOIN ge_usuarios u ON u.id = m.id_remitente ' +
        '  WHERE m.id_destinatario IS NULL OR m.id_destinatario = 0 ' +
        '  ORDER BY m.id DESC LIMIT ' + IntToStr(FLimitMensajes) +
        ') t ORDER BY t.id ASC';
    end
    else
    begin
      LQry.SQL.Text :=
        'SELECT * FROM (' +
        '  SELECT m.id, m.id_remitente, m.mensaje, m.fecha_envio, CAST(m.leido AS SIGNED) AS leido, ' +
        '         COALESCE(NULLIF(u.nombre_completo, ''''), u.username, ''Usuario'') AS rem_nombre ' +
        '  FROM ge_chat_mensajes m ' +
        '  LEFT JOIN ge_usuarios u ON u.id = m.id_remitente ' +
        '  WHERE (m.id_remitente = :yo1 AND m.id_destinatario = :otro1) ' +
        '     OR (m.id_remitente = :otro2 AND m.id_destinatario = :yo2) ' +
        '  ORDER BY m.id DESC LIMIT ' + IntToStr(FLimitMensajes) +
        ') t ORDER BY t.id ASC';
      LQry.ParamByName('yo1').AsInteger := FCurrentUserId;
      LQry.ParamByName('otro1').AsInteger := FSelectedContactId;
      LQry.ParamByName('otro2').AsInteger := FSelectedContactId;
      LQry.ParamByName('yo2').AsInteger := FCurrentUserId;
    end;
    LQry.Open;

    while not LQry.Eof do
    begin
      LDiaMsg := Trunc(LQry.FieldByName('fecha_envio').AsDateTime);
      if LDiaMsg <> LUltDia then
      begin
        LUltDia := LDiaMsg;
        LSep.Id := 0;
        LSep.EsSeparadorFecha := True;
        LSep.FechaEnvio := LDiaMsg;
        if LDiaMsg = Date then
          LSep.Texto := 'Hoy'
        else if LDiaMsg = Date - 1 then
          LSep.Texto := 'Ayer'
        else
          LSep.Texto := FormatDateTime('dd/mm/yyyy', LDiaMsg);
        FMensajes.Add(LSep);
      end;

      LRec.Id := LQry.FieldByName('id').AsLargeInt;
      if LRec.Id > LMaxId then
        LMaxId := LRec.Id;
      LRec.EsSeparadorFecha := False;
      LRec.RemitenteId := LQry.FieldByName('id_remitente').AsInteger;
      LRec.RemitenteNombre := LQry.FieldByName('rem_nombre').AsString;
      LRec.Texto := LQry.FieldByName('mensaje').AsString;
      LRec.FechaEnvio := LQry.FieldByName('fecha_envio').AsDateTime;
      var LFldLeido := LQry.FieldByName('leido');
      if LFldLeido is TBooleanField then
        LRec.Leido := LFldLeido.AsBoolean
      else
        LRec.Leido := LFldLeido.AsInteger <> 0;
      LRec.EsPropio := (LRec.RemitenteId = FCurrentUserId);
      FMensajes.Add(LRec);

      LQry.Next;
    end;

    // Obtener el máximo ID global para polling
    LQry.Close;
    LQry.SQL.Text := 'SELECT COALESCE(MAX(id), 0) FROM ge_chat_mensajes';
    LQry.Open;
    if LQry.Fields[0].AsLargeInt > FLastMaxMsgId then
      FLastMaxMsgId := LQry.Fields[0].AsLargeInt;
  finally
    LQry.Free;
  end;

  FLbMensajes.Items.BeginUpdate;
  try
    FLbMensajes.Items.Clear;
    for var I := 0 to FMensajes.Count - 1 do
      FLbMensajes.Items.Add(FMensajes[I].Texto);
  finally
    FLbMensajes.Items.EndUpdate;
  end;

  if AScrollAlFinal and (FLbMensajes.Items.Count > 0) then
  begin
    FLbMensajes.ItemIndex := FLbMensajes.Items.Count - 1;
    FLbMensajes.TopIndex := Max(0, FLbMensajes.Items.Count - 1);
  end;
end;

procedure TfrmChatInterno.EnviarMensajeActual;
var
  LTexto: string;
  LQry: TFDQuery;
begin
  LTexto := Trim(FMemMensaje.Text);
  if LTexto = '' then
    Exit;

  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;
    LQry.SQL.Text :=
      'INSERT INTO ge_chat_mensajes (id_remitente, id_destinatario, mensaje, leido, fecha_envio) ' +
      'VALUES (:rem, :dest, :msg, 0, NOW())';
    LQry.ParamByName('rem').AsInteger := FCurrentUserId;
    if FSelectedContactId > 0 then
      LQry.ParamByName('dest').AsInteger := FSelectedContactId
    else
    begin
      LQry.ParamByName('dest').DataType := ftInteger;
      LQry.ParamByName('dest').Clear;
    end;
    LQry.ParamByName('msg').AsWideString := LTexto;
    LQry.ExecSQL;
  finally
    LQry.Free;
  end;

  FMemMensaje.Clear;
  FMemMensaje.SetFocus;
  CargarMensajesConversacion(True);
  CargarContactos;
end;

procedure TfrmChatInterno.EdtBuscarContactoChange(Sender: TObject);
begin
  AplicarFiltroContactos;
end;

procedure TfrmChatInterno.LbContactosClick(Sender: TObject);
var
  LIdx: Integer;
  LC: TChatContacto;
begin
  LIdx := FLbContactos.ItemIndex;
  if (LIdx < 0) or (LIdx >= FContactosFiltrados.Count) then
    Exit;

  LC := FContactosFiltrados[LIdx];
  FSelectedContactId := LC.UsuarioId;
  FSelectedContactName := LC.Nombre;
  FLimitMensajes := 150;

  FLblChatTitulo.Caption := LC.Nombre;
  if LC.UsuarioId = 0 then
    FLblChatSubtitulo.Caption := 'Mensajes visibles para todos los usuarios del ERP'
  else
    FLblChatSubtitulo.Caption := 'Conversación privada con @' + LC.Username;

  CargarMensajesConversacion(True);
  CargarContactos;
end;

procedure TfrmChatInterno.LbContactosDrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
  LC: TChatContacto;
  LCanvas: TCanvas;
  LAvatarRect, LBadgeRect, LTextRect: TRect;
  LIniciales, LBadgeTxt: string;
  LParts: TArray<string>;
begin
  if (Index < 0) or (Index >= FContactosFiltrados.Count) then
    Exit;

  LC := FContactosFiltrados[Index];
  LCanvas := FLbContactos.Canvas;

  if LC.UsuarioId = FSelectedContactId then
    LCanvas.Brush.Color := RGB(230, 242, 239)
  else
    LCanvas.Brush.Color := clWhite;
  LCanvas.FillRect(Rect);

  // Separador inferior sutil
  LCanvas.Pen.Color := RGB(235, 235, 235);
  LCanvas.MoveTo(Rect.Left + 56, Rect.Bottom - 1);
  LCanvas.LineTo(Rect.Right, Rect.Bottom - 1);

  // Avatar circular
  LAvatarRect := System.Types.Rect(Rect.Left + 10, Rect.Top + 9, Rect.Left + 46, Rect.Top + 45);
  LCanvas.Pen.Style := psClear;
  if LC.UsuarioId = 0 then
    LCanvas.Brush.Color := RGB(7, 94, 84)
  else
    LCanvas.Brush.Color := RGB(45, 130, 180);
  LCanvas.Ellipse(LAvatarRect);
  LCanvas.Pen.Style := psSolid;

  if LC.UsuarioId = 0 then
    LIniciales := '#'
  else
  begin
    LParts := Trim(LC.Nombre).Split([' '], TStringSplitOptions.ExcludeEmpty);
    if Length(LParts) >= 2 then
      LIniciales := UpperCase(Copy(LParts[0], 1, 1) + Copy(LParts[1], 1, 1))
    else
      LIniciales := UpperCase(Copy(LC.Nombre, 1, 2));
  end;

  LCanvas.Font.Name := 'Segoe UI';
  LCanvas.Font.Size := 10;
  LCanvas.Font.Style := [fsBold];
  LCanvas.Font.Color := clWhite;
  LCanvas.Brush.Style := bsClear;
  DrawText(LCanvas.Handle, PChar(LIniciales), Length(LIniciales), LAvatarRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE);

  // Nombre
  LCanvas.Font.Color := RGB(30, 30, 30);
  LCanvas.Font.Size := 9;
  LCanvas.Font.Style := [fsBold];
  LTextRect := System.Types.Rect(Rect.Left + 56, Rect.Top + 8, Rect.Right - 44, Rect.Top + 26);
  DrawText(LCanvas.Handle, PChar(LC.Nombre), Length(LC.Nombre), LTextRect, DT_LEFT or DT_SINGLELINE or DT_END_ELLIPSIS);

  // Último mensaje
  LCanvas.Font.Color := RGB(110, 110, 110);
  LCanvas.Font.Size := 8;
  LCanvas.Font.Style := [];
  LTextRect := System.Types.Rect(Rect.Left + 56, Rect.Top + 28, Rect.Right - 44, Rect.Top + 46);
  DrawText(LCanvas.Handle, PChar(LC.UltimoMensaje), Length(LC.UltimoMensaje), LTextRect, DT_LEFT or DT_SINGLELINE or DT_END_ELLIPSIS);

  // Badge de no leídos
  if LC.NoLeidos > 0 then
  begin
    LBadgeTxt := IntToStr(LC.NoLeidos);
    LBadgeRect := System.Types.Rect(Rect.Right - 34, Rect.Top + 17, Rect.Right - 10, Rect.Top + 37);
    LCanvas.Brush.Style := bsSolid;
    LCanvas.Brush.Color := CLR_WA_BADGE;
    LCanvas.Pen.Style := psClear;
    LCanvas.RoundRect(LBadgeRect.Left, LBadgeRect.Top, LBadgeRect.Right, LBadgeRect.Bottom, 10, 10);
    LCanvas.Pen.Style := psSolid;
    LCanvas.Brush.Style := bsClear;
    LCanvas.Font.Color := clWhite;
    LCanvas.Font.Style := [fsBold];
    DrawText(LCanvas.Handle, PChar(LBadgeTxt), Length(LBadgeTxt), LBadgeRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE);
  end;
  LCanvas.Brush.Style := bsSolid;
end;

procedure TfrmChatInterno.LbMensajesMeasureItem(Control: TWinControl; Index: Integer;
  var Height: Integer);
var
  LM: TChatMensajeItem;
  LCalcRect: TRect;
  LMaxBubbleW: Integer;
  LTextH: Integer;
begin
  Height := 48;
  if (Index < 0) or (Index >= FMensajes.Count) then
    Exit;

  LM := FMensajes[Index];
  if LM.EsSeparadorFecha then
  begin
    Height := 30;
    Exit;
  end;

  LMaxBubbleW := Max(220, Round(FLbMensajes.ClientWidth * 0.66) - 24);
  FLbMensajes.Canvas.Font.Name := 'Segoe UI';
  FLbMensajes.Canvas.Font.Size := 10;
  FLbMensajes.Canvas.Font.Style := [];
  LCalcRect := System.Types.Rect(0, 0, LMaxBubbleW, 0);
  DrawText(FLbMensajes.Canvas.Handle, PChar(LM.Texto), Length(LM.Texto), LCalcRect, DT_CALCRECT or DT_WORDBREAK);
  LTextH := LCalcRect.Height;

  Height := LTextH + 34;
  if (FSelectedContactId = 0) and (not LM.EsPropio) then
    Height := Height + 18; // espacio para nombre del remitente en Canal General
end;

procedure TfrmChatInterno.LbMensajesDrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
  LM: TChatMensajeItem;
  LCanvas: TCanvas;
  LMaxBubbleW, LBubbleW, LBubbleH, LHeaderH: Integer;
  LCalcRect, LBubbleRect, LTextRect, LMetaRect, LSepRect: TRect;
  LMetaTxt: string;
begin
  if (Index < 0) or (Index >= FMensajes.Count) then
    Exit;

  LM := FMensajes[Index];
  LCanvas := FLbMensajes.Canvas;
  LCanvas.Brush.Color := RGB(239, 234, 226);
  LCanvas.FillRect(Rect);

  if LM.EsSeparadorFecha then
  begin
    LSepRect := System.Types.Rect((Rect.Left + Rect.Right) div 2 - 55, Rect.Top + 4, (Rect.Left + Rect.Right) div 2 + 55, Rect.Bottom - 4);
    LCanvas.Brush.Color := RGB(225, 220, 212);
    LCanvas.Pen.Style := psClear;
    LCanvas.RoundRect(LSepRect.Left, LSepRect.Top, LSepRect.Right, LSepRect.Bottom, 10, 10);
    LCanvas.Pen.Style := psSolid;
    LCanvas.Brush.Style := bsClear;
    LCanvas.Font.Name := 'Segoe UI';
    LCanvas.Font.Size := 8;
    LCanvas.Font.Style := [fsBold];
    LCanvas.Font.Color := RGB(85, 85, 85);
    DrawText(LCanvas.Handle, PChar(LM.Texto), Length(LM.Texto), LSepRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE);
    LCanvas.Brush.Style := bsSolid;
    Exit;
  end;

  LMaxBubbleW := Max(220, Round(FLbMensajes.ClientWidth * 0.66));
  LCanvas.Font.Name := 'Segoe UI';
  LCanvas.Font.Size := 10;
  LCanvas.Font.Style := [];
  LCalcRect := System.Types.Rect(0, 0, LMaxBubbleW - 24, 0);
  DrawText(LCanvas.Handle, PChar(LM.Texto), Length(LM.Texto), LCalcRect, DT_CALCRECT or DT_WORDBREAK);

  LHeaderH := 0;
  if (FSelectedContactId = 0) and (not LM.EsPropio) then
    LHeaderH := 18;

  LBubbleW := Max(135, Min(LMaxBubbleW, LCalcRect.Width + 28));
  if LHeaderH > 0 then
  begin
    LCanvas.Font.Size := 8;
    LCanvas.Font.Style := [fsBold];
    LBubbleW := Max(LBubbleW, LCanvas.TextWidth(LM.RemitenteNombre) + 28);
  end;
  LBubbleH := Rect.Height - 6;

  if LM.EsPropio then
    LBubbleRect := System.Types.Rect(Rect.Right - LBubbleW - 14, Rect.Top + 3, Rect.Right - 14, Rect.Top + 3 + LBubbleH)
  else
    LBubbleRect := System.Types.Rect(Rect.Left + 14, Rect.Top + 3, Rect.Left + 14 + LBubbleW, Rect.Top + 3 + LBubbleH);

  LCanvas.Pen.Color := RGB(205, 205, 200);
  if LM.EsPropio then
    LCanvas.Brush.Color := CLR_WA_OWN
  else
    LCanvas.Brush.Color := CLR_WA_OTHER;
  LCanvas.RoundRect(LBubbleRect.Left, LBubbleRect.Top, LBubbleRect.Right, LBubbleRect.Bottom, 12, 12);

  LCanvas.Brush.Style := bsClear;

  // Remitente en Canal General
  if LHeaderH > 0 then
  begin
    LCanvas.Font.Name := 'Segoe UI';
    LCanvas.Font.Size := 8;
    LCanvas.Font.Style := [fsBold];
    LCanvas.Font.Color := RGB(7, 94, 84);
    LTextRect := System.Types.Rect(LBubbleRect.Left + 10, LBubbleRect.Top + 5, LBubbleRect.Right - 10, LBubbleRect.Top + 22);
    DrawText(LCanvas.Handle, PChar(LM.RemitenteNombre), Length(LM.RemitenteNombre), LTextRect, DT_LEFT or DT_SINGLELINE or DT_END_ELLIPSIS);
  end;

  // Texto del mensaje
  LCanvas.Font.Name := 'Segoe UI';
  LCanvas.Font.Size := 10;
  LCanvas.Font.Style := [];
  LCanvas.Font.Color := RGB(25, 25, 25);
  LTextRect := System.Types.Rect(LBubbleRect.Left + 10, LBubbleRect.Top + 7 + LHeaderH, LBubbleRect.Right - 10, LBubbleRect.Bottom - 18);
  DrawText(LCanvas.Handle, PChar(LM.Texto), Length(LM.Texto), LTextRect, DT_LEFT or DT_WORDBREAK);

  // Hora + check de lectura
  LCanvas.Font.Size := 8;
  LMetaTxt := FormatDateTime('hh:nn', LM.FechaEnvio);
  if LM.EsPropio and (FSelectedContactId > 0) then
  begin
    if LM.Leido then
    begin
      LMetaTxt := LMetaTxt + '  ✓✓';
      LCanvas.Font.Color := RGB(30, 136, 229);
    end
    else
    begin
      LMetaTxt := LMetaTxt + '  ✓';
      LCanvas.Font.Color := RGB(120, 120, 120);
    end;
  end
  else
    LCanvas.Font.Color := RGB(120, 120, 120);

  LMetaRect := System.Types.Rect(LBubbleRect.Left + 10, LBubbleRect.Bottom - 17, LBubbleRect.Right - 10, LBubbleRect.Bottom - 3);
  DrawText(LCanvas.Handle, PChar(LMetaTxt), Length(LMetaTxt), LMetaRect, DT_RIGHT or DT_SINGLELINE);
  LCanvas.Brush.Style := bsSolid;
end;

procedure TfrmChatInterno.BtnEnviarClick(Sender: TObject);
begin
  EnviarMensajeActual;
end;

procedure TfrmChatInterno.BtnCargarMasClick(Sender: TObject);
begin
  FLimitMensajes := FLimitMensajes + 150;
  CargarMensajesConversacion(False);
end;

procedure TfrmChatInterno.BtnRefrescarClick(Sender: TObject);
begin
  CargarContactos;
  CargarMensajesConversacion(True);
end;

procedure TfrmChatInterno.MemMensajeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if (Key = VK_RETURN) and not (ssShift in Shift) then
  begin
    Key := 0;
    EnviarMensajeActual;
  end;
end;

procedure TfrmChatInterno.TmrPollTimer(Sender: TObject);
var
  LQry: TFDQuery;
  LNewMaxId: Int64;
begin
  if (not Visible) or (not dmgMain.dbConn.Connected) then
    Exit;

  FTmrPoll.Enabled := False;
  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := dmgMain.dbConn;
    LQry.SQL.Text := 'SELECT COALESCE(MAX(id), 0) FROM ge_chat_mensajes';
    try
      LQry.Open;
      LNewMaxId := LQry.Fields[0].AsLargeInt;
      if LNewMaxId > FLastMaxMsgId then
      begin
        CargarContactos;
        CargarMensajesConversacion(True);
      end
      else if FSelectedContactId > 0 then
      begin
        // Comprobar si algún mensaje propio reciente pasó a leído para actualizar ✓ -> ✓✓
        LQry.Close;
        LQry.SQL.Text :=
          'SELECT COUNT(*) FROM ge_chat_mensajes ' +
          'WHERE id_remitente = :yo AND id_destinatario = :otro AND leido = 1 AND fecha_lectura >= DATE_SUB(NOW(), INTERVAL 6 SECOND)';
        LQry.ParamByName('yo').AsInteger := FCurrentUserId;
        LQry.ParamByName('otro').AsInteger := FSelectedContactId;
        LQry.Open;
        if LQry.Fields[0].AsInteger > 0 then
          CargarMensajesConversacion(False);
      end;
    except
      // Ignorar cortes puntuales de red en polling
    end;
  finally
    LQry.Free;
    FTmrPoll.Enabled := True;
  end;
end;

procedure TfrmChatInterno.FormResize(Sender: TObject);
begin
  if Assigned(FLbMensajes) then
    FLbMensajes.Invalidate;
end;

procedure TfrmChatInterno.SeleccionarConversacion(AContactId: Integer);
var
  I: Integer;
begin
  FEdtBuscarContacto.Text := '';
  CargarContactos;
  FSelectedContactId := AContactId;
  FLimitMensajes := 150;

  for I := 0 to FContactosFiltrados.Count - 1 do
  begin
    if FContactosFiltrados[I].UsuarioId = AContactId then
    begin
      FLbContactos.ItemIndex := I;
      FSelectedContactName := FContactosFiltrados[I].Nombre;
      FLblChatTitulo.Caption := FContactosFiltrados[I].Nombre;
      if AContactId = 0 then
        FLblChatSubtitulo.Caption := 'Mensajes visibles para todos los usuarios del ERP'
      else
        FLblChatSubtitulo.Caption := 'Conversación privada con @' + FContactosFiltrados[I].Username;
      Break;
    end;
  end;

  CargarMensajesConversacion(True);
  CargarContactos;
  if CanFocus and FMemMensaje.CanFocus then
    FMemMensaje.SetFocus;
end;

class function TfrmChatInterno.GetMaxMessageId(AConn: TFDConnection): Int64;
var
  LQry: TFDQuery;
begin
  Result := 0;
  if (not Assigned(AConn)) or (not AConn.Connected) then
    Exit;
  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := AConn;
    try
      LQry.SQL.Text :=
        'SELECT COUNT(*) FROM information_schema.tables ' +
        'WHERE table_schema = DATABASE() AND table_name = ''ge_chat_mensajes''';
      LQry.Open;
      if LQry.Fields[0].AsInteger = 0 then
        Exit;
      LQry.Close;

      LQry.SQL.Text := 'SELECT COALESCE(MAX(id), 0) FROM ge_chat_mensajes';
      LQry.Open;
      Result := LQry.Fields[0].AsLargeInt;
    except
      Result := 0;
    end;
  finally
    LQry.Free;
  end;
end;

class function TfrmChatInterno.GetUltimoMensajeEntrante(AConn: TFDConnection;
  AUserId: Integer; ADespuesDeId: Int64; out AMsgId: Int64; out ARemitenteId: Integer;
  out ARemitenteNombre, AMensaje: string; out AEsGeneral: Boolean): Boolean;
var
  LQry: TFDQuery;
begin
  Result := False;
  AMsgId := 0;
  ARemitenteId := 0;
  ARemitenteNombre := '';
  AMensaje := '';
  AEsGeneral := False;

  if (not Assigned(AConn)) or (not AConn.Connected) or (AUserId <= 0) then
    Exit;

  LQry := TFDQuery.Create(nil);
  try
    LQry.Connection := AConn;
    try
      LQry.SQL.Text :=
        'SELECT m.id, m.id_remitente, COALESCE(m.id_destinatario, 0) AS id_dest, m.mensaje, ' +
        '       COALESCE(NULLIF(u.nombre_completo, ''''), u.username, ''Usuario'') AS rem_nombre ' +
        'FROM ge_chat_mensajes m ' +
        'LEFT JOIN ge_usuarios u ON u.id = m.id_remitente ' +
        'WHERE m.id > :last_id ' +
        '  AND m.id_remitente <> :yo1 ' +
        '  AND (m.id_destinatario = :yo2 OR m.id_destinatario IS NULL OR m.id_destinatario = 0) ' +
        'ORDER BY m.id DESC LIMIT 1';
      LQry.ParamByName('last_id').AsLargeInt := ADespuesDeId;
      LQry.ParamByName('yo1').AsInteger := AUserId;
      LQry.ParamByName('yo2').AsInteger := AUserId;
      LQry.Open;
      if not LQry.IsEmpty then
      begin
        AMsgId := LQry.FieldByName('id').AsLargeInt;
        ARemitenteId := LQry.FieldByName('id_remitente').AsInteger;
        ARemitenteNombre := Trim(LQry.FieldByName('rem_nombre').AsString);
        AMensaje := Trim(LQry.FieldByName('mensaje').AsString);
        AEsGeneral := LQry.FieldByName('id_dest').AsInteger = 0;
        Result := True;
      end;
    except
      Result := False;
    end;
  finally
    LQry.Free;
  end;
end;

{ TfrmChatBurbujaToast }

constructor TfrmChatBurbujaToast.Create(AOwner: TComponent);
begin
  inherited CreateNew(AOwner);
  BorderStyle := bsNone;
  FormStyle := fsStayOnTop;
  Width := 340;
  Height := 94;
  Color := clWhite;
  Cursor := crHandPoint;
  DoubleBuffered := True;

  FTmrAutoHide := TTimer.Create(Self);
  FTmrAutoHide.Interval := 8000;
  FTmrAutoHide.Enabled := False;
  FTmrAutoHide.OnTimer := OnAutoHideTimer;
end;

procedure TfrmChatBurbujaToast.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);
  Params.ExStyle := Params.ExStyle or WS_EX_NOACTIVATE or WS_EX_TOOLWINDOW or WS_EX_TOPMOST;
end;

procedure TfrmChatBurbujaToast.MostrarMensaje(AOwnerForm: TForm; AContactId: Integer;
  const ARemitenteNombre, AMensaje: string; AEsGeneral: Boolean);
var
  LParts: TArray<string>;
  LWorkArea: TRect;
  LRgn: HRGN;
begin
  FContactId := AContactId;
  if AEsGeneral then
  begin
    FTitulo := 'Canal General · ' + ARemitenteNombre;
    FSubtitulo := 'Nuevo mensaje en el canal general';
  end
  else
  begin
    FTitulo := ARemitenteNombre;
    FSubtitulo := 'Nuevo mensaje interno';
  end;
  FMensaje := StringReplace(Trim(AMensaje), sLineBreak, ' ', [rfReplaceAll]);
  FHora := FormatDateTime('hh:nn', Now);

  LParts := Trim(ARemitenteNombre).Split([' '], TStringSplitOptions.ExcludeEmpty);
  if Length(LParts) >= 2 then
    FIniciales := UpperCase(Copy(LParts[0], 1, 1) + Copy(LParts[1], 1, 1))
  else
    FIniciales := UpperCase(Copy(ARemitenteNombre, 1, 2));

  // Posicionar en la esquina inferior derecha del monitor / ventana principal
  if Assigned(AOwnerForm) and (AOwnerForm.WindowState <> wsMinimized) then
  begin
    Left := AOwnerForm.Left + AOwnerForm.Width - Width - 28;
    Top := AOwnerForm.Top + AOwnerForm.Height - Height - 92;
  end
  else
  begin
    SystemParametersInfo(SPI_GETWORKAREA, 0, @LWorkArea, 0);
    Left := LWorkArea.Right - Width - 18;
    Top := LWorkArea.Bottom - Height - 18;
  end;

  HandleNeeded;
  LRgn := CreateRoundRectRgn(0, 0, Width + 1, Height + 1, 16, 16);
  SetWindowRgn(Handle, LRgn, True);

  ShowWindow(Handle, SW_SHOWNOACTIVATE);
  Visible := True;
  Invalidate;

  FTmrAutoHide.Enabled := False;
  FTmrAutoHide.Enabled := True;
  MessageBeep(MB_ICONASTERISK);
end;

procedure TfrmChatBurbujaToast.Paint;
var
  LAvatarRect, LTitleRect, LMsgRect, LHoraRect: TRect;
begin
  // Fondo blanco con borde redondeado y franja verde izquierda estilo WhatsApp
  Canvas.Brush.Color := clWhite;
  Canvas.FillRect(ClientRect);

  Canvas.Brush.Color := RGB(37, 211, 102);
  Canvas.FillRect(System.Types.Rect(0, 0, 7, Height));

  Canvas.Pen.Color := RGB(205, 220, 212);
  Canvas.Pen.Width := 1;
  Canvas.Brush.Style := bsClear;
  Canvas.RoundRect(0, 0, Width - 1, Height - 1, 16, 16);

  // Avatar circular
  LAvatarRect := System.Types.Rect(16, 20, 58, 62);
  Canvas.Brush.Style := bsSolid;
  Canvas.Pen.Style := psClear;
  if FContactId = 0 then
    Canvas.Brush.Color := RGB(7, 94, 84)
  else
    Canvas.Brush.Color := RGB(37, 175, 96);
  Canvas.Ellipse(LAvatarRect);
  Canvas.Pen.Style := psSolid;

  Canvas.Brush.Style := bsClear;
  Canvas.Font.Name := 'Segoe UI';
  Canvas.Font.Size := 11;
  Canvas.Font.Style := [fsBold];
  Canvas.Font.Color := clWhite;
  DrawText(Canvas.Handle, PChar(FIniciales), Length(FIniciales), LAvatarRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE);

  // Botón cerrar ✕
  FCloseRect := System.Types.Rect(Width - 26, 6, Width - 6, 24);
  Canvas.Font.Size := 9;
  Canvas.Font.Style := [fsBold];
  Canvas.Font.Color := RGB(140, 140, 140);
  DrawText(Canvas.Handle, '✕', 1, FCloseRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE);

  // Hora
  LHoraRect := System.Types.Rect(Width - 68, 8, Width - 28, 24);
  Canvas.Font.Size := 8;
  Canvas.Font.Style := [];
  Canvas.Font.Color := RGB(120, 120, 120);
  DrawText(Canvas.Handle, PChar(FHora), Length(FHora), LHoraRect, DT_RIGHT or DT_SINGLELINE);

  // Remitente
  LTitleRect := System.Types.Rect(68, 10, Width - 72, 28);
  Canvas.Font.Size := 9;
  Canvas.Font.Style := [fsBold];
  Canvas.Font.Color := RGB(7, 94, 84);
  DrawText(Canvas.Handle, PChar(FTitulo), Length(FTitulo), LTitleRect, DT_LEFT or DT_SINGLELINE or DT_END_ELLIPSIS);

  // Texto del mensaje (hasta 2 líneas)
  LMsgRect := System.Types.Rect(68, 30, Width - 14, 72);
  Canvas.Font.Size := 9;
  Canvas.Font.Style := [];
  Canvas.Font.Color := RGB(45, 45, 45);
  DrawText(Canvas.Handle, PChar(FMensaje), Length(FMensaje), LMsgRect, DT_LEFT or DT_WORDBREAK or DT_END_ELLIPSIS);

  // Pie interactivo
  LMsgRect := System.Types.Rect(68, 72, Width - 14, 88);
  Canvas.Font.Size := 7;
  Canvas.Font.Style := [fsItalic];
  Canvas.Font.Color := RGB(115, 135, 125);
  DrawText(Canvas.Handle, 'Haz clic para responder...', 26, LMsgRect, DT_LEFT or DT_SINGLELINE);
end;

procedure TfrmChatBurbujaToast.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  inherited;
  if Button <> mbLeft then
    Exit;

  FTmrAutoHide.Enabled := False;
  Hide;

  if PtInRect(FCloseRect, Point(X, Y)) then
    Exit;

  if Assigned(FOnOpenChat) then
    FOnOpenChat(Self, FContactId);
end;

procedure TfrmChatBurbujaToast.OnAutoHideTimer(Sender: TObject);
begin
  FTmrAutoHide.Enabled := False;
  Hide;
end;

end.
